程序开发:MVC设计模式与应用
MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码,将业务逻辑聚集到一个部件里面,在改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑。MVC被独特的发展起来用于映射传统的输入、处理和输出功能在一个逻辑的图形化用户界面的结构中。
下面讲解简单的登录操作:
程序流程图:
No. |
页面名称 |
文件类型 |
描述 |
1 |
User |
JavaBean |
用户登陆的VO操作类 |
2 |
DatabaseConnection |
JavaBean |
负责数据库的连接和关闭操作 |
3 |
IUserDAO |
JavaBean |
定义登陆操作的DAO接口 |
4 |
UserDAOImpl |
JavaBean |
DAO接口的真实实现类,完成具体的登陆验证 |
5 |
UserDAOProxy |
JavaBean |
定义代理操作,负责数据库的打开和关闭并且调用真实主题 |
6 |
DAOFactory |
JavaBean |
工厂类,取得DAO接口的实例 |
7 |
LoginServlet |
Servlet |
接收请求参数,进行参数验证,调用DAO完成具体的登陆验证,并根据DAO的验证结果返回登陆信息 |
8 |
login.jsp |
JSP |
提供用户输入的表单、可以显示用户登陆成功或失败的信息 |
JSP的功能
User.java文件
package com.mvc.oumyye.vo ; /** * * @author 偶my耶 * 实体类 */ 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 ; } }
DatabaseConnection.java
package com.mvc.oumyye.dbc ; import java.sql.* ; /** * * @author 偶my耶 * 数据库连接 */ public class DatabaseConnection { private static final String DBDRIVER = "org.gjt.mm.mysql.Driver" ; private static final String DBURL = "jdbc:mysql://localhost:3306/mytest" ; private static final String DBUSER = "root" ; private static final String DBPASSWORD = "root" ; private Connection conn = null ; public DatabaseConnection() throws Exception{ try{ Class.forName(DBDRIVER) ; this.conn = DriverManager.getConnection(DBURL,DBUSER,DBPASSWORD) ; }catch(Exception e){ throw e ; } } public Connection getConnection(){ return this.conn ; } public void close() throws Exception{ if(this.conn != null){ try{ this.conn.close() ; }catch(Exception e){ throw e ; } } } }
package com.mvc.oumyye.dao ; import com.mvc.oumyye.vo.User; public interface IUserDAO { public boolean findLogin(User user) throws Exception ; }
package com.mvc.oumyye.dao.impl ; import com.mvc.oumyye.dao.*; import com.mvc.oumyye.vo.User; import java.sql.* ; /** * * @author 偶my耶 * Dao实现类 */ 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(1)) ; flag = true ; } this.pstmt.close() ; return flag ; } }
DAOFactory.java
package com.mvc.oumyye.factory ; import com.mvc.oumyye.dao.*; import com.mvc.oumyye.dao.proxy.*; /** * * @author 偶my耶 * 工厂接口 */ public class DAOFactory { public static IUserDAO getIUserDAOInstance(){ return new UserDAOProxy() ; } }
UserDAOProxy.java
package com.mvc.oumyye.dao.proxy ; import com.mvc.oumyye.dbc.DatabaseConnection; import com.mvc.oumyye.dao.IUserDAO; import com.mvc.oumyye.dao.impl.UserDAOImpl; import com.mvc.oumyye.vo.User; /** * * @author 偶my耶 * 工厂类 实现业务操作 */ public class UserDAOProxy implements IUserDAO { private DatabaseConnection dbc = null ; private IUserDAO dao = 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 ; } }
LoginServlet.java
package com.mvc.oumyye.servlet ; import java.io.* ; import java.util.* ; import javax.servlet.* ; import javax.servlet.http.* ; import com.mvc.oumyye.factory.DAOFactory; import com.mvc.oumyye.vo.User; /** * * @author 偶my耶 * Servlet */ public class LoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{ String path = "login.jsp" ; String userid = req.getParameter("userid") ; String userpass = req.getParameter("userpass") ; System.out.println(userid); System.out.println(userpass); List<String> info = new ArrayList<String>() ; if(userid==null || "".equals(userid)){ info.add("用户名不能为空!!!") ; } 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,resp) ; } public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{ this.doGet(req,resp) ; } }
web.xml文件
<?xml version="1.0" encoding="ISO-8859-1"?> <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_2_5.xsd" version="2.5"> <display-name>Welcome to Tomcat</display-name> <description> Welcome to Tomcat </description> <servlet> <servlet-name>login</servlet-name> <servlet-class> com.mvc.oumyye.servlet.LoginServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>login</servlet-name> <url-pattern>/LoginServlet</url-pattern> </servlet-mapping> </web-app>
login.jsp文件
<%@ page contentType="text/html" pageEncoding="GBK"%> <%@ page import="java.util.*"%> <html> <head><title></title></head> <body> <script language="javascript"> function validate(f){ if(!(/^\w{5,15}$/.test(f.userid.value))){ alert("用户ID必须是5~15位!") ; f.userid.focus() ; return false ; } if(!(/^\w{5,15}$/.test(f.userpass.value))){ alert("密码必须是5~15位!") ; f.userpass.focus() ; return false ; } } </script> <% request.setCharacterEncoding("GBK") ; %> <% List<String> info = (List<String>) request.getAttribute("info") ; if(info != null){ // 有信息返回 Iterator<String> iter = info.iterator() ; while(iter.hasNext()){ %> <h4><%=iter.next()%></h4> <% } } %> <form action="LoginServlet" method="post" onSubmit="return validate(this)"> 用户ID:<input type="text" name="userid"><br> 密 码:<input type="password" name="userpass"><br> <input type="submit" value="登陆"> <input type="reset" value="重置"> </form> </body> </html>
数据库文件.sql
/*======================= 创建user数据表 =======================*/ CREATE TABLE user( userid VARCHAR(30) PRIMARY KEY , name VARCHAR(30) NOT NULL , password VARCHAR(32) NOT NULL ) ; /*======================= 插入测试数据 =======================*/ INSERT INTO user (userid,name,password) VALUES (‘admin‘,‘administrator‘,‘admin‘) ;
效果图:
MVC设计模式的好处:
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。