Java Web編程的主要組件技術——MVC設計模式

參考書籍:《J2EE開源編程精要15講》php

 

MVC(Model View Controller),Model(模型)表示業務邏輯層,View(視圖)表明表述層,Controller(控制)表示控制層。css

在Java Web應用程序中,html

  View部分通常用JSP和HTML構建。客戶在View部分提交請求,在業務邏輯層處理後,把結果返回給View部分顯示java

  Controller部分通常用Servlet組成,把用戶的請求發給適當的業務邏輯組件處理;處理後又返回Controller,把結果轉發給適當的View組件mysql

  Model部分包括業務邏輯層和數據庫訪問層,通常由JavaBean或EJB(Enterprise JavaBean,企業級JavaBean)構建。數據訪問層也叫數據持久層,與數據庫打交道,經常使用JDBC API或Hibernate構建。web

 

示例:sql

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&nbsp&nbsp碼:<input type="password" name="password" size="15"><br><br>
27         <input type="submit" name="submit" value="登錄"><br>
28     </form>
29   </body>
30 </html>
View Code

  main.jspsession

 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>
View Code

  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>
View Code

 

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 }
View Code

 

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 }
View Code

  數據庫訪問組件,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 }
View Code

 

配置文件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>
View Code

 

應用實例 簡單登錄系統:http://pan.baidu.com/s/1eQdAGqI

PS:使用環境Win7 64bit+MyEclipse Professional 2014+phpMyAdmin-2.10.3

相關文章
相關標籤/搜索