开发模式Model1中 引入JavaBean来实现对数据库表的对象化操作,初步体现了Java面向对象的精神。但是在Model1中,JSP仍然要同时承担页面的显示,控制程序流程和业务逻辑处理等多项任务。为了从根本上克服Model1模式的缺陷,原Sun公司对Model1进行改造,发展出Model2模式。
Model2模式的工作原理如下,其工作流程如下5个步骤进行。
- Servlet接收浏览器发出的请求
- Servlet根据不同的请求调用相应的JavaBean
- JavaBean按自己的业务逻辑,通过JDBC操作数据库
- Servlet将结果传递给JSP
-
JSP将后台处理的结果呈现给浏览器
实例
login页面
<%--
Created by IntelliJ IDEA.
User: FX50J
Date: 2018/1/21
Time: 22:06
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=gb2312" language="java" %>
<html>
<head>
<title>简易留言板</title>
</head>
<body>
<form action="mainServlet" method="post"> //仅仅将之前的传到validated的数据传到了mainServlet中 对应了Model2模式下 将数据传送到servlet中
<table>
<caption>用户登陆</caption>
<tr>
<td>用户名:</td>
<td>
<input type="text" name="username" size="20"/>
</td>
</tr>
<tr>
<td>密码</td>
<td>
<input type="password" name="password" size="21"/>
</td>
</tr>
</table>
<input type="submit" value="登陆"/>
<input type="reset" value="重置"/>
</form>
如果没有注册单机<a href="">这里</a>注册!
</body>
</html>
UserTable 用以记录登陆收集的信息
package org.easybooks.test.model.vo;
public class UserTable {
//属性
private Integer id;
private String username;
private String password;
//属性id 的 get/set方法
public Integer getId(){
return this.id;
}
public void setId(Integer id){
this.id = id;
}
//属性username的set/get方法
public String getUsername(){
return username;
}
public void setUsername(String username){
this.username = username;
}
//属性password的set/get方法
public String getPassword(){
return this.password;
}
public void setPassword(String password){
this.password = password;
}
}
连接数据库的jdbc类
package org.easybooks.test.jdbc;
import java.sql.*;
public class SqlSrvDBConn {
// public static void main(String[] argv){
// SqlSrvDBConn sqlSrvDBConn = new SqlSrvDBConn();
// String sql = "select * from usertable";
// sqlSrvDBConn.executeQuery(sql);
// ResultSet rs = sqlSrvDBConn.rs;
// if(sqlSrvDBConn.conn==null) {
// System.out.println("Conn is null");
// }
// if(rs==null){
// System.out.println("Error");
// return ;
// }
// try{
// while(rs.next()){
// System.out.println(rs.getString("username"));
// }
// }catch(SQLException e){
// System.out.println(e.getMessage());
// }
// }
private Statement stmt;
private Connection conn;
public ResultSet rs;
//在构造方法中创建数据库连接
public SqlSrvDBConn(){
stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(Exception e){
System.out.println("Class is error");
}
try{
String uri = "jdbc:mysql://localhost:3306/test?useSSL=true";
String user = "host";
String password = "HanDong85";
conn = DriverManager.getConnection(uri,user,password);
}catch(Exception e){
System.out.println("Connection happened error");
e.printStackTrace();
}
}
public ResultSet executeQuery(String sql){
try{
// stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
}catch(SQLException e){
System.out.println("Data.executeQuery:"+e.getMessage());
}
return rs;
}
//关闭 对象
public void closeStmt(){
try{
stmt.close();
}catch(SQLException e){
System.out.println("38行出错啦!!!!");
System.out.println("Data.executeQuery:"+e.getMessage());
}
}
public void closeConn(){
try{
conn.close();
}catch(SQLException e){
System.out.println("Data.executeQuery:"+e.getMessage());
}
}
}
操纵信息流向的servlet类
package org.easybooks.test.servlet;
import org.easybooks.test.jdbc.SqlSrvDBConn;
import org.easybooks.test.model.vo.UserTable;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
public class MainServlet extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException{
request.setCharacterEncoding("gb2312"); //设置请求编码
String username = request.getParameter("username"); //获取提交的用户名
String pwd = request.getParameter("password"); //获取提交的密码
boolean validated = false;
SqlSrvDBConn sqlSrvDBConn = new SqlSrvDBConn();
HttpSession session = request.getSession(); //获得会话对象 用来保存当前登录用户信息
//比JSP操纵数据流向来说 多了这一步
UserTable userTable = null;
//先获得UserTable对象 如果是第一次访问该页 用户对象 肯定为null 但如果是第二次甚至是第三次
//就直接登陆主页而无需再次重复验证该用户信息
userTable = (UserTable)session.getAttribute("userTable");
System.out.println(username);
System.out.println(pwd);
if(userTable==null){
String sql = "select * from usertable";
ResultSet rs = sqlSrvDBConn.executeQuery(sql);
try{
while(rs.next()){
if(rs.getString("username").trim().compareTo(username)==0 && rs.getString("password").trim().compareTo(pwd)==0){
userTable = new UserTable();
userTable.setUsername(rs.getString("username"));
userTable.setId(rs.getInt("id"));
userTable.setPassword(rs.getString("password"));
session.setAttribute("userTable",userTable);
validated = true;
}
}
}catch (SQLException e){
e.printStackTrace();
}
sqlSrvDBConn.closeStmt();
sqlSrvDBConn.closeConn();
}
else{
validated = true;
}
if(validated==true){
//验证成功 转向main页面
//转向其他页面发生了变化
response.sendRedirect("main.jsp");
}
else{
//验证失败 转向error页面
response.sendRedirect("error.jsp");
}
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
doGet(request,response);
}
}
登陆成功之后的main页面
<%@ page import="org.easybooks.test.model.vo.UserTable" %><%--
Created by IntelliJ IDEA.
User: FX50J
Date: 2018/1/17
Time: 17:29
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>留言信息板</title>
</head>
<body>
<% UserTable userTable = (UserTable)session.getAttribute("userTable");
String username = userTable.getUsername();
%>
<%=username%>,您好 欢迎登陆留言板!
</body>
</html>
登录失败之后的error页面
<%--
Created by IntelliJ IDEA.
User: FX50J
Date: 2018/1/17
Time: 17:30
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>出错</title>
</head>
<body>
登录失败!单击<a href="login.jsp">这里</a>返回
</body>
</html>
web.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_1.xsd"
version="3.1">
<display-name>jsp_servlet_javabean_jdbc</display-name>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<servlet>
<!--配置servlet-->
<servlet-name>mainServlet</servlet-name>
<servlet-class>org.easybooks.test.servlet.MainServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>mainServlet</servlet-name>
<url-pattern>/mainServlet</url-pattern>
</servlet-mapping>
</web-app>
总结:
总体来说 实际上达到的效果和Model1的实例是一样的
但是因为分工的原因 体现了面向对象 只做自己的事 这一个特点
就此而言 相比Model1来说 Servlet起到了控制程序流程的作用 将原先属于JSP的这一点剥离了出来