JavaWeb总结(国税)
一、JavaWeb示例
1.1、Servlet Hello World&IDEA创建第一个Servlet
新建项目
选择maven
组织名与项目名
位置,完成
允许自动导入包
添加框架支持,变换成web项目
选择web application
如果没有Web-INF
添加Web容器支持,tomcat
添加tomcat
设置tomcat属性
设置虚拟目录
运行
添加一个Servlet
新建个一个用于存放servlet的包com.tax.action
结果
创建一个servlet
添加Servlet依赖的包
选择要依赖的环境
修改Servlet类,结果如下:
package com.tax.action; import java.io.IOException; import java.io.PrintWriter; //注解,访问路径 @javax.servlet.annotation.WebServlet("/HiServlet") public class HiServlet extends javax.servlet.http.HttpServlet { protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException { doGet(request,response); } protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException { //设置HTTP内容类型 response.setContentType("text/html;charset=utf-8"); //获得输出对象 PrintWriter out=response.getWriter(); //向客户端响应一串字符 out.println("<h2>Hello Servlet!</h2>"); } }
运行结果:
1.2、获得参数
reg.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <!DOCTYPE html> <html> <head> <title>用户注册</title> <meta charset="UTF-8" /> </head> <body> <form method="post" action="Reg"> <h2>用户注册</h2> <p> 姓名:<input type="text" name="name"/> </p> <p> 爱好: <input type="checkbox" name="hobby" value="运动"/>运动 <input type="checkbox" name="hobby" value="电影"/>电影 <input type="checkbox" name="hobby" value="阅读"/>阅读 </p> <p> <input type="submit" value="提交" /> </p> </form> </body> </html>
Reg Servlet
package com.tax.action; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet("/Reg") public class Reg extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置编码 request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); //获得输出对象 PrintWriter out=response.getWriter(); //获得单个参数 String name=request.getParameter("name"); //获得元素name=name的值 out.println("姓名:"+name+"<br/>"); //获得多个参数 String[] hobbies=request.getParameterValues("hobby"); //获得所有name=hobby的值,数组 out.println("爱好:"); for (String hobby:hobbies){ //遍历输出所有的爱好 out.println(hobby); } } }
运行结果:
提交后
1.3、编码处理
前台
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
后台代码
request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8");
字符
String msg = request.getParameter("message"); String str=new String(msg.getBytes("ISO-8859-1"),"UTF-8"); byte []b = ss.getBytes("GBK"); ss = new String(b,"UTF-8");
tomcat
server.xml文件
<Connector port="80" maxThreads="150" minSpareThreads="25" maxSpareThreads="75" enableLookups="false" redirectPort="8443" acceptCount="100" debug="0" connectionTimeout="20000" disableUploadTimeout="true" URIEncoding="UTF-8" />
1.4、重定向、转发与Session
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <% //如果为空则获得空字符,否则取值 String uid = request.getParameter("uid") == null ? "" : request.getParameter("uid"); String pwd = request.getParameter("pwd") == null ? "" : request.getParameter("pwd"); Object msg=request.getAttribute("message")==null?"":request.getAttribute("message"); %> <html> <head> <title>登录</title> </head> <body> <form action="Login" method="post"> <p> 帐号:<input name="uid" value="<%=uid%>"/> </p> <p> 密码:<input name="pwd" type="password" value="<%=pwd%>"/> </p> <p> <input type="submit" value="登录"/> </p> <p> <%=msg.toString()%> </p> </form> </body> </html>
Login Servlet
package com.tax.action; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; @WebServlet("/Login") public class Login extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置编码 request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); //获得输出对象 PrintWriter out=response.getWriter(); //获得单个参数 String uid=request.getParameter("uid"); String pwd=request.getParameter("pwd"); //如果用户名与密码为admin,123456 if(uid.equals("admin")&&pwd.equals("123456")){ //向Session写入当前登录的用户信息 request.getSession().setAttribute("user",uid); //成功,重定向到后台首页,路径变化了,但request,response对象在index.jsp中无法使用 response.sendRedirect("backend/index.jsp"); }else{ //在请求中添加属性 request.setAttribute("message","用户名或密码不正确"); //转发,路径不变,但request与response可以再使用 request.getRequestDispatcher("login.jsp").forward(request,response); } } }
后台backend/index.jsp
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2018/3/14 Time: 11:33 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <% Object user=request.getSession().getAttribute("user"); if(user==null) { response.sendRedirect("../login.jsp"); } %> <html> <head> <title>Title</title> </head> <body> <h2>欢迎您(<%=user+""%>)登录后台!</h2> </body> </html>
运行结果:
二、综合示例
2.1、Oracle数据库与表
create table book ( id int not null primary key, title varchar2(128) not null unique, typename varchar2(128) not null, price numeric(10,2) default(0), state varchar2(10) default('未借出') ) insert into book(id,title,Typename,Price,State) select 1,'零基础学Java(全彩版)','计算机',50.60,'未借出' from dual union select 2,'轻量级Java EE企业应用实战','软件工程',85.30,'未借出' from dual union select 3,'Java并发编程的艺术','软件工程',45.40,'未借出' from dual union select 4,'实战Java高并发程序设计','软件开发',48.70,'未借出' from dual union select 5,'Java程序员面试笔试宝典','神话',38.50,'已借出' from dual union select 6,'Java Web从入门到精通','计算机',71.00,'未借出' from dual union select 7,'Java编程思想(第4版)','计算机',70.10,'已借出' from dual union select 8,'深入理解JAVA虚拟机','神话',65.00,'未借出' from dual union select 9,'从零开始写Java Web框架','计算机',63.20,'已借出' from dual select id, title, typename, price, state from book commit;
2.2、Java Bean
Book.java
package com.tax.model; /**图书*/ public class Book { /**编号*/ private int id; /**书名*/ private String title; /**类型*/ private String typename; /**价格*/ private double price; /**状态*/ private String state; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getTypename() { return typename; } public void setTypename(String typename) { this.typename = typename; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public String getState() { return state; } public void setState(String state) { this.state = state; } }
2.3、BookDao 图书的数据访问层
2.3.1、添加Oracle驱动
2.3.2、封装JDBC数据访问工具类
package com.tax.dao; /** * Created by Administrator on 2017/8/10. */ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class JDBCUtil { public static String DRIVER="oracle.jdbc.driver.OracleDriver"; public static String URL="jdbc:oracle:thin:@127.0.0.1:1521:orcl"; public static String USER_NAME="tax"; public static String PASSWORD="orcl"; //加载驱动 static { try { Class.forName(DRIVER); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private JDBCUtil() { } /** * 获得连接 * * @return */ public static Connection getconnnection() { Connection con = null; try { con = DriverManager.getConnection(URL, USER_NAME, PASSWORD); } catch (SQLException e) { e.printStackTrace(); } return con; } /** * 关闭连接 * * @param rs * @param st * @param con */ public static void close(ResultSet rs, Statement st, Connection con) { try { try { if (rs != null) { rs.close(); } } finally { try { if (st != null) { st.close(); } } finally { if (con != null) con.close(); } } } catch (SQLException e) { e.printStackTrace(); } } /** * 关闭连接 * * @param rs */ public static void close(ResultSet rs) { Statement st = null; Connection con = null; try { try { if (rs != null) { st = rs.getStatement(); rs.close(); } } finally { try { if (st != null) { con = st.getConnection(); st.close(); } } finally { if (con != null) { con.close(); } } } } catch (SQLException e) { e.printStackTrace(); } } /** * 关闭连接 * * @param st * @param con */ public static void close(Statement st, Connection con) { try { try { if (st != null) { st.close(); } } finally { if (con != null) con.close(); } } catch (SQLException e) { e.printStackTrace(); } } /** * insert/update/delete * 增加/更新/删除 * * @param sql 数据库语句 * @param args 可变参数(可以不带参数,可以带0-n个参数) * @return */ public static int update(String sql, Object... args) { int result = 0; Connection con = getconnnection(); PreparedStatement ps = null; try { ps = con.prepareStatement(sql); if (args != null) { for (int i = 0; i < args.length; i++) { ps.setObject((i + 1), args[i]); } } result = ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { close(ps, con); } return result; } /** * query, because need to manually close the resource, so not recommended * for use it * * @param sql * @param args * @return ResultSet */ @Deprecated //注解 public static ResultSet query(String sql, Object... args) { ResultSet result = null; Connection con = getconnnection(); PreparedStatement ps = null; try { ps = con.prepareStatement(sql); if (args != null) { for (int i = 0; i < args.length; i++) { ps.setObject((i + 1), args[i]); } } result = ps.executeQuery(); } catch (SQLException e) { e.printStackTrace(); } return result; } /** * Query a single record * 查询单个记录 * @param sql * @param args * @return Map<String,Object> */ public static Map<String, Object> queryForMap(String sql, Object... args) { Map<String, Object> result = new HashMap<String, Object>(); List<Map<String, Object>> list = queryForList(sql, args); if (list.size() > 0) { result = list.get(0); } return result; } /** * Query a single record * 查询单个记录返回强类型对象 * @param sql * @param args * @return <T> //泛型 */ public static <T> T queryForObject(String sql, Class<T> clz, Object... args) { T result = null; List<T> list = queryForList(sql, clz, args); if (list.size() > 0) { result = list.get(0); } return result; } /** * Query a single record * * @param sql * @param args * @return List<Map<String,Object>> */ public static List<Map<String, Object>> queryForList(String sql, Object... args) { List<Map<String, Object>> result = new ArrayList<Map<String, Object>>(); Connection con = null; ResultSet rs = null; PreparedStatement ps = null; try { con = getconnnection(); ps = con.prepareStatement(sql); if (args != null) { for (int i = 0; i < args.length; i++) { ps.setObject((i + 1), args[i]); } } rs = ps.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); while (rs.next()) { Map<String, Object> map = new HashMap<String, Object>(); for (int i = 1; i <= columnCount; i++) { map.put(rsmd.getColumnLabel(i), rs.getObject(i)); } result.add(map); } } catch (SQLException e) { e.printStackTrace(); } finally { close(rs, ps, con); } return result; } /** * Query records * 查询多个对象,返回强类型集合 * @param sql * @param args * @return List<T> */ public static <T> List<T> queryForList(String sql, Class<T> clz, Object... args) { List<T> result = new ArrayList<T>(); Connection con = null; PreparedStatement ps = null; ResultSet rs = null; try { con = getconnnection(); ps = con.prepareStatement(sql); if (args != null) { for (int i = 0; i < args.length; i++) { ps.setObject((i + 1), args[i]); } } rs = ps.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); while (rs.next()) { T obj = clz.newInstance(); for (int i = 1; i <= columnCount; i++) { String columnName = rsmd.getColumnName(i); String methodName = "set" + columnName.substring(0, 1).toUpperCase() + columnName.substring(1, columnName.length()).toLowerCase(); Method method[] = clz.getMethods(); for (Method meth : method) { if (methodName.equals(meth.getName())) { meth.invoke(obj, rs.getObject(i)); } } } result.add(obj); } } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } finally { close(rs, ps, con); } return result; } }
2.3.3、BookDao访问图书表
package com.tax.dao; import com.tax.model.Book; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * 用于访问数据库中的Book表 */ public class BookDao { /*** * 获得所有的图书 * @return */ public List<Book> getAllBooks() { List<Book> result = null; Connection conn = null; PreparedStatement statement = null; ResultSet set = null; try { //获得连接对象 conn = JDBCUtil.getconnnection(); //创建sql命令对象 statement = conn.prepareStatement("select id, title, typename, price, state from book"); //执行查询返回结果集 set = statement.executeQuery(); result = new ArrayList<Book>(); //遍历结果集 while (set.next()) { Book book = new Book(); //创建图书对象 book.setId(set.getInt("id")); //从结果集中获得当前行列名为id的值转成int类型 book.setTypename(set.getString("typename")); book.setTitle(set.getString("title")); book.setState(set.getString("state")); book.setPrice(set.getDouble("price")); result.add(book); //将图书对象添加到集合中 } } catch (Exception e) { e.printStackTrace(); } finally { JDBCUtil.close(set, statement, conn); } //返回结果 return result; } public static void main(String[] args) { BookDao dao=new BookDao(); for (Book book:dao.getAllBooks()) { System.out.println(book.getTitle()); } } }
2.4、图书列表
Book.jsp
<%@ page import="com.tax.dao.BookDao" %> <%@ page import="com.tax.model.Book" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <% BookDao dao=new BookDao(); %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Book</title> <link rel="stylesheet" type="text/css" href="js/jPicture.min.css" /> <style type="text/css"> * { margin: 0; padding: 0; } #container { width: 1004px; margin: 0 auto; } #header { height: 200px; background: url(images/top.png) no-repeat; } #menu { background: orangered; } #menu a { width: 100px; display: inline-block; background: orangered; height: 30px; text-align: center; line-height: 30px; text-decoration: none; color: white; } #menu a:hover { background: mistyrose; color: orangered; } #banner img { width: 1004px; } #main { clear: both; overflow: hidden; margin-bottom: 10px; } #main #left { width: 30%; float: left; background: lightblue; height: 400px; } #main #right { width: 70%; float: left; } #main .bookitem { width: 30%; float: left; margin-right: 3%; } #footer { clear: both; text-align: center; background: lightsalmon; height: 65px; line-height: 30px; padding-top: 5px; } #left a { width: 100%; display: inline-block; /*行内块标签,行内标签设置宽度无效*/ background: orangered; height: 30px; text-align: center; line-height: 30px; text-decoration: none; /*去下划线*/ color: white; } #banner{ width: 1004px; height: 300px;} </style> </head> <body> <div id="container"> <div id="header"></div> <div id="menu"> <a href="#">图书列表</a> <a href="#">用户登录</a> <a href="#">后台管理</a> <a href="#">图书列表</a> <a href="#">用户登录</a> <a href="#">后台管理</a> </div> <div id="banner"> <div> <div> <a href="#"> <img src="images/adv3.jpg" /> </a> </div> <div> <a href="#"> <img src="images/adv2.jpg" /> </a> </div> <div> <a href="#"> <img src="images/adv1.jpg" /> </a> </div> </div> </div> <div id="main"> <div id="left"> <a href="#">图书列表</a> <a href="#">用户登录</a> <a href="#">后台管理</a> <a href="#">图书列表</a> <a href="#">用户登录</a> <a href="#">后台管理</a> </div> <div id="right"> <%for (Book book: dao.getAllBooks()) {%> <div class="bookitem"> <p class="picture"> <img src="images/book(<%=book.getId()%>).jpg" /> </p> <p class="price"> ¥<%=book.getPrice()%> </p> <p class="title"> <%=book.getTitle()%> </p> <p class="state"> <%=book.getState()%> </p> </div> <%}%> </div> </div> <div id="footer"> <p> 关于我们 | 联系我们 | 联系客服 | 合作招商 | 商家帮助 | 营销中心 | 手机书店 | 友情链接 | 销售联盟 </p> <p> Copyright @ 2004 - 2018 国税JavaEE版权所有 </p> </div> </div> <script src="js/jquery-1.11.3.min.js" type="text/javascript" charset="utf-8"></script> <script src="js/jPicture.min.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> jPicture("#banner", { type: "slide", autoplay: 2000 }); </script> </body> </html>
结果:
2.5、JSTL+MVC展示图书
BookController控制器
package com.tax.action; import com.tax.dao.BookDao; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/Book") public class BookController extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BookDao dao=new BookDao(); request.setAttribute("books",dao.getAllBooks()); request.getRequestDispatcher("booklist.jsp").forward(request,response); } }
booklist.jsp视图
<%@ page import="com.tax.dao.BookDao" %> <%@ page import="com.tax.model.Book" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Book</title> <link rel="stylesheet" type="text/css" href="js/jPicture.min.css"/> <style type="text/css"> * { margin: 0; padding: 0; } #container { width: 1004px; margin: 0 auto; } #header { height: 200px; background: url(images/top.png) no-repeat; } #menu { background: orangered; } #menu a { width: 100px; display: inline-block; background: orangered; height: 30px; text-align: center; line-height: 30px; text-decoration: none; color: white; } #menu a:hover { background: mistyrose; color: orangered; } #banner img { width: 1004px; } #main { clear: both; overflow: hidden; margin-bottom: 10px; } #main #left { width: 30%; float: left; background: lightblue; height: 400px; } #main #right { width: 70%; float: left; } #main .bookitem { width: 30%; float: left; margin-right: 3%; } #footer { clear: both; text-align: center; background: lightsalmon; height: 65px; line-height: 30px; padding-top: 5px; } #left a { width: 100%; display: inline-block; /*行内块标签,行内标签设置宽度无效*/ background: orangered; height: 30px; text-align: center; line-height: 30px; text-decoration: none; /*去下划线*/ color: white; } #banner { width: 1004px; height: 300px; } </style> </head> <body> <div id="container"> <div id="header"></div> <div id="menu"> <a href="#">图书列表</a> <a href="#">用户登录</a> <a href="#">后台管理</a> <a href="#">图书列表</a> <a href="#">用户登录</a> <a href="#">后台管理</a> </div> <div id="banner"> <div> <div> <a href="#"> <img src="images/adv3.jpg"/> </a> </div> <div> <a href="#"> <img src="images/adv2.jpg"/> </a> </div> <div> <a href="#"> <img src="images/adv1.jpg"/> </a> </div> </div> </div> <div id="main"> <div id="left"> <a href="#">图书列表</a> <a href="#">用户登录</a> <a href="#">后台管理</a> <a href="#">图书列表</a> <a href="#">用户登录</a> <a href="#">后台管理</a> </div> <div id="right"> <c:forEach var="book" items="${books}"> <div class="bookitem"> <p class="picture"> <img src="images/book(${book.id}).jpg"/> </p> <p class="price"> ¥${book.price} </p> <p class="title"> ${book.title} </p> <p class="state"> ${book.state} </p> </div> </c:forEach> </div> </div> <div id="footer"> <p> 关于我们 | 联系我们 | 联系客服 | 合作招商 | 商家帮助 | 营销中心 | 手机书店 | 友情链接 | 销售联盟 </p> <p> Copyright @ 2004 - 2018 国税JavaEE版权所有 </p> </div> </div> <script src="js/jquery-1.11.3.min.js" type="text/javascript" charset="utf-8"></script> <script src="js/jPicture.min.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> jPicture("#banner", { type: "slide", autoplay: 2000 }); </script> </body> </html>
结果:
2.6、添加图书
addBook.jsp
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2018/3/14 Time: 17:07 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>添加图书</title> </head> <body> <form method="post" action="AddBook"> <h2>添加图书</h2> <fieldset> <legend>图书详细</legend> <p> 书名:<input type="text" name="title"/> </p> <p> 类型:<select name="typename"> <option value="计算机">计算机</option> <option value="神话">神话</option> <option value="软件工程">软件工程</option> </select> </p> <p> 价格:<input type="text" name="price"/> </p> <p> 状态:<input type="checkbox" name="state" value="已借出"/>已借出 <input type="checkbox" name="state" value="未借出"/>未借出 </p> <p> 描述:<textarea name="memo" cols="50" rows="5"></textarea> </p> <p> <input type="submit" value="添加" /> </p> <P> <%=request.getAttribute("msg")==null?"":request.getAttribute("msg")%> </P> </fieldset> </form> </body> </html>
AddBook Servlet
package com.tax.action; import com.tax.dao.BookDao; import com.tax.model.Book; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/AddBook") public class AddBook extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置编码 request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); String title=request.getParameter("title"); String state=request.getParameter("state"); String price=request.getParameter("price"); String typename=request.getParameter("typename"); Book book=new Book(); book.setTitle(title); book.setState(state); book.setTypename(typename); book.setPrice(Double.parseDouble(price)); BookDao dao=new BookDao(); if(dao.add(book)>0) { response.sendRedirect("book.jsp"); }else { request.setAttribute("msg","添加失败"); request.getRequestDispatcher("addBook.jsp").forward(request,response); } } }
运行结果
三、总结
day1
|