参考书籍:《J2EE开源编程精要15讲》
MVC(Model View Controller),Model(模型)表示业务逻辑层,View(视图)代表表述层,Controller(控制)表示控制层。
在Java Web应用程序中,
View部分一般用JSP和HTML构建。客户在View部分提交请求,在业务逻辑层处理后,把结果返回给View部分显示
Controller部分一般用Servlet组成,把用户的请求发给适当的业务逻辑组件处理;处理后又返回Controller,把结果转发给适当的View组件
Model部分包括业务逻辑层和数据库访问层,一般由JavaBean或EJB(Enterprise JavaBean,企业级JavaBean)构建。数据访问层也叫数据持久层,与数据库打交道,常用JDBC API或Hibernate构建。
示例:
View部分:
index.jsp
1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head> 10 <base href="<%=basePath%>"> 11 12 <title>登陆界面</title> 13 <meta http-equiv="pragma" content="no-cache"> 14 <meta http-equiv="cache-control" content="no-cache"> 15 <meta http-equiv="expires" content="0"> 16 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 17 <meta http-equiv="description" content="This is my page"> 18 <!-- 19 <link rel="stylesheet" type="text/css" href="styles.css"> 20 --> 21 </head> 22 23 <body> 24 <form method="post" action="LoginServlet"> 25 用户名:<input type="text" name="username" size="15"><br><br> 26 密  码:<input type="password" name="password" size="15"><br><br> 27 <input type="submit" name="submit" value="登陆"><br> 28 </form> 29 </body> 30 </html>
main.jsp
1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head> 10 <base href="<%=basePath%>"> 11 12 <title>主页面</title> 13 14 <meta http-equiv="pragma" content="no-cache"> 15 <meta http-equiv="cache-control" content="no-cache"> 16 <meta http-equiv="expires" content="0"> 17 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 18 <meta http-equiv="description" content="This is my page"> 19 <!-- 20 <link rel="stylesheet" type="text/css" href="styles.css"> 21 --> 22 23 </head> 24 25 <body> 26 <h1> 27 <%=session.getAttribute("username") %>,你成功登陆,现已进入主界面! 28 </h1> 29 </body> 30 </html>
register.jsp
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head> 10 <base href="<%=basePath%>"> 11 12 <title>注册页面</title> 13 14 <meta http-equiv="pragma" content="no-cache"> 15 <meta http-equiv="cache-control" content="no-cache"> 16 <meta http-equiv="expires" content="0"> 17 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 18 <meta http-equiv="description" content="This is my page"> 19 <!-- 20 <link rel="stylesheet" type="text/css" href="styles.css"> 21 --> 22 23 </head> 24 25 <body> 26 <h1> 27 <%=session.getAttribute("username") %>,你未能成功登陆。 28 <br>现已进入注册页面,请注册你的信息! 29 </h1> 30 </body> 31 </html>
Controller部分:
LoginServlet.java
1 /** 2 * 控制组件,在web.xml中将<servlet-mapping>标签内的<url-pattern>设置为"/LoginServlet", 3 * 所以能接受来自index.jsp中action="LoginServlet"的表单的HTTP POST请求 4 */ 5 package login; 6 7 import java.io.IOException; 8 import java.io.PrintWriter; 9 10 import javax.servlet.ServletException; 11 import javax.servlet.http.HttpServlet; 12 import javax.servlet.http.HttpServletRequest; 13 import javax.servlet.http.HttpServletResponse; 14 import javax.servlet.http.HttpSession; 15 16 public class LoginServlet extends HttpServlet { 17 18 /** 19 * Constructor of the object. 20 */ 21 public LoginServlet() { 22 super(); 23 } 24 25 /** 26 * Destruction of the servlet. <br> 27 */ 28 public void destroy() { 29 super.destroy(); // Just puts "destroy" string in log 30 // Put your code here 31 } 32 33 /** 34 * The doGet method of the servlet. <br> 35 * 36 * This method is called when a form has its tag value method equals to get. 37 * 38 * @param request the request send by the client to the server 39 * @param response the response send by the server to the client 40 * @throws ServletException if an error occurred 41 * @throws IOException if an error occurred 42 */ 43 public void doGet(HttpServletRequest request, HttpServletResponse response) 44 throws ServletException, IOException { 45 doPost(request,response); 46 47 } 48 49 /** 50 * The doPost method of the servlet. <br> 51 * 52 * This method is called when a form has its tag value method equals to post. 53 * 54 * @param request the request send by the client to the server 55 * @param response the response send by the server to the client 56 * @throws ServletException if an error occurred 57 * @throws IOException if an error occurred 58 */ 59 public void doPost(HttpServletRequest request, HttpServletResponse response) 60 throws ServletException, IOException { 61 62 //获取请求中的用户名和密码 63 String username=request.getParameter("username"); 64 String password=request.getParameter("password"); 65 66 //生成一个Session对象,在main.jsp和register.jsp中可以根据Session对象获取用户名 67 HttpSession session=request.getSession(true); 68 session.removeAttribute("username"); 69 session.setAttribute("username", username); 70 71 //调用业务逻辑组件,检查该用户是否已注册 72 LoginHandler login=new LoginHandler(); 73 boolean mark=login.checkLogin(username,password); 74 75 //根据查询结果跳转 76 if(mark) 77 response.sendRedirect("main.jsp"); 78 else 79 response.sendRedirect("register.jsp"); 80 } 81 82 /** 83 * Initialization of the servlet. <br> 84 * 85 * @throws ServletException if an error occurs 86 */ 87 public void init() throws ServletException { 88 // Put your code here 89 } 90 91 }
Model部分
业务逻辑组件,LoginHandler.java
1 /** 2 * 业务逻辑组件,从数据访问组件DBPool中获得数据库链接,检查用户记录是否存在 3 */ 4 package login; 5 6 import java.sql.*; 7 8 public class LoginHandler { 9 public LoginHandler(){} 10 11 Connection conn; 12 PreparedStatement ps; 13 ResultSet rs; 14 15 public boolean checkLogin(String username,String password){ 16 DBPool con=new DBPool(); 17 try{ 18 conn=con.getConnection(); 19 String sql="select * from UserInfo where username=? and password=?"; 20 ps=conn.prepareStatement(sql); 21 ps.setString(1, username); 22 ps.setString(2, password); 23 rs=ps.executeQuery(); 24 if(rs.next()){ 25 conn.close(); 26 return true; 27 } 28 conn.close(); 29 }catch(SQLException e){ 30 e.printStackTrace(); 31 } 32 return false; 33 } 34 }
数据库访问组件,DBPool.java (MySQL数据库)
1 /** 2 * 数据访问组件,数据库类型为MySQL, 3 * 登陆数据库用户名:"root", 4 * 密码:"root", 5 * 数据库:"user", 6 * 表:"UserInfo" 7 */ 8 package login; 9 10 import java.sql.*; 11 12 public class DBPool { 13 public Connection getConnection() throws SQLException{ 14 Connection con=null; 15 16 try{ 17 Class.forName("com.mysql.jdbc.Driver"); 18 con=DriverManager.getConnection("jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=UTF-8", "root", "root"); 19 }catch(ClassNotFoundException e){ 20 e.printStackTrace(); 21 } 22 return con; 23 } 24 }
配置文件web.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> 3 <display-name>Login_Proj</display-name> 4 <servlet> 5 <description>This is the description of my J2EE component</description> 6 <display-name>This is the display name of my J2EE component</display-name> 7 <servlet-name>LoginServlet</servlet-name> 8 <servlet-class>login.LoginServlet</servlet-class> 9 </servlet> 10 11 <servlet-mapping> 12 <servlet-name>LoginServlet</servlet-name> 13 <url-pattern>/LoginServlet</url-pattern> 14 </servlet-mapping> 15 <welcome-file-list> 16 <welcome-file>index.html</welcome-file> 17 <welcome-file>index.htm</welcome-file> 18 <welcome-file>index.jsp</welcome-file> 19 <welcome-file>default.html</welcome-file> 20 <welcome-file>default.htm</welcome-file> 21 <welcome-file>default.jsp</welcome-file> 22 </welcome-file-list> 23 </web-app>
应用实例 简单登陆系统:http://pan.baidu.com/s/1eQdAGqI
PS:使用环境Win7 64bit+MyEclipse Professional 2014+phpMyAdmin-2.10.3