Java Web编程的主要组件技术——MVC设计模式

时间:2023-12-05 18:45:38

参考书籍:《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

 <%@ page language="java" import="java.util.*" pageEncoding="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>登陆界面</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>
<form method="post" action="LoginServlet">
用户名:<input type="text" name="username" size="15"><br><br>
密&nbsp&nbsp码:<input type="password" name="password" size="15"><br><br>
<input type="submit" name="submit" value="登陆"><br>
</form>
</body>
</html>

  main.jsp

 <%@ page language="java" import="java.util.*" pageEncoding="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>主页面</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>
<%=session.getAttribute("username") %>,你成功登陆,现已进入主界面!
</h1>
</body>
</html>

  register.jsp

 <%@ page language="java" import="java.util.*" pageEncoding="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>注册页面</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>
<%=session.getAttribute("username") %>,你未能成功登陆。
<br>现已进入注册页面,请注册你的信息!
</h1>
</body>
</html>

Controller部分:

  LoginServlet.java

 /**
* 控制组件,在web.xml中将<servlet-mapping>标签内的<url-pattern>设置为"/LoginServlet",
* 所以能接受来自index.jsp中action="LoginServlet"的表单的HTTP POST请求
*/
package login; import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; 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 { //获取请求中的用户名和密码
String username=request.getParameter("username");
String password=request.getParameter("password"); //生成一个Session对象,在main.jsp和register.jsp中可以根据Session对象获取用户名
HttpSession session=request.getSession(true);
session.removeAttribute("username");
session.setAttribute("username", username); //调用业务逻辑组件,检查该用户是否已注册
LoginHandler login=new LoginHandler();
boolean mark=login.checkLogin(username,password); //根据查询结果跳转
if(mark)
response.sendRedirect("main.jsp");
else
response.sendRedirect("register.jsp");
} /**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
} }

Model部分

  业务逻辑组件,LoginHandler.java

 /**
* 业务逻辑组件,从数据访问组件DBPool中获得数据库链接,检查用户记录是否存在
*/
package login; import java.sql.*; public class LoginHandler {
public LoginHandler(){} Connection conn;
PreparedStatement ps;
ResultSet rs; public boolean checkLogin(String username,String password){
DBPool con=new DBPool();
try{
conn=con.getConnection();
String sql="select * from UserInfo where username=? and password=?";
ps=conn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
rs=ps.executeQuery();
if(rs.next()){
conn.close();
return true;
}
conn.close();
}catch(SQLException e){
e.printStackTrace();
}
return false;
}
}

  数据库访问组件,DBPool.java (MySQL数据库)

 /**
* 数据访问组件,数据库类型为MySQL,
* 登陆数据库用户名:"root",
* 密码:"root",
* 数据库:"user",
* 表:"UserInfo"
*/
package login; import java.sql.*; public class DBPool {
public Connection getConnection() throws SQLException{
Connection con=null; try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=UTF-8", "root", "root");
}catch(ClassNotFoundException e){
e.printStackTrace();
}
return con;
}
}

配置文件web.xml

 <?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" 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">
<display-name>Login_Proj</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>login.LoginServlet</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>

应用实例 简单登陆系统:http://pan.baidu.com/s/1eQdAGqI

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