MVC设计模式
简介
M:Model:模型--一个功能。用JavaBean实现(登录功能(LoginDao)、注册功能)eg:LoginDao.java
V:View:视图--用于展示以及与用户交互(负责页面的显示-html/css/jsp/js、登录表单、注册表单)eg:index.jsp
C:Controller:控制器--接收请求,将请求跳转到模型进行处理;模型处理完毕后,再将处理结果返回给请求处(分发器,分发模型-将登录表单的登录请求分发给登录模型)可以用jsp实现,eg:check.jsp,但是不推荐,一般建议使用Servlet实现控制器。
mvc
Servlet
Java类必须符合一定的规范:
- 必须继承javax.servlet.http.HttpServlet
b.重写其中的doGet()或doPost()方法
doGet():接受并处理所有get方式提交的请求
doPost():接受并处理所有post方式提交的请求
Servlet要想使用,必须配置
Servlet2.5:web.xml
servlet
项目的根目录:WebContent、src
所在的jsp是在WebContent目录中,因此,发出的请求WelcomeServlet是去请求项目的根目录(用/表示)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>WelcomeServlet</servlet-name> <servlet-class>Util.WelcomeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>WelcomeServlet</servlet-name> <url-pattern>/WelcomeServlet</url-pattern> </servlet-mapping> </web-app>
|
1 2 3 4 5 6 7 8 9 10 11
| public class WelcomeServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doGet(req, resp); }
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); } }
|
1 2 3 4 5 6 7 8 9
| <%@ page import="java.util.Date" %> <html> <head> <title>index</title> </head> <body> <a href="WelcomeServlet">WelcomeServlet</a> </body> </html>
|
Servlet流程:
请求->->根据去匹配中的,然后将请求交由该执行
Servlet3.0:@WebServlet
不需要在web.xml中配置,但需要在Servlet类定义处之上编写注解@WebServlet("/url-pattern")
匹配流程:请求地址与@WebServelt中的值进行匹配,如果匹配成功,则说明请求的就是该注解所对应的类
/的含义
项目根目录:web、src(所有的构建路径)
eg:web中有一个文件index.jsp:...< /a>,则寻找范围:既会在src根目录中找也会在web根目录中找
如果index.jsp中请求的是web中有一个文件index.jsp:...< /a>,则寻找范围:先在src或web中找a目录,然后再在a目录中找abc
/:在web.xml中,/ 代表的是项目根路径(localhost:8080/Project/)
/:在jsp中,/代表的是服务器的根路径(localhost:8080/)
Servlet生命周期
加载
初始化:init(),该方法会在Servlet被加载并实例化以后执行,默认第一次访问Servlet时会被执行,可修改为在tomcat启动时自动执行
修改方法:
servlet2.5:
在web.xml中的中添加1
servlet3.0:
修改@WebServlet(value="/WelcomeServlet",loadOnStartup=1)
服务:service() ->doGet() doPost(),每次调用均执行
销毁:destroy(),Servlet被系统回收时执行,关闭tomcat服务时执行
卸载
Servlet API
由两个软件包组成:对应于HTTP协议的软件包、对应于除HTTP协议外的其它软件包,即Servlet API可以适用于任何通信协议,我们学习的Servlet,是位于javax.servlet.http包中的类和接口,是基础HTTP协议。
Servlet继承关系
ServletConfig:接口
ServletContext getServletContext():获取Servlet上下文对象
String getInitParameter(String name):在当前Servlet范围内,获取名为name的参数值(初始化参数)
ServletContext中的常见方法(application):
getContextPath():相对路径
getRealPath():绝对路径
setAttribute()、getAttribute()
String getInitParameter(String name):在当前web容器范围内,获取名为name的参数值(初始化参数)
eg:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <context-param> <param-name>globalParam</param-name> <param-value>globalValue</param-value> </context-param> <servlet> <servlet-name>WelcomeServlet</servlet-name> <servlet-class>Util.WelcomeServlet</servlet-class> <init-param> <param-name>servletParam</param-name> <param-value>servletValue</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>WelcomeServlet</servlet-name> <url-pattern>/WelcomeServlet</url-pattern> </servlet-mapping> </web-app>
|
在3.0中:@WebServlet(value="/WelcomeServlet",loadOnStartup = 1,initParams = {@WebInitParam(name="paraname",value="Vlaue")}),但全局的不能通过注解配置
HttpServletRequest中的方法:同request,例如setAttribute()、getCookies()、getMethod()
HtppServletResponse中的方法:同response
继承关系图
Servlet使用层面:
在src中创建一个Servlet,然后重写doGet()、doPost()就行了(且doGet()、doPost()具体只用写一个)
MVC案例
登录:
example
login.jsp:
1 2 3 4 5 6 7 8 9 10 11 12 13
| <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Login</title> </head> <body> <form action="LoginServlet" method="post"> 用户名:<input type="text" name="uname"/><br/> 密码: <input type="password" name="upwd"/><br/> <input type="submit"/> </form> </body> </html>
|
Login.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| public class Login { private String name; private String pwd;
public Login(String name, String pwd) { this.name = name; this.pwd = pwd; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getPwd() { return pwd; }
public void setPwd(String pwd) { this.pwd = pwd; } }
|
LoginDao.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
|
public class LoginDao { public static int login(Login login) { final String URL = "jdbc:mysql://localhost:3306/JavaMysql"; final String USERNAME = "root"; final String PWD = ""; int count = -1; PreparedStatement pstmt = null; Connection connection = null; ResultSet rs = null; Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection(URL, USERNAME, PWD); String sql = "select count(*) from login where name=? and pwd=?"; pstmt = connection.prepareStatement(sql); pstmt.setString(1,login.getName()); pstmt.setString(2,login.getPwd()); rs = pstmt.executeQuery(); if(rs.next()){ count=rs.getInt(1); }else{ count = 0; } } catch (ClassNotFoundException e) { e.printStackTrace(); count = -1; } catch (SQLException e) { e.printStackTrace(); count = -1; } catch (Exception e) { e.printStackTrace(); count = -1; } finally { try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); if (connection != null) connection.close(); } catch (SQLException e) { e.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } return count; } } }
|
LoginServlet.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
|
@WebServlet(name = "LoginServlet") public class LoginServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String name = request.getParameter("uname"); String pwd = request.getParameter("upwd"); int result = new LoginDao().login(new Login(name,pwd)); if(result>0){ response.sendRedirect("welcom.jsp"); }else{ response.sendRedirect("login.jsp"); } } }
@WebServlet(name = "LoginServlet") public class LoginServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String name = request.getParameter("uname"); String pwd = request.getParameter("upwd"); int result = LoginDao.login(new Login(name,pwd)); if(result>0){ response.sendRedirect("welcom.jsp"); }else{ response.sendRedirect("login.jsp"); } } }
|