Servlet--慕课网笔记
来源:互联网 发布:高斯滤波matlab算法 编辑:程序博客网 时间:2024/06/08 08:03
第1章 Servlet基础
1-1 Servlet概述
Servlet基础
- 什么是Servlet
- Tomcat容器等级
- 手工编写第一个Servlet
- 使用MyEclipse编写Servlet
- Servlet声明周期
- Servlet获取九大内置对象
- Servlet与表单
- Servlet路径跳转
- 阶段项目
什么是Servlet 先有JSP还是先有Servlet?
我可以负责任的告诉大家先有Servlet。没错,Jsp的前身就是Servlet。
Servlet是在服务端运行的小程序。一个Servlet就是一个Java类,并且
可以通过“请求-响应”编程模型来访问的这个驻留在服务器内里的Servlet
程序。
1-2 Tomcat容器等级
Tomcat容器等级
Tomcat的容器分为四个等级,Servlet的容器管理Context容器,一个
Context对应一个Web工程。
Tomcat->Container容器->Engine->HOST->Servlet容器->Context
1-3 手工编写第一个Servlet
手工编写第一个Servlet
- 继承HttpServlet
- 重写doGet()或者doPost()方法
- 在web.xml中注册Servlet
Servlet ->三个方法Init() service() destory()
|
GenericServlet(Abstract Class) ->与协议无关的Servlet
|
HttpServlet(Abstract Class) ->实现了http协议的servlet
|
自定义Servlet ->一般重写(覆盖)doGet(),doPost()方法
public class HelloServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest requset, HttpServletResponse response) throws ServletException, IOException { System.out.println("处理Get()请求..."); PrintWriter out = response.getWriter(); response.setContentType("text/html;charset=utf-8"); out.println("<Strong>Hello Servlet!</Strong><br>"); } @Override protected void doPost(HttpServletRequest requset, HttpServletResponse response) throws ServletException, IOException { System.out.println("处理Post()请求..."); PrintWriter out = response.getWriter(); response.setContentType("text/html;charset=utf-8"); out.println("<Strong>Hello Servlet!</Strong><br>"); }}
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/servlet/HelloServlet</url-pattern> </servlet-mapping></web-app>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <h1>第一个Servlet小例子</h1> <hr> <a href="servlet/HelloServlet">Get方式请求HelloServlet</a><br> <form action="servlet/HelloServlet" method="post"> <input type="submit" value="Post方式请求HelloServlet"/> </form> </body></html>
1-4 使用MyEclipse编写Servlet
使用M有Eclipse编写第一个Servlet
- src->new->Servlet
- 重写doGet()或者doPost()
- 部署运行
public class HelloServlet extends HttpServlet { /** * Constructor of the object. */ public HelloServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("处理get请求..."); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.println("<strong>Hello Servlet!</strong>"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("处理post请求..."); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.println("<strong>Hello Servlet!</strong>"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here }}
<?xml version="1.0" encoding="UTF-8"?><web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>HelloServlet</servlet-name> <servlet-class>servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/servlet/HelloServlet</url-pattern> </servlet-mapping></web-app>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <h1>第一个Servlet小例子</h1> <hr> <a href="servlet/HelloServlet">Get方式请求HelloServlet</a><br> <form action="servlet/HelloServlet" method="post"> <input type="submit" value="Post方式请求HelloServlet"/> </form> </body></html>
1-5 练习题
假设在helloapp应用中有一个HelloServlet类,它在 web.xml文件中的配置如下:
<servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>org.javathinker.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/hello</url-pattern></servlet-mapping>
那么在浏览器端访问HelloServlet的URL是什么?
http://localhost:8080/helloapp/hello
localhost是服务器主机名,也可以是IP地址127.0.0.1;8080是tomcat服务器的端口号;helloapp是web工程的上下文地址ContexRoot(一般情况下与web工程名一致);最后是标签中的内容。
1-6 Servlet执行流程和生命周期
- servlet执行流程
- 使用MyEclipse编写第一个Servlet
Get方式请求HelloServlet -> Get方式请求HelloServlet
/servlet/HelloServlet
servlet.HelloServlet
public class HelloServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest requset, HttpServletResponse response) throws ServletException, IOException { System.out.println("处理Get()请求...");
Servlet生命周期
- 舒适化阶段,调用init()方法
- 响应客户端请求阶段,调用service()方法。由service()方法根据提交
方式选择执行doGet()或者doPost()方法。 - 终止阶段,调用destroy()方法。
1-7 练习题
在Java EE中Servlet是在服务器端运行以处理客户端请求而做出的响应的程序。下列选项中属于Servlet生命周期阶段的是
加载和实例化、初始化、服务和销毁
1-8 练习题
编写Servlet的doPost方法时,需要抛出异常为
ServletException, IOException
1-9 Tomcat装载Servlet的三种情况
在下列时刻Servlet容器装载Servlet
- Servlet容器启动时刻自动装载某些Servlet,实现它只需在web.xml文件中的
之间添加如下代码:1
数字越小表示优先级别越高。 - 在Servlet容器启动后,客户端首次向Servlet发送请求。
- Servlet类文件被更新后,重新装载Servlet。
public class TestServlet1 extends HttpServlet { /** * Constructor of the object. */ public TestServlet1() { System.out.println("TestServlet1构造方法被执行...."); } /** * Destruction of the servlet. <br> */ public void destroy() { System.out.println("TestServlet1销毁方法被执行...."); } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("TestServlet1的doGet()方法被执行..."); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.println("<h1>大家好,我是TestServlet1!</h1>"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("TestServlet1的doPost()方法被执行..."); doGet(request,response); //让doPost()执行与doGet()相同的操作。 } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here System.out.println("TestServlet1的初始化方法被执行...."); }}
public class TestServlet2 extends HttpServlet { /** * Constructor of the object. */ public TestServlet2() { System.out.println("TestServlet2构造方法被执行...."); } /** * Destruction of the servlet. <br> */ public void destroy() { System.out.println("TestServlet2销毁方法被执行...."); } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("TestServlet2的doGet()方法被执行..."); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.println("<h1>您好,我是TestServlet2</h1>"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("TestServlet2的doPost()方法被执行..."); doGet(request,response); //让doPost()执行与doGet()相同的操作 } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { System.out.println("TestServlet2的初始化方法被执行...."); }}
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name></display-name> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>TestServlet1</servlet-name> <servlet-class>servlet.TestServlet1</servlet-class> <load-on-startup>2</load-on-startup> </servlet> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>TestServlet2</servlet-name> <servlet-class>servlet.TestServlet2</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>TestServlet1</servlet-name> <url-pattern>/servlet/TestServlet1</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>TestServlet2</servlet-name> <url-pattern>/servlet/TestServlet2</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <h1>Servlet生命周期</h1> <hr> <a href="servlet/TestServlet1">以Get方式请求TestServlet1</a> </body></html>
1-10 Servlet与JSP内置对象的对应关系
1-11 Servlet获取表单数据
//用户实体类public class Users { private String username; //用户名 private String mypassword; //密码 private String email; //电子邮箱 private String gender; //性别 private Date birthday; //出生日期 private String[] favorites; //爱好 private String introduce; //自我介绍 private boolean flag; //是否接受协议 public Users() { } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getMypassword() { return mypassword; } public void setMypassword(String mypassword) { this.mypassword = mypassword; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String[] getFavorites() { return favorites; } public void setFavorites(String[] favorites) { this.favorites = favorites; } public String getIntroduce() { return introduce; } public void setIntroduce(String introduce) { this.introduce = introduce; } public boolean isFlag() { return flag; } public void setFlag(boolean flag) { this.flag = flag; }}
public class RegServlet extends HttpServlet { /** * Constructor of the object. */ public RegServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); Users u = new Users(); String username,mypassword,gender,email,introduce,isAccept; Date birthday; String[] favorites; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); try { username = request.getParameter("username"); mypassword = request.getParameter("mypassword"); gender = request.getParameter("gender"); email = request.getParameter("email"); introduce = request.getParameter("introduce"); birthday = sdf.parse(request.getParameter("birthday")); if(request.getParameterValues("isAccpet")!=null) { isAccept = request.getParameter("isAccept"); } else { isAccept = "false"; } //用来获取多个复选按钮的值 favorites = request.getParameterValues("favorite"); u.setUsername(username); u.setMypassword(mypassword); u.setGender(gender); u.setEmail(email); u.setFavorites(favorites); u.setIntroduce(introduce); if(isAccept.equals("true")) { u.setFlag(true); } else { u.setFlag(false); } u.setBirthday(birthday); //把注册成功的用户对象保存在session中 request.getSession().setAttribute("regUser", u); //跳转到注册成功页面 request.getRequestDispatcher("../userinfo.jsp").forward(request,response); } catch(Exception ex) { ex.printStackTrace(); } } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here }}
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name></display-name> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>RegServlet</servlet-name> <servlet-class>servlet.RegServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>RegServlet</servlet-name> <url-pattern>/servlet/RegServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>My JSP 'reg.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <style type="text/css"> .label{ width: 20% } .controler{ width: 80% } </style> <script type="text/javascript" src="js/Calendar3.js"></script> </head> <body> <h1>用户注册</h1> <hr> <form name="regForm" action="servlet/RegServlet" method="post" > <table border="0" width="800" cellspacing="0" cellpadding="0"> <tr> <td class="lalel">用户名:</td> <td class="controler"><input type="text" name="username" /></td> </tr> <tr> <td class="label">密码:</td> <td class="controler"><input type="password" name="mypassword" ></td> </tr> <tr> <td class="label">确认密码:</td> <td class="controler"><input type="password" name="confirmpass" ></td> </tr> <tr> <td class="label">电子邮箱:</td> <td class="controler"><input type="text" name="email" ></td> </tr> <tr> <td class="label">性别:</td> <td class="controler"><input type="radio" name="gender" checked="checked" value="Male">男<input type="radio" name="gender" value="Female">女</td> </tr> <tr> <td class="label">出生日期:</td> <td class="controler"> <input name="birthday" type="text" id="control_date" size="10" maxlength="10" onclick="new Calendar().show(this);" readonly="readonly" /> </td> </tr> <tr> <td class="label">爱好:</td> <td class="controler"> <input type="checkbox" name="favorite" value="nba"> NBA <input type="checkbox" name="favorite" value="music"> 音乐 <input type="checkbox" name="favorite" value="movie"> 电影 <input type="checkbox" name="favorite" value="internet"> 上网 </td> </tr> <tr> <td class="label">自我介绍:</td> <td class="controler"> <textarea name="introduce" rows="10" cols="40"></textarea> </td> </tr> <tr> <td class="label">接受协议:</td> <td class="controler"> <input type="checkbox" name="isAccept" value="true">是否接受霸王条款 </td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" value="注册"/> <input type="reset" value="取消"/> </td> </tr> </table> </form> </body></html>
<%@ page language="java" import="java.util.*,java.text.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>My JSP 'userinfo.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <style type="text/css"> .title{ width: 30%; background-color: #CCC; font-weight: bold; } .content{ width:70%; background-color: #CBCFE5; } </style> </head> <body> <h1>用户信息</h1> <hr> <center> <jsp:useBean id="regUser" class="entity.Users" scope="session"/> <table width="600" cellpadding="0" cellspacing="0" border="1"> <tr> <td class="title">用户名:</td> <td class="content"> <jsp:getProperty name="regUser" property="username"/></td> </tr> <tr> <td class="title">密码:</td> <td class="content"> <jsp:getProperty name="regUser" property="mypassword"/></td> </tr> <tr> <td class="title">性别:</td> <td class="content"> <jsp:getProperty name="regUser" property="gender"/></td> </tr> <tr> <td class="title">E-mail:</td> <td class="content"> <jsp:getProperty name="regUser" property="email"/></td> </tr> <tr> <td class="title">出生日期:</td> <td class="content"> <% SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日"); String date = sdf.format(regUser.getBirthday()); %> <%=date%> </td> </tr> <tr> <td class="title">爱好:</td> <td class="content"> <% String[] favorites = regUser.getFavorites(); for(String f:favorites) { %> <%=f%> <% } %> </td> </tr> <tr> <td class="title">自我介绍:</td> <td class="content"> <jsp:getProperty name="regUser" property="introduce"/></td> </tr> <tr> <td class="title">是否介绍协议:</td> <td class="content"> <jsp:getProperty name="regUser" property="flag"/></td> </tr> </table> </center> </body></html>
1-12 练习题
在J2EE中,对于HttpServlet类的描述,不正确的是
我们自己编写的Servlet继承了HttpServlet类,一般只需覆盖doPost或者doGet方法,不必覆盖service( )方法,因为一个sevrvice( )方法是空的。
HttpServlet类扩展了GenericServlet类,实现了GenericServlet类的抽象方法
sevrvice( )
HttpServlet类有两个sevrvice( )方法
我们自己编写的Servlet继承了HttpServlet类,一般只需覆盖doPost或者doGet方法,不必覆盖sevrvice( )方法.因为一个sevrvice( )方法会调用doPost或者doGet方法
该选项描述错误,不覆盖service()方法,不是因为该方法是空,而是因为sevrvice( )方法会调用doPost或者doGet方法。
1-13 Servlet路径跳转
Servlet路径跳转
- 绝对路径:放之四海而皆准的路径
- 相对路径:相对于当前资源的路径
public class HelloServlet extends HttpServlet { /** * Constructor of the object. */ public HelloServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.println("<h1>您好,我是HelloServlet!</h1>"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here }}
public class TestServlet extends HttpServlet { /** * Constructor of the object. */ public TestServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //请求重定向方式跳转到test.jsp,当前路径是ServletPathDirection/servlet/ //response.sendRedirect("test.jsp"); //使用request.getContextPath获得上下文对象 //response.sendRedirect(request.getContextPath()+"/test.jsp"); //服务器内部跳转,这里的斜线表示项目的根目录 //request.getRequestDispatcher("/test.jsp").forward(request, response); request.getRequestDispatcher("../test.jsp").forward(request, response); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here }}
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name></display-name> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>HelloServlet</servlet-name> <servlet-class>servlet.HelloServlet</servlet-class> </servlet> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>TestServlet</servlet-name> <servlet-class>servlet.TestServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <!--url-pattern处必须以/开头,这里的/表示项目的根目录 --> <url-pattern>/servlet/HelloServlet</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>TestServlet</servlet-name> <url-pattern>/servlet/TestServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <h1>Servlet路径跳转</h1> <hr> <!--使用相对路径访问HelloServlet --> <!-- /servlet/HelloServlet 第一个/表示服务器的根目录 --> <a href="servlet/HelloServlet">访问HelloServlet!</a><br> <!-- 使用绝对路径 访问HelloServlet,可以使用path变量:path变量表示项目的根目录--> <a href="<%=path%>/servlet/HelloServlet">访问HelloServlet!</a><br> <!--表单中action的URL地址写法,与超链接方式完全相同。 --> <a href="servlet/TestServlet">访问TestServlet,跳转到Test.jsp</a> </body></html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <h1>Test.jsp</h1> <hr> </body></html>
1-14 阶段案例
//用户类public class Users { private String username; private String password; public Users() { } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; }}
public class LoginServlet extends HttpServlet { /** * Constructor of the object. */ public LoginServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Users u = new Users(); String username = request.getParameter("username"); String password = request.getParameter("password"); u.setUsername(username); u.setPassword(password); //判断用户名和密码是否合法 if(u.getUsername().equals("admin")&&u.getPassword().equals("admin")) { request.getSession().setAttribute("loginUser", username); response.sendRedirect(request.getContextPath()+"/login_success.jsp"); } else { response.sendRedirect(request.getContextPath()+"/login_failure.jsp"); } } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here }}
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name></display-name> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>LoginServlet</servlet-name> <servlet-class>servlet.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/servlet/LoginServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list></web-app>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><html> <head> <!-- Page title --> <title>imooc - Login</title> <!-- End of Page title --> <!-- Libraries --> <link type="text/css" href="css/login.css" rel="stylesheet" /> <link type="text/css" href="css/smoothness/jquery-ui-1.7.2.custom.html" rel="stylesheet" /> <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="js/easyTooltip.js"></script> <script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script> <!-- End of Libraries --> </head> <body> <div id="container"> <div class="logo"> <a href="#"><img src="assets/logo.png" alt="" /></a> </div> <div id="box"> 登录失败!请检查用户或者密码!<br> <a href="login.jsp">返回登录</a> </div> </div> </body></html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><html> <head> <!-- Page title --> <title>imooc - Login</title> <!-- End of Page title --> <!-- Libraries --> <link type="text/css" href="css/login.css" rel="stylesheet" /> <link type="text/css" href="css/smoothness/jquery-ui-1.7.2.custom.html" rel="stylesheet" /> <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="js/easyTooltip.js"></script> <script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script> <!-- End of Libraries --> </head> <body> <div id="container"> <div class="logo"> <a href="#"><img src="assets/logo.png" alt="" /></a> </div> <div id="box"> <% String loginUser = ""; if(session.getAttribute("loginUser")!=null) { loginUser = session.getAttribute("loginUser").toString(); } %> 欢迎您<font color="red"><%=loginUser%></font>,登录成功! </div> </div> </body></html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><html> <head> <!-- Page title --> <title>imooc - Login</title> <!-- End of Page title --> <!-- Libraries --> <link type="text/css" href="css/login.css" rel="stylesheet" /> <link type="text/css" href="css/smoothness/jquery-ui-1.7.2.custom.html" rel="stylesheet" /> <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="js/easyTooltip.js"></script> <script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script> <!-- End of Libraries --> </head> <body> <div id="container"> <div class="logo"> <a href="#"><img src="assets/logo.png" alt="" /></a> </div> <div id="box"> <form action="servlet/LoginServlet" method="post"> <p class="main"> <label>用户名: </label> <input name="username" value="" /> <label>密码: </label> <input type="password" name="password" value=""> </p> <p class="space"> <input type="submit" value="登录" class="login" style="cursor: pointer;"/> </p> </form> </div> </div> </body></html>
第2章 应用MVC架构实现项目
2-1 获取初始化参数
Servlet高级
- 获取初始化参数
- MVC设计模式
- Model2简介
- 阶段项目
获取初始化参数
在web.xml中配置Servlet时,可以配置一些初始化参数。而在Servlet中可以
通过ServletConfig接口提供的方法来获取这些参数。
public class GetInitParameterServlet extends HttpServlet { private String username;//用户名 private String password; //密码 public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } /** * Constructor of the object. */ public GetInitParameterServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.println("<h2>"+"用户名:"+this.getUsername()+"</h2>"); out.println("<h2>"+"密码:"+this.getPassword()+"</h2>"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here this.setUsername(this.getInitParameter("username")); this.setPassword(this.getInitParameter("password")); }}
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <display-name></display-name> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>GetInitParameterServlet</servlet-name> <servlet-class>servlet.GetInitParameterServlet</servlet-class> <init-param> <param-name>username</param-name> <param-value>admin</param-value> </init-param> <init-param> <param-name>password</param-name> <param-value>123456</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>GetInitParameterServlet</servlet-name> <url-pattern>/servlet/GetInitParameterServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" %><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <h1>获取初始化参数演示案例</h1> <hr> <a href="servlet/GetInitParameterServlet">获取初始化参数Servlet</a> </body></html>
2-2 练习题
从以下哪一个选项中可以获得Servlet的初始化参数
ServletConfig
2-3 MVC模型介绍
MVC
MVC模式:MVC(Model、View、Controller),是软件开发过程中比较流行的
设计思想。旨在分离模型、控制、视图。是一种分层思想的体现。
2-4 Model2模型介绍
Model1简介
浏览器 - JSP JavaBean - 企业数据库
Model2简介
JSP(V)-Servlet(C)-JavaBean(M)-DB
2-5 项目概述
使用servlet技术实现购物车效果
2-6 界面原型效果及界面开发步骤
MVC模型实现(Jsp+Servlet+dao)
创建购物车类
编写Servlet
创建页面层
2-7 购物车类的设计
购物车类(Cart)的设计
- 添加
- 删除
- 计算总金额
//购物车类public class Cart { //购买商品的集合 private HashMap<Items,Integer> goods; //购物车的总金额 private double totalPrice; //构造方法 public Cart(){ goods = new HashMap<Items,Integer>(); totalPrice = 0.0; } public HashMap<Items, Integer> getGoods() { return goods; } public void setGoods(HashMap<Items, Integer> goods) { this.goods = goods; } public double getTotalPrice() { return totalPrice; } public void setTotalPrice(double totalPrice) { this.totalPrice = totalPrice; } //添加商品进购物车 public boolean addGoodsInCart(Items item,int number){ goods.put(item, number); calTotalPrice();//重新计算购物车的总金额 return true; } //删除商品的方法 public boolean removeGoodsFromCart(Items item){ goods.remove(item); calTotalPrice();//重新计算购物车的总金额 return true; } //统计购物车的总金额 public double calTotalPrice(){ double sum = 0.0; Set<Items> keys = goods.keySet(); Iterator<Items> it = keys.iterator(); while(it.hasNext()){ Items i = it.next(); sum += i.getPrice()*goods.get(i); } this.setTotalPrice(sum);//设置购物车的总金额 return sum; }}
2-8 测试购物车类
//购物车类public class Cart { // 购买商品的集合 private HashMap<Items, Integer> goods; // 购物车的总金额 private double totalPrice; // 构造方法 public Cart() { goods = new HashMap<Items, Integer>(); totalPrice = 0.0; } public HashMap<Items, Integer> getGoods() { return goods; } public void setGoods(HashMap<Items, Integer> goods) { this.goods = goods; } public double getTotalPrice() { return totalPrice; } public void setTotalPrice(double totalPrice) { this.totalPrice = totalPrice; } // 添加商品进购物车 public boolean addGoodsInCart(Items item, int number) { goods.put(item, number); calTotalPrice();// 重新计算购物车的总金额 return true; } // 删除商品的方法 public boolean removeGoodsFromCart(Items item) { goods.remove(item); calTotalPrice();// 重新计算购物车的总金额 return true; } // 统计购物车的总金额 public double calTotalPrice() { double sum = 0.0; Set<Items> keys = goods.keySet(); Iterator<Items> it = keys.iterator(); while (it.hasNext()) { Items i = it.next(); sum += i.getPrice() * goods.get(i); } this.setTotalPrice(sum);// 设置购物车的总金额 return sum; } public static void main(String[] args) { // 先创建两个商品对象 Items i1 = new Items(1, "沃特篮球鞋", "温州", 200, 500, "001.jpg"); Items i2 = new Items(2, "李宁运动鞋", "广州", 300, 500, "002.jpg"); Items i3 = new Items(1, "沃特篮球鞋", "温州", 200, 500, "001.jpg"); Cart c = new Cart(); c.addGoodsInCart(i1, 1); c.addGoodsInCart(i2, 2); // 再次购买沃特篮球鞋,购买3双 c.addGoodsInCart(i3, 3); // 变量购物商品的集合 Set<Map.Entry<Items, Integer>> items = c.getGoods().entrySet(); for (Map.Entry<Items, Integer> obj : items) { System.out.println(obj); } System.out.println("购物车的总金额:" + c.getTotalPrice()); }}
2-9 如何保证不添加重复商品进购物车
//购物车类public class Cart { //购买商品的集合 private HashMap<Items,Integer> goods; //购物车的总金额 private double totalPrice; //构造方法 public Cart() { goods = new HashMap<Items,Integer>(); totalPrice = 0.0; } public HashMap<Items, Integer> getGoods() { return goods; } public void setGoods(HashMap<Items, Integer> goods) { this.goods = goods; } public double getTotalPrice() { return totalPrice; } public void setTotalPrice(double totalPrice) { this.totalPrice = totalPrice; } //添加商品进购物车的方法 public boolean addGoodsInCart(Items item ,int number) { if(goods.containsKey(item)) { goods.put(item, goods.get(item)+number); } else { goods.put(item, number); } calTotalPrice(); //重新计算购物车的总金额 return true; } //删除商品的方法 public boolean removeGoodsFromCart(Items item) { goods.remove(item); calTotalPrice(); //重新计算购物车的总金额 return true; } //统计购物车的总金额 public double calTotalPrice() { double sum = 0.0; Set<Items> keys = goods.keySet(); //获得键的集合 Iterator<Items> it = keys.iterator(); //获得迭代器对象 while(it.hasNext()) { Items i = it.next(); sum += i.getPrice()* goods.get(i); } this.setTotalPrice(sum); //设置购物车的总金额 return this.getTotalPrice(); } public static void main(String[] args) { //先创建两个商品对象 Items i1 = new Items(1,"沃特篮球鞋","温州",200,500,"001.jpg"); Items i2 = new Items(2,"李宁运动鞋","广州",300,500,"002.jpg"); Items i3 = new Items(1,"沃特篮球鞋","温州",200,500,"001.jpg"); Cart c = new Cart(); c.addGoodsInCart(i1, 1); c.addGoodsInCart(i2, 2); //再次购买沃特篮球鞋,购买3双 c.addGoodsInCart(i3, 3); //变量购物商品的集合 Set<Map.Entry<Items, Integer>> items= c.getGoods().entrySet(); for(Map.Entry<Items, Integer> obj:items) { System.out.println(obj); } System.out.println("购物车的总金额:"+c.getTotalPrice()); }}
//商品类public class Items { private int id; // 商品编号 private String name; // 商品名称 private String city; // 产地 private int price; // 价格 private int number; // 库存 private String picture; // 商品图片 //保留此不带参数的构造方法 public Items() { } public Items(int id,String name,String city,int price,int number,String picture) { this.id = id; this.name = name; this.city = city; this.picture = picture; this.price = price; this.number = number; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public String getPicture() { return picture; } public void setPicture(String picture) { this.picture = picture; } @Override public int hashCode() { // TODO Auto-generated method stub return this.getId()+this.getName().hashCode(); } @Override public boolean equals(Object obj) { // TODO Auto-generated method stub if(this==obj) { return true; } if(obj instanceof Items) { Items i = (Items)obj; if(this.getId()==i.getId()&&this.getName().equals(i.getName())) { return true; } else { return false; } } else { return false; } } public String toString() { return "商品编号:"+this.getId()+",商品名称:"+this.getName(); }}
2-10 添加商品进购物车
2-11 显示购物车
2-12 商品删除
//商品的业务逻辑类public class ItemsDAO { // 获得所有的商品信息 public ArrayList<Items> getAllItems() { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; ArrayList<Items> list = new ArrayList<Items>(); // 商品集合 try { conn = DBHelper.getConnection(); String sql = "select * from items;"; // SQL语句 stmt = conn.prepareStatement(sql); rs = stmt.executeQuery(); while (rs.next()) { Items item = new Items(); item.setId(rs.getInt("id")); item.setName(rs.getString("name")); item.setCity(rs.getString("city")); item.setNumber(rs.getInt("number")); item.setPrice(rs.getInt("price")); item.setPicture(rs.getString("picture")); list.add(item);// 把一个商品加入集合 } return list; // 返回集合。 } catch (Exception ex) { ex.printStackTrace(); return null; } finally { // 释放数据集对象 if (rs != null) { try { rs.close(); rs = null; } catch (Exception ex) { ex.printStackTrace(); } } // 释放语句对象 if (stmt != null) { try { stmt.close(); stmt = null; } catch (Exception ex) { ex.printStackTrace(); } } } } // 根据商品编号获得商品资料 public Items getItemsById(int id) { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = DBHelper.getConnection(); String sql = "select * from items where id=?;"; // SQL语句 stmt = conn.prepareStatement(sql); stmt.setInt(1, id); rs = stmt.executeQuery(); if (rs.next()) { Items item = new Items(); item.setId(rs.getInt("id")); item.setName(rs.getString("name")); item.setCity(rs.getString("city")); item.setNumber(rs.getInt("number")); item.setPrice(rs.getInt("price")); item.setPicture(rs.getString("picture")); return item; } else { return null; } } catch (Exception ex) { ex.printStackTrace(); return null; } finally { // 释放数据集对象 if (rs != null) { try { rs.close(); rs = null; } catch (Exception ex) { ex.printStackTrace(); } } // 释放语句对象 if (stmt != null) { try { stmt.close(); stmt = null; } catch (Exception ex) { ex.printStackTrace(); } } } } //获取最近浏览的前五条商品信息 public ArrayList<Items> getViewList(String list) { System.out.println("list:"+list); ArrayList<Items> itemlist = new ArrayList<Items>(); int iCount=5; //每次返回前五条记录 if(list!=null&&list.length()>0) { String[] arr = list.split(","); System.out.println("arr.length="+arr.length); //如果商品记录大于等于5条 if(arr.length>=5) { for(int i=arr.length-1;i>=arr.length-iCount;i--) { itemlist.add(getItemsById(Integer.parseInt(arr[i]))); } } else { for(int i=arr.length-1;i>=0;i--) { itemlist.add(getItemsById(Integer.parseInt(arr[i]))); } } return itemlist; } else { return null; } }}
//购物车类public class Cart { //购买商品的集合 private HashMap<Items,Integer> goods; //购物车的总金额 private double totalPrice; //构造方法 public Cart() { goods = new HashMap<Items,Integer>(); totalPrice = 0.0; } public HashMap<Items, Integer> getGoods() { return goods; } public void setGoods(HashMap<Items, Integer> goods) { this.goods = goods; } public double getTotalPrice() { return totalPrice; } public void setTotalPrice(double totalPrice) { this.totalPrice = totalPrice; } //添加商品进购物车的方法 public boolean addGoodsInCart(Items item ,int number) { if(goods.containsKey(item)) { goods.put(item, goods.get(item)+number); } else { goods.put(item, number); } calTotalPrice(); //重新计算购物车的总金额 return true; } //删除商品的方法 public boolean removeGoodsFromCart(Items item) { goods.remove(item); calTotalPrice(); //重新计算购物车的总金额 return true; } //统计购物车的总金额 public double calTotalPrice() { double sum = 0.0; Set<Items> keys = goods.keySet(); //获得键的集合 Iterator<Items> it = keys.iterator(); //获得迭代器对象 while(it.hasNext()) { Items i = it.next(); sum += i.getPrice()* goods.get(i); } this.setTotalPrice(sum); //设置购物车的总金额 return this.getTotalPrice(); } public static void main(String[] args) { //先创建两个商品对象 Items i1 = new Items(1,"沃特篮球鞋","温州",200,500,"001.jpg"); Items i2 = new Items(2,"李宁运动鞋","广州",300,500,"002.jpg"); Items i3 = new Items(1,"沃特篮球鞋","温州",200,500,"001.jpg"); Cart c = new Cart(); c.addGoodsInCart(i1, 1); c.addGoodsInCart(i2, 2); //再次购买沃特篮球鞋,购买3双 c.addGoodsInCart(i3, 3); //变量购物商品的集合 Set<Map.Entry<Items, Integer>> items= c.getGoods().entrySet(); for(Map.Entry<Items, Integer> obj:items) { System.out.println(obj); } System.out.println("购物车的总金额:"+c.getTotalPrice()); }}
//商品类public class Items { private int id; // 商品编号 private String name; // 商品名称 private String city; // 产地 private int price; // 价格 private int number; // 库存 private String picture; // 商品图片 //保留此不带参数的构造方法 public Items() { } public Items(int id,String name,String city,int price,int number,String picture) { this.id = id; this.name = name; this.city = city; this.picture = picture; this.price = price; this.number = number; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public String getPicture() { return picture; } public void setPicture(String picture) { this.picture = picture; } @Override public int hashCode() { // TODO Auto-generated method stub return this.getId()+this.getName().hashCode(); } @Override public boolean equals(Object obj) { // TODO Auto-generated method stub if(this==obj) { return true; } if(obj instanceof Items) { Items i = (Items)obj; if(this.getId()==i.getId()&&this.getName().equals(i.getName())) { return true; } else { return false; } } else { return false; } } public String toString() { return "商品编号:"+this.getId()+",商品名称:"+this.getName(); }}
public class CartServlet extends HttpServlet { private String action ; //表示购物车的动作 ,add,show,delete //商品业务逻辑类的对象 private ItemsDAO idao = new ItemsDAO(); /** * Constructor of the object. */ public CartServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); if(request.getParameter("action")!=null) { this.action = request.getParameter("action"); if(action.equals("add")) //如果是添加商品进购物车 { if(addToCart(request,response)) { request.getRequestDispatcher("/success.jsp").forward(request, response); } else { request.getRequestDispatcher("/failure.jsp").forward(request, response); } } if(action.equals("show"))//如果是显示购物车 { request.getRequestDispatcher("/cart.jsp").forward(request, response); } if(action.equals("delete")) //如果是执行删除购物车中的商品 { if(deleteFromCart(request,response)) { request.getRequestDispatcher("/cart.jsp").forward(request, response); } else { request.getRequestDispatcher("/cart.jsp").forward(request, response); } } } } //添加商品进购物车的方法 private boolean addToCart(HttpServletRequest request, HttpServletResponse response) { String id = request.getParameter("id"); String number = request.getParameter("num"); Items item = idao.getItemsById(Integer.parseInt(id)); //是否是第一次给购物车添加商品,需要给session中创建一个新的购物车对象 if(request.getSession().getAttribute("cart")==null) { Cart cart = new Cart(); request.getSession().setAttribute("cart",cart); } Cart cart = (Cart)request.getSession().getAttribute("cart"); if(cart.addGoodsInCart(item, Integer.parseInt(number))) { return true; } else { return false; } } //从购物车中删除商品 private boolean deleteFromCart(HttpServletRequest request, HttpServletResponse response) { String id = request.getParameter("id"); Cart cart = (Cart)request.getSession().getAttribute("cart"); Items item = idao.getItemsById(Integer.parseInt(id)); if(cart.removeGoodsFromCart(item)) { return true; } else { return false; } } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here }}
public class DBHelper { private static final String driver = "com.mysql.jdbc.Driver"; //数据库驱动 //连接数据库的URL地址 private static final String url="jdbc:mysql://localhost:3306/shopping?useUnicode=true&characterEncoding=UTF-8"; private static final String username="root";//数据库的用户名 private static final String password="root";//数据库的密码 private static Connection conn=null; //静态代码块负责加载驱动 static { try { Class.forName(driver); } catch(Exception ex) { ex.printStackTrace(); } } //单例模式返回数据库连接对象 public static Connection getConnection() throws Exception { if(conn==null) { conn = DriverManager.getConnection(url, username, password); return conn; } return conn; } public static void main(String[] args) { try { Connection conn = DBHelper.getConnection(); if(conn!=null) { System.out.println("数据库连接正常!"); } else { System.out.println("数据库连接异常!"); } } catch(Exception ex) { ex.printStackTrace(); } }}
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name></display-name> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>CartServlet</servlet-name> <servlet-class>servlet.CartServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CartServlet</servlet-name> <url-pattern>/servlet/CartServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%@ page import="entity.Cart" %><%@ page import="entity.Items" %><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>My JSP 'cart.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <link type="text/css" rel="stylesheet" href="css/style1.css" /> <script language="javascript"> function delcfm() { if (!confirm("确认要删除?")) { window.event.returnValue = false; } } </script> </head> <body> <h1>我的购物车</h1> <a href="index.jsp">首页</a> >> <a href="index.jsp">商品列表</a> <hr> <div id="shopping"> <form action="" method=""> <table> <tr> <th>商品名称</th> <th>商品单价</th> <th>商品价格</th> <th>购买数量</th> <th>操作</th> </tr> <% //首先判断session中是否有购物车对象 if(request.getSession().getAttribute("cart")!=null) { %> <!-- 循环的开始 --> <% Cart cart = (Cart)request.getSession().getAttribute("cart"); HashMap<Items,Integer> goods = cart.getGoods(); Set<Items> items = goods.keySet(); Iterator<Items> it = items.iterator(); while(it.hasNext()) { Items i = it.next(); %> <tr name="products" id="product_id_1"> <td class="thumb"><img src="images/<%=i.getPicture()%>" /><a href=""><%=i.getName()%></a></td> <td class="number"><%=i.getPrice() %></td> <td class="price" id="price_id_1"> <span><%=i.getPrice()*goods.get(i) %></span> <input type="hidden" value="" /> </td> <td class="number"> <%=goods.get(i)%> </td> <td class="delete"> <a href="servlet/CartServlet?action=delete&id=<%=i.getId()%>" onclick="delcfm();">删除</a> </td> </tr> <% } %> <!--循环的结束--> </table> <div class="total"><span id="total">总计:<%=cart.getTotalPrice() %>¥</span></div> <% } %> <div class="button"><input type="submit" value="" /></div> </form> </div> </body></html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" %><%@ page import="entity.Items"%><%@ page import="dao.ItemsDAO"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>My JSP 'details.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <link href="css/main.css" rel="stylesheet" type="text/css"> <script type="text/javascript" src="js/lhgcore.js"></script> <script type="text/javascript" src="js/lhgdialog.js"></script> <script type="text/javascript"> function selflog_show(id) { var num = document.getElementById("number").value; J.dialog.get({id: 'haoyue_creat',title: '购物成功',width: 600,height:400, link: '<%=path%>/servlet/CartServlet?id='+id+'&num='+num+'&action=add', cover:true}); } function add() { var num = parseInt(document.getElementById("number").value); if(num<100) { document.getElementById("number").value = ++num; } } function sub() { var num = parseInt(document.getElementById("number").value); if(num>1) { document.getElementById("number").value = --num; } } </script> <style type="text/css"> hr{ border-color:FF7F00; } div{ float:left; margin-left: 30px; margin-right:30px; margin-top: 5px; margin-bottom: 5px; } div dd{ margin:0px; font-size:10pt; } div dd.dd_name { color:blue; } div dd.dd_city { color:#000; } div #cart { margin:0px auto; text-align:right; } span{ padding:0 2px;border:1px #c0c0c0 solid;cursor:pointer; } a{ text-decoration: none; } </style> </head> <body> <h1>商品详情</h1> <a href="index.jsp">首页</a> >> <a href="index.jsp">商品列表</a> <hr> <center> <table width="750" height="60" cellpadding="0" cellspacing="0" border="0"> <tr> <!-- 商品详情 --> <% ItemsDAO itemDao = new ItemsDAO(); Items item = itemDao.getItemsById(Integer.parseInt(request.getParameter("id"))); if(item!=null) { %> <td width="70%" valign="top"> <table> <tr> <td rowspan="5"><img src="images/<%=item.getPicture()%>" width="200" height="160"/></td> </tr> <tr> <td><B><%=item.getName() %></B></td> </tr> <tr> <td>产地:<%=item.getCity()%></td> </tr> <tr> <td>价格:<%=item.getPrice() %>¥</td> </tr> <tr> <td>购买数量:<span id="sub" onclick="sub();">-</span><input type="text" id="number" name="number" value="1" size="2"/><span id="add" onclick="add();">+</span></td> </tr> </table> <div id="cart"> <img src="images/buy_now.png"><a href="javascript:selflog_show(<%=item.getId()%>)"><img src="images/in_cart.png"></a><a href="servlet/CartServlet?action=show"><img src="images/view_cart.jpg"/></a> </div> </td> <% } %> <% String list =""; //从客户端获得Cookies集合 Cookie[] cookies = request.getCookies(); //遍历这个Cookies集合 if(cookies!=null&&cookies.length>0) { for(Cookie c:cookies) { if(c.getName().equals("ListViewCookie")) { list = c.getValue(); } } } list+=request.getParameter("id")+","; //如果浏览记录超过1000条,清零. String[] arr = list.split(","); if(arr!=null&&arr.length>0) { if(arr.length>=1000) { list=""; } } Cookie cookie = new Cookie("ListViewCookie",list); response.addCookie(cookie); %> <!-- 浏览过的商品 --> <td width="30%" bgcolor="#EEE" align="center"> <br> <b><font color="#FF7F00">您浏览过的商品</font></b><br> <!-- 循环开始 --> <% ArrayList<Items> itemlist = itemDao.getViewList(list); if(itemlist!=null&&itemlist.size()>0 ) { System.out.println("itemlist.size="+itemlist.size()); for(Items i:itemlist) { %> <div> <dl> <dt> <a href="details.jsp?id=<%=i.getId()%>"><img src="images/<%=i.getPicture() %>" width="120" height="90" border="1"/></a> </dt> <dd class="dd_name"><%=i.getName() %></dd> <dd class="dd_city">产地:<%=i.getCity() %> 价格:<%=i.getPrice() %> ¥ </dd> </dl> </div> <% } } %> <!-- 循环结束 --> </td> </tr> </table> </center> </body></html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>My JSP 'success.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <center> <img src="images/add_cart_failure.jpg"/> <hr> <br> <br> <br> </center> </body></html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%@ page import="entity.Items"%><%@ page import="dao.ItemsDAO"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <style type="text/css"> hr{ border-color:FF7F00; } div{ float:left; margin: 10px; } div dd{ margin:0px; font-size:10pt; } div dd.dd_name { color:blue; } div dd.dd_city { color:#000; } </style> </head> <body> <h1>商品展示</h1> <hr> <center> <table width="750" height="60" cellpadding="0" cellspacing="0" border="0"> <tr> <td> <!-- 商品循环开始 --> <% ItemsDAO itemsDao = new ItemsDAO(); ArrayList<Items> list = itemsDao.getAllItems(); if(list!=null&&list.size()>0) { for(int i=0;i<list.size();i++) { Items item = list.get(i); %> <div> <dl> <dt> <a href="details.jsp?id=<%=item.getId()%>"><img src="images/<%=item.getPicture()%>" width="120" height="90" border="1"/></a> </dt> <dd class="dd_name"><%=item.getName() %></dd> <dd class="dd_city">产地:<%=item.getCity() %> 价格:¥ <%=item.getPrice() %></dd> </dl> </div> <!-- 商品循环结束 --> <% } } %> </td> </tr> </table> </center> </body></html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>My JSP 'success.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <center> <img src="images/add_cart_success.jpg"/> <hr> <% String id = request.getParameter("id"); String num = request.getParameter("num"); %> 您成功购买了<%=num%>件商品编号为<%=id%>的商品 <br> <br> <br> </center> </body></html>
2-13 练习题
MVC模型包含模型层、视图层和控制器层,在下列组件中扮演控制器角色的是
Servlet
使用MVC模型搭建某网上书店系统设计用户登陆界面,如果你是设计人员你将在MVC模型结构的( )中实现
视图层
视图层关注界面设计。
《JAVA遇见HTML——Servlet篇》视频地址
- Servlet--慕课网笔记
- 【servlet】servlet 笔记
- servlet 理解 --servlet笔记
- servlet笔记
- Servlet笔记
- Servlet笔记
- Servlet笔记
- Servlet 笔记
- servlet笔记
- Servlet笔记
- servlet 笔记
- servlet笔记
- servlet笔记
- Servlet笔记
- servlet笔记
- Servlet笔记
- servlet笔记
- Servlet笔记
- 二叉树
- Android
- Android 网络请求框架Retrofit2.0使用笔记
- 前端框架vue.js 学习
- 基于RESTful API的TCC补偿模式 分布式事务
- Servlet--慕课网笔记
- OneProxy6.1.3 读写分离配置
- opencv3学习(1)
- 动漫收藏
- 仿3D效果的实现
- Big Integer Addition存储在字符串内的整数相加
- iOS开发-由浅至深学习block
- Android中View和ViewGroup介绍
- Android studio上传项目到gitHub(超级详细)