MVC Design Pattern Implementation Login Program

Source: Internet
Author: User
Tags throw exception

One: Introduction to MVC:

MVC pattern (Model-view-controller) is a software architecture model in software engineering that divides software systems into three basic parts: model, view, and controller.

MVC pattern Purpose: To achieve a dynamic programming, so that the subsequent modification and extension of the program to simplify, and make a part of the process of reuse is possible. In addition, this mode makes the program structure more intuitive by simplifying the complexity. The software system is separated by the basic parts of itself and also gives the functions of the basic parts. Professionals can be grouped by their own expertise:

    • (Controller controllers)-responsible for forwarding requests and processing requests.
    • (views view)-graphical interface design for interface designers.
    • (model)-Programmer to write the functions that the program should have (implementation algorithm, etc.), database experts for data Management and database design (can achieve specific functions).
    • model is used to encapsulate data that is relevant to the business logic of an application and how the data is processed. "Model" has the right to direct data access, such as access to the database. "Model" does not depend on "view" and "Controller", that is, the model does not care how it will be displayed or how it is manipulated. However, changes in the data in the model are generally advertised through a refresh mechanism. To implement this mechanism, the views that are used to monitor this model must be registered in advance on this model, so that the view can understand the changes that have occurred on the data model. (Comparison: Viewer mode (software design mode))
    • views enable the purposeful display of data (in theory, this is not required). There is generally no logic on the program in the view. To implement the Refresh feature on the view, the view needs to access the data model it monitors, so it should be registered with the data it is monitoring beforehand.
    • The controller acts as an organizational function between different levels to control the flow of the application. It handles the event and responds. An "event" includes the user's behavior and changes on the data model.

Second: the MVC login Program Flowchart:


Third: List of MVC login programs


Four: Specific class design (DAO+MVC)

Model class:

4.1:user class:

