我们来看交互图
例子一,
基于MVC 用户登录的实现(JavaBean + Servlet + JSP)
1、web.xml配置
<?xml version=”1.0″ encoding=”UTF-8″?>
<web-app version=”2.5″
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_2_5.xsd”>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>loginServlet</servlet-name>
<servlet-class>org.zxj.mvcdemo.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
</web-app>
2、User
package org.zxj.mvcdemo.vo;
public class User{
private String userid;
private String name;
private String password;
public void setUSerid(String userid){
this.userid = userid;
}
public void setName (String name){
this.name = name;
}
public void setPassword(String password){
this.password = password;
}
public String getUserid(){
return this.userid;
}
public String getName(){
return this.name;
}
public String getPassword(){
return this.password;
}
}
3、DatabaseConnection
package org.zxj.mvcdemo.dbc;
import java.sql.*;
public class DatabaseConnection{
private static final String DBDRIVER = “com.mysql.jdbc.Driver”;
private static final String DBURL = “jdbc:mysql://localhost:3306/zxj”;
private static final String DBUSER = “root”;
private static final String DBPASSWORD =”pf”;
private static Connection con = null;
public DatabaseConnection() throws Exception{
try{
Class.forName(DBDRIVER);
this.con = DriverManager.getConnection(DBURL,DBUSER,DBPASSWORD);
}catch(Exception e){
throw e;
}
}
public Connection getConnection(){
return this.con;
}
public void close() throws Exception {
if(this.con != null){
try{
this.con.close();
}catch(Exception e){
throw e;
}
}
}
}
4、IUserDAO
package org.zxj.mvcdemo.dao;
import org.zxj.mvcdemo.vo.User;
public interface IUserDAO{
public boolean findLogin(User user) throws Exception;
}
5、UserDAOImpl
package org.zxj.mvcdemo.dao.impl;
import org.zxj.mvcdemo.vo.User;
import org.zxj.mvcdemo.dao.*;
import java.sql.*;
public class UserDAOImpl implements IUserDAO{
private Connection conn = null;
private PreparedStatement pstmt = null;
public UserDAOImpl(Connection conn){
this.conn = conn;
}
public boolean findLogin(User user) throws Exception{
boolean flag = false;
String sql = “select name from user where userid= ? and password = ?”;
this.pstmt = this.conn.prepareStatement(sql);
this.pstmt.setString(1,user.getUserid());
this.pstmt.setString(2,user.getPassword());
ResultSet rs = this.pstmt.executeQuery();
if(rs.next()){
user.setName(rs.getString(“name”));
flag = true;
}
this.pstmt.close();
return flag;
}
}
6、UserDAOProxy
package org.zxj.mvcdemo.dao.proxy;
import org.zxj.mvcdemo.vo.User;
import org.zxj.mvcdemo.dbc.*;
import org.zxj.mvcdemo.dao.*;
import org.zxj.mvcdemo.dao.impl.*;
import java.sql.*;
public class UserDAOProxy implements IUserDAO{
private DatabaseConnection dbc = null;
private IUserDAO dao = null;
private PreparedStatement pstmt = null;
public UserDAOProxy(){
try{
this.dbc = new DatabaseConnection();
}catch(Exception e){
e.printStackTrace();
}
this.dao = new UserDAOImpl(dbc.getConnection());
}
public boolean findLogin(User user) throws Exception{
boolean flag = false;
try{
flag = this.dao.findLogin(user);
}catch(Exception e){
throw e;
}finally{
this.dbc.close();
}
return flag;
}
}
7、DAOFactory
package org.zxj.mvcdemo.factory;
import org.zxj.mvcdemo.dao.*;
import org.zxj.mvcdemo.dao.proxy.*;
public class DAOFactory{
public static IUserDAO getIUserDAOInstance(){
return new UserDAOProxy();
}
}
8、LoginServlet
package org.zxj.mvcdemo.servlet;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.zxj.mvcdemo.factory.*;
import org.zxj.mvcdemo.vo.*;
public class LoginServlet extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,IOException {
String path = “login.jsp”;
String userid = req.getParameter(“userid”);
String userpass = req.getParameter(“userpass”);
List<String> info = new ArrayList<String>();
if(userid == null || “”.equals(userid)){
info.add(“用户id不能为空”);
}
if(userpass == null || “”.equals(userpass)){
info.add(“密码不能为空”);
}
if(info.size() == 0){
User user = new User();
user.setUSerid(userid);
user.setPassword(userpass);
try{
if(DAOFactory.getIUserDAOInstance().findLogin(user)){
info.add(“用户登录成功,欢迎”+user.getName()+ “登录”);
}else{
info.add(“用户登录失败”);
}
}catch(Exception e){
e.printStackTrace();
}
}
req.setAttribute(“info”,info);
req.getRequestDispatcher(path).forward(req,res);
//RequestDispatcher rd = null;
//rd = req.getRequestDispatcher(path);
//rd.forward(req,res);
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException,IOException {
doGet(req,res);
}
}
9、Login.jsp
<%@ page language=”java” contentType=”text/html” pageEncoding=”GBK” %>
<%@ page import=”java.util.*”%>
<html>
<head>
<title>登录</title>
<meta http-equiv=”content-type” content=”text/html;charset=gbk”>
</head>
<body>
<%
request.setCharacterEncoding(“GBK”);
List<String> info = (List<String>)request.getAttribute(“info”);
if(info != null){
Iterator<String> iter = info.iterator();
while(iter.hasNext()){
out.println(iter.next());
}
}
%>
<form action=”LoginServlet” method=”post”>
用户:<input type=”text” name=”userid” /> <br />
密码:<input type=”password” name=”userpass” /><br />
<input type=”submit” value=”登录” />
<input type=”reset” value=”重置” />
</body
</html>
例子二,
第一:JSP:由页面指令和HTML组成的查询界面query_condention.jsp,也就是咱们现在的html页和asp页面类似。
<%@ page language="java" contentType="text/html;charset=GBK"%>
<html>
<head>
<title>学生信息</title>
</head>
<body>
<form action="SearchStudentServlet" method="post">
出生日期:<input type="text" name="beginDate">至<input type="text" name="endDate">
<input type="submit" value="查询学生">
</form>
</body>
</html>
第二:控制层 SearchStudentServlet用来接受客户的请求,来处理流程,调用Model(StudentManager.java),转发到要请求的后台服务器的student_list.jsp页面
import java.text.*;
import java.util.*;
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
import com.bjpowernode.exam.model.*;
import com.bjpowernode.exam.manager.*;
public class SearchStudentServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String sBeginDate = request.getParameter("beginDate");
String sEndDate = request.getParameter("endDate");
Date beginDate = new Date();
Date endDate = new Date();
try {
beginDate = new SimpleDateFormat("yyyy-MM-dd").parse(sBeginDate);
endDate = new SimpleDateFormat("yyyy-MM-dd").parse(sEndDate);
}catch(Exception e) {
e.printStackTrace();
}
StudentManager studentManager = new StudentManagerImpl();
List<Student> studentList = studentManager.findStudentList(beginDate, endDate);
//将学生列表设置到requet范围中
//request.setAttribute("student_list", studentList);
//转发,转发是在服务器端转发的,客户端是不知道的
//request.getRequestDispatcher("/student_list.jsp").forward(request, response);
//将studentList放到session中
HttpSession session = request.getSession();
session.setAttribute("student_list", studentList);
//重定向,不会共享request
//以下写法错误,该 "/"代表了8080端口
//response.sendRedirect("/student_list.jsp");
response.sendRedirect(request.getContextPath() + "/student_list.jsp");
}
}
第三 :student_list.jsp页面接收数据形成html,返回到浏览器,渲染在界面上
<%@ page language="java" contentType="text/html;charset=GBK"%>
<%@ page import="java.util.*"%>
<%@ page import="java.text.*"%>
<%@ page import="com.bjpowernode.exam.model.*"%>
<%@ page import="com.bjpowernode.exam.manager.*"%>
<html>
<head>
<title>学生信息</title>
<style type="text/css">
/*表格宽度为1px,实线,黑色*/
table{
border:1px solid black;
border-collapse:collapse;
}
td {
border:1px solid black;
border-collapse:collapse;
}
</style>
</head>
<body>
<table border="1">
<tr>
<td>学生代码</td>
<td>姓名</td>
<td>性别</td>
<td>出生日期</td>
<td>联系电话</td>
<td>家庭住址</td>
<td>班级名称</td>
<td>年龄</td>
</tr>
<%
//List<Student> studentList = (List)request.getAttribute("student_list");
List<Student> studentList = (List)session.getAttribute("student_list");
for (Iterator<Student> iter=studentList.iterator(); iter.hasNext();) {
Student student = iter.next();
%>
<tr>
<td><%=student.getStudentId()%></td>
<td><%=student.getStudentName()%></td>
<td><%=student.getSex()%></td>
<td><%=new SimpleDateFormat("yyyy-MM-dd").format(student.getBirthday())%></td>
<td><%=student.getContactTel()%></td>
<td><%=student.getAddress()%></td>
<td><%=student.getClasses().getClassesName()%></td>
<%
long b = 1000L*60L*60L*24L*365L;
long a = System.currentTimeMillis() - student.getBirthday().getTime();
%>
<td><%=a/b%></td>
</tr>
<%
}
%>
</table>
</body>
</html>
在View的student_list.jsp页面中是大量的html和java代码的混合,在查询条件界面query_condention.jsp主要是html,因为不涉及后台数据的交互.
第四:xml配置Servlet:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<servlet>
<servlet-name>SearchStudentServlet</servlet-name>
<servlet-class>SearchStudentServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SearchStudentServlet</servlet-name>
<url-pattern>/SearchStudentServlet</url-pattern>
</servlet-mapping>
</web-app>