Program Development: MVC design mode and application, mvc design mode

Source: Internet
Author: User

Program Development: MVC design mode and application, mvc design mode

The full name of MVC is Model View Controller, short for model-view-controller. It is a Model of software design, organize Code by means of separation of business logic, data, and interface display, and integrate the business logic into a component to improve and personalize the custom interface and user interaction, you do not need to rewrite the business logic. MVC is uniquely developed to map traditional input, processing, and output functions in a logical graphical user interface structure.

The following describes simple logon operations:

Program flowchart:

In this program, the login information entered by the user is submitted to the Servlet for receiving. After the Servlet receives the request content, it first checks its validity (for example: whether the entered content is null or whether the length meets the requirements). If the verification fails, the error message is sent to the login page. If the data is valid, the DAO layer is called to complete database verification. Based on the verification structure, the "Login successful" or Login Failed page is displayed. In this program, for ease of operation, set the logon success or failure display pages to the logon pages. MVC login program list:

No.

Page name

File Type

Description

1

User

JavaBean

User-logged-on VO operations

2

DatabaseConnection

JavaBean

Responsible for database connection and shutdown operations

3

IUserDAO

JavaBean

Define the DAO interface for login operations

4

UserDAOImpl

JavaBean

Real implementation class of DAO interface, complete specific login verification

5

UserDAOProxy

JavaBean

Defines proxy operations, opens and closes databases, and calls real topics.

6

DAOFactory

JavaBean

Factory class to obtain the DAO interface instance

7

LoginServlet

Servlet

Receive request parameters, perform parameter verification, call DAO to complete specific login verification, and return the login information based on DAO's verification results

8

Login. jsp

JSP

Provides user input forms to Display User Login success or failure information

User Login table structure:

JSP Functions

Through the MVC program, you can clearly feel that the Code on the JSP page has been greatly reduced compared with the initial JSP development (such as JSP + JDBC or JSP + DAO, the output is simply completed. In fact, in development, the reader must remember that JSP should contain only the following three types of code: receive attributes passed from Servlet; judgment statement: determines whether the property passed to JSP exists; Output content: outputs using iteration or VO. Remember that the only package allowed to be imported on the JSP page can only be a java. util package. As long as you can grasp this, you can develop a concise and clear JSP page. After understanding the above information, start to operate on the source code
User. java File
Package com. mvc. oumyye. vo;/***** @ author even my yeah * entity class */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 even my * database connection */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 DatabaseCon Nection () 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 even my * Dao implementation class */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; Str Ing 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.exe cuteQuery (); 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 even my Jesus * factory interface */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 even my Jesus * factory class to implement business operations */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 even my * Servlet */public class LoginServlet extends HttpServlet {private static final long serialVersionUID = 1L; public void doGet (HttpServletRequest req, HttpServletResponse resp) throws Ser VletException, 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 ("the user name cannot be blank !!! ");} If (userpass = null |" ". equals (userpass) {info. add (" the password cannot be blank !! ");} If (info. size () = 0) {User user = new User (); user. setUserid (userid); user. setPassword (userpass); try {if (DAOFactory. getIUserDAOInstance (). findLogin (user) {info. add ("welcome" + user. getName () + "login");} else {info. add ("Log on again") ;}} 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 file

<?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 file

<% @ Page contentType = "text/html" pageEncoding = "GBK" %> <% @ page import = "java. util. * "%> 

Database file. SQL

/* = ============= */Create table user (userid VARCHAR (30) primary key, name VARCHAR (30) not null, password VARCHAR (32) not null ); /* ================================== insert test data ============== ============= */insert into user (userid, name, password) VALUES ('admin', 'admin', 'admin ');

:

Benefits of the MVC design pattern:

JSP is only responsible for displaying DAO. It is responsible for data layer operation Servlet connection JSP and DAO, and jump according to the operation result of JavaBean

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.