<span style= "FONT-SIZE:18PX;" >package Shiyeqiang.vo; Value Object Public     class User {   //This program defines the employee class, as well as a sequence of setter, getter methods,      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;}}  </span>

4.2:databaseconnection class:

<span style= "FONT-SIZE:18PX;"    >package Shiyeqiang.dbc;  Import java.sql.Connection;  Import Java.sql.DriverManager;    Import java.sql.SQLException; public class DatabaseConnection {//This class is mainly used to complete the opening of the database and close the operation//after the construction method is completed, close () method completes closing, all exceptions are thrown directly, to the call to handle the PRI vate static final String dbdriver = "Org.gjt.mm.mysql.Driver"; Define a database driver in MySQL private static final String Dburl = "JDBC:MYSQL://LOCALHOST:3306/MLDN"; Defines the connection address of the database, where MLDN is the name of the database private static final String DBUSER = "root"; Define the connection user name for the database private static final String Dbpass = "Sqladmin"; Defines the connection password for the database private Connection conn = null; Database connection public databaseconnection () throws Exception {//within the constructor method, make a connection operation to the database try {C Lass.forname (Dbdriver); Load Driver conn = drivermanager.getconnection (Dburl, DBUSER, dbpass);//attempt to build to a given database} catch (Exception E          ) {//For convenience, throw exception exception throw e directly; }} public ConnectionGetconnection () {//Get connection to database return this.conn; } public void Close () throws SQLException {if (this.conn! = null) {try {T              His.conn.close ();              } catch (SQLException e) {throw e; }}} </span>

4.3:iuserdao class

<span style= "FONT-SIZE:18PX;" >package Shiyeqiang.dao;    Import java.util.List;    Import Shiyeqiang.vo.User; Import the VO package public interface Iuserdao {////For the employee class    is defined as the standard for DAO operations;       //FindByID: Indicates that the EMP object public boolean is returned based on the employee number query      Findlogin (user user) throws Exception;    }  </span>

4.4:userdaoimpl class:

<span style= "FONT-SIZE:18PX;" >package shiyeqiang.dao.impl;import java.sql.*;import Shiyeqiang.vo.user;import shiyeqiang.dao.IUserDAO;// For the real implementation class, complete the specific login validation public class Userdaoimpl implements iuserdao{private Connection conn=null;//define the connection operation of the database privat e PreparedStatement ps=null; Define the execution of the database public Userdaoimpl (Connection conn) {//In the constructor to complete the connection operation of the database This.conn=conn;}   public boolean findlogin (user user) throws exception{Boolean flag=false;   try{String sql= "select name from user where userid=? and password=?";    This.ps=this.conn.preparestatement (SQL);    This.ps.setString (1,user.getuserid ());         This.ps.setString (2, User.getpassword ()); ResultSet rs=this.ps.executequery ();//Execute Query operation if (Rs.next ()) {Flag=true;user.setname (rs.getstring (1));   The data in the result set is taken out to save in user}}catch (Exception e) {throw e; }finally{if (this.ps!=null) {try{this.ps.close ();}   catch (Exception e) {throw e;}} } return flag;}} </span>

4.5:userdaoproxy class:

<span Style= "FONT-SIZE:18PX;" >package shiyeqiang.dao.proxy;import shiyeqiang.dao.*;import Shiyeqiang.vo.*;import shiyeqiang.dao.impl.*; Import shiyeqiang.dbc.*;p Ublic class Userdaoproxy implements iuserdao{//for the proxy class, invoking the real topic class, and responsible for opening the database and closing the operation//and the proxy class, as well as the real The theme of the implementation class, are implemented the same//proxy class data members have the real topic class private Iuserdao dao=null; Real-World Theme implementation class//constructor open,//Because the proxy class is also responsible for opening the database and shutting down the operation private databaseconnection dbc=null;public Userdaoproxy () {try{this.dbc= New DatabaseConnection ();}  catch (Exception e) {e.printstacktrace ();}  This.dao=new Userdaoimpl (This.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; }}</span> 

4.6:daofactory class:

<span style= "FONT-SIZE:18PX;" >package shiyeqiang.factory;    Import shiyeqiang.dao.proxy.*;  Import shiyeqiang.dao.*;  public class Daofactory {//Get instantiated object of DAO interface public      static Iuserdao getiuserdaoinstance () throws Exception {            return New Userdaoproxy (); Get instance of proxy class      }  }  </span>

4.7:loginservlet class: Control class, responsible for forwarding requests, processing requests!!!

<span style= "FONT-SIZE:18PX;" >package Shiyeqiang.servlet;import Java.util.*;import javax.servlet.http.*; Import javax.servlet.*; Import java.io.*;import shiyeqiang.vo.user;import shiyeqiang.factory.*;import shiyeqiang.dao.proxy.*;p ublic class Loginservlet extends httpservlet{public void doget (HttpServletRequest req,httpservletresponse resp) throws Servletexce ption,ioexception{string Path = "login.jsp"; String UserID = req.getparameter ("userid"); String Userpass = Req.getparameter ("Usepass"); list<string> info = new arraylist<string> ();//Collect error if (Userid==null | | "". Equals (userid) {info.add ("User ID cannot be empty!") ") ;} if (Userpass==null | | "". Equals (Userpass)) {Info.add ("Password cannot be empty!") ") ;} if (Info.size () ==0) {//There is no error logged in the user user = new user (); User.setuserid (userid); User.setpassword (Userpass); Try{if ( Daofactory.getiuserdaoinstance (). Findlogin (user) {Info.add ("Login successful, welcome" + user.getname () + "Visit! ") ;} else {info.add ("User login failed, wrong username and password! ") ;}} 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);}} </span>

Configuration of the Loginservlet class: Web. XML is configured as follows:

<span style= "FONT-SIZE:18PX;" ><servlet>         <servlet-name>login</servlet-name>      <servlet-class> shiyeqiang.servlet.loginservlet</servlet-class>   </servlet><servlet-mapping>         < servlet-name>login</servlet-name>      <url-pattern>/login/LoginServlet</url-pattern>   </servlet-mapping></span>
4.8:login.jsp: View display, interface display

<span style= "FONT-SIZE:18PX;"  ><% @page contenttype= "text/html" pageencoding= "GBK"%><% @page import= "java.util.*"%>
Using the MySQL database, the database name is MLDN, and the table name in the database is: User, which contains three attributes, respectively: (Userid,name,password).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.