MVC(Model -View-Controller)实例应用模式
以登录为例:
Model:User
- package com.keith.bean;
- public class TUser implements java.io.Serializable {
- private static final long serialVersionUID = 1L;
- private Integer userid;
- private String userName;
- private String pwd;
- public TUser() {
- }
- public Integer getUserid() {
- return userid;
- }
- public void setUserid(Integer userid) {
- this.userid = userid;
- }
- public String getUserName() {
- return userName;
- }
- public void setUserName(String userName) {
- this.userName = userName;
- }
- public String getPwd() {
- return pwd;
- }
- public void setPwd(String pwd) {
- this.pwd = pwd;
- }
- }
数据库连接类:
- package com.keith.util;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- public class DBConn {
- private static final String DBDRIVER = "com.mysql.jdbc.Driver";
- private static final String DBURL = "jdbc:mysql://127.0.0.1:3306/login";
- private static final String DBUSER = "root";
- private static final String DBPWD = "kejianjun";
- private Connection conn = null;
- public DBConn() {
- try {
- Class.forName(DBDRIVER);
- conn = DriverManager.getConnection(DBURL, DBUSER, DBPWD);
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- public void close() throws Exception{
- if (this.conn != null) {
- try {
- conn.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
- public Connection getConn() {
- return conn;
- }
- public void setConn(Connection conn) {
- this.conn = conn;
- }
- }
View层:登录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>My JSP 'index.jsp' starting page</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">
- -->
- <script type="text/javascript">
- function validate(f){
- if (!(/^w{4,15}$/.test(f.username.value))) {
- alert("用户名必须是4~16位!");
- f.username.focus();
- return false;
- }
- if (!(/^w{4,15}$/.test(f.pwd.value))) {
- alert("密码必须是4~15位!");
- f.pwd.focus();
- return false;
- }
- return true;
- }
- </script>
- </head>
- <body>
- <%
- List<String> info = (List<String>)request.getAttribute("info");
- if(info != null){
- Iterator<String> iter = info.iterator();
- while(iter.hasNext()){
- %>
- <h3><font color="red"><%=iter.next() %></font></h3>
- <%}
- } %>
- <form action="login" method="post" onsubmit="return validate(this)" name="f">
- 用户名:<input type="text" name="username"><br />
- 密 码:<input type="password" name="pwd"><br />
- <input type="submit" value="登陆">
- <input type="reset" value="取消">
- </form>
- </body>
- </html>
配置web.xml
- <servlet>
- <servlet-name>login</servlet-name>
- <servlet-class>com.keith.servlet.LoginServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>login</servlet-name>
- <url-pattern>/login</url-pattern>
- </servlet-mapping>
- <servlet>
Controller控制层 servlet
- package com.keith.servlet;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.List;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import com.keith.bean.TUser;
- import com.keith.factory.DAOFactory;
- /**
- * 定义Sevlet
- *
- * @author T
- *
- */
- public class LoginServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
- this.doPost(req, resp);
- }
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
- String sucPath = "main.jsp";
- String loginEroPath = "index.jsp";
- String username = req.getParameter("username");
- String pwd = req.getParameter("pwd");
- List<String> info = new ArrayList<String>();
- if (username == null || "".equals(username)) {
- info.add("用户名不能为空!");
- }
- if (pwd == null || "".equals(pwd)) {
- info.add("密码不能为空!");
- }
- //用户名密码通过验证
- if (info.size() == 0) {
- //实例化VO
- TUser user = new TUser();
- //设置username
- user.setUserName(username);
- //设置pwd
- user.setPwd(pwd);
- if (DAOFactory.getIUserDAOInstance().findLogin(user)) {
- info.add("欢迎:" + user.getUserName());
- //保存信息,进行跳转
- req.setAttribute("info", info);
- req.getRequestDispatcher(sucPath).forward(req, resp);
- } else {
- info.add("用户信息错误!");
- req.setAttribute("info", info);
- req.getRequestDispatcher(loginEroPath).forward(req, resp);
- }
- }
- }
- }
通过DAO工厂找到UserDAO的实例:这是DAOFactory:
- package com.keith.factory;
- import com.keith.dao.IUserDAO;
- import com.keith.dao.proxy.UserDAOProxy;
- /**
- * 定义工厂类,取得DAO实例
- * @author T
- *
- */
- public class DAOFactory {
- /**
- * 取得DAO实例
- * @return
- */
- public static IUserDAO getIUserDAOInstance(){
- //返回代理实例
- return new UserDAOProxy();
- }
- }
返回代理实例,找到userDAO的代理类:
Java代码
- package com.keith.dao.proxy;
- import com.keith.bean.TUser;
- import com.keith.dao.IUserDAO;
- import com.keith.dao.UserDAOImpl;
- import com.keith.util.DBConn;
- /**
- * DAO代理操作类
- *
- * @author T
- *
- */
- public class UserDAOProxy implements IUserDAO {
- private DBConn dbc = null;
- private IUserDAO dao = null;
- public UserDAOProxy() {
- //实例化数据库连接
- this.dbc = new DBConn();
- this.dao = new UserDAOImpl(this.dbc.getConn());
- }
- /**
- * 代理登陆方法
- */
- public boolean findLogin(TUser user) {
- boolean flag = false;
- try {
- // 调用真实主题
- flag = this.dao.findLogin(user);
- this.dbc.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- return flag;
- }
- }
找到UserDAOImpl的并执行它的findLogin()方法:
Java代码
- package com.keith.dao;
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import com.keith.bean.TUser;
- public class UserDAOImpl implements IUserDAO {
- private Connection conn = null;
- private PreparedStatement pstm = null;
- public UserDAOImpl(Connection conn) {
- this.conn = conn;
- }
- /**
- * 登陆
- *
- * @throws SQLException
- */
- public boolean findLogin(TUser user) {
- boolean flag = false;
- try {
- String sql = "SELECT username,pwd FROM tuser WHERE username=? and pwd=?";
- this.pstm = this.conn.prepareStatement(sql);
- this.pstm.setString(1, user.getUserName());
- this.pstm.setString(2, user.getPwd());
- ResultSet rs = this.pstm.executeQuery();
- if (rs.next()) {
- user.setUserName(rs.getString(1));
- flag = true;
- }
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- try {
- if (this.pstm != null) {
- this.pstm.close();
- }
- } catch (SQLException e2) {
- e2.printStackTrace();
- }
- }
- return flag;
- }
- }
实现了IUserDAO接口:
Java代码
- package com.keith.dao;
- import java.sql.SQLException;
- import com.keith.bean.TUser;
- /**
- * userDao接口
- *
- * @author T
- *
- */
- public interface IUserDAO {
- /**
- * 用户登录验证
- *
- * @param user
- * @return
- */
- public boolean findLogin(TUser user);
- }