Layered idea of web development

Source: Internet
Author: User
Tags throw exception

MVC Development Pattern:
M:model model javabean& Four kinds of scopes
V:view View JSP
C:controller Controller Servlet

Use Jsp+javabean+servlet to develop without using frames

But in actual development, we have a more detailed division:
Layered thinking: strong cohesion, weak coupling

The whole business process is like this:
The browser is where the user initiates a request to the server, and the server-side controller servlet receives the user's request to do three things:
1. Get data for the form 2. Call business logic 3. Distribution steering, where the business logic invoked, the business layer will invoke the DAO layer's basic additions and deletions, each layer can operate on javabean| three domain objects. The final result is returned to the user's browser display through a JSP.
For each layer, we typically create the following packages:
Domain:javabean, entity Bean, for encapsulating data
Service: Business layer interface, such as registration, login ...
Service.impl: Implementation class for Business layer interface
Dao:dao interface, basic additions and deletions to the search method
Implementation classes for DAO.IMPL:DAO interfaces
Servlet:servlet class
Utils: Tool Class
Exception: Custom Exception class
Jsp
The interface can be seen as a function specification, which includes all the methods.
Below, write a Web applet for user login Registration

Based on the layered thinking above, the Javaweb program is shown in the above diagram.
User: Entity Bean, encapsulating data in which the name of the field should be consistent with the database field

Dao: Data Access Layer Interface

The methods are basic additions and deletions, access to data in the database
Implementation classes for DAO.IMPL:DAO interfaces

Package Com.itdream.dao.impl;
Import Com.itdream.dao.UserDao;
Import Com.itdream.domain.User;
Import com.itdream.exception.UserExcisException;

I write the operation of the database tool class, the specific implementation of the method see before the Bowen "JDBC Technology" import com.itdream.utils.DBUtils;
Import java.sql.Connection;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSet;

Import Java.text.SimpleDateFormat;
 /** * Created by Dream on 2017/12/1.  */public class Userdaoimpl implements Userdao {public void Insert (user user) throws exception{Connection con
        = NULL;

        PreparedStatement PS = null;
            try{con = dbutils.getconnection ();
            String sql = "INSERT into users (Username,password,email,birthday) VALUES (?,?,?,?)";
            PS = con.preparestatement (SQL);
            Ps.setstring (1,user.getusername ());
            Ps.setstring (2,user.getpassword ());
            Ps.setstring (3,user.getemail ());
            SimpleDateFormat SPF = new SimpleDateFormat ("Yyyy-mm-dd"); String date = Spf.format (useR.getbirthday ());

            Ps.setstring (4,date);
        int result = Ps.executeupdate ();
            }catch (Exception e) {e.printstacktrace (); throw new RuntimeException ("Insert failed.")
        ");
        }finally {dbutils.closeall (Null,ps,con);
        } public user select (user user) throws exception{Connection con = null;
        ResultSet rs = null;
        PreparedStatement PS = null;
        User u = null;
            try{con = dbutils.getconnection (); String sql = "SELECT * from users where username =?"
            and password =? ";
            PS = con.preparestatement (SQL);
            Ps.setstring (1,user.getusername ());
            Ps.setstring (2,user.getpassword ());
            rs = Ps.executequery ();
                if (Rs.next ()) {u = new User ();
                U.setid (Rs.getint (1));
                U.setusername (rs.getstring (2));
                U.setpassword (Rs.getstring (3)); U.setemail (RS.GEtstring (4));
            U.setbirthday (Rs.getdate (5));
        }}catch (Exception e) {e.printstacktrace ();
    return u;
        public boolean selectbyname (String name) {Connection con = null;
        ResultSet rs = null;
        PreparedStatement PS = null;
            try{con = dbutils.getconnection ();
            String sql = "SELECT * from users where username =?";
            PS = con.preparestatement (SQL);
            Ps.setstring (1,name);
            rs = Ps.executequery ();
            if (Rs.next ()) {return true;
        }}catch (Exception e) {e.printstacktrace ();
    return false; }
}

Service: Business layer

Service.impl: Implementation classes for the business layer

Package Com.itdream.service.impl;
Import Com.itdream.dao.UserDao;
Import Com.itdream.dao.impl.UserDaoImpl;
Import Com.itdream.domain.User;
Import com.itdream.exception.UserExcisException;

Import Com.itdream.service.UserService;
 /** * Created by Dream on 2017/12/1. */public class Userserviceimpl implements UserService {//to manipulate the underlying database Userdao Userdao = new Userdaoim by invoking the DAO interface implementation class
    PL ();
    The public void register (user user) throws exception{//registration is the user's insert Userdao.insert.
        Public user login (user user) {user U = null;
        try{//login is also the user's lookup U = userdao.select (user);
        }catch (Exception e) {e.printstacktrace ();
    return u; 
        public boolean finduserbyname (String name) throws userexcisexception{Boolean B = userdao.selectbyname (name); The user already exists and needs to throw an exception if (b) {throw new Userexcisexception ("User already exists.")
        ");
    return b; }
}

Servlet: Controller servlet class

Login:

public class Logservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse Respon
        SE) throws ioexception,servletexception{request.setcharacterencoding ("Utf-8");
        Get form data User user = new user ();
            try{beanutils.populate (User,request.getparametermap ());
            Invoke business logic userservice US = new Userserviceimpl ();
            User U = us.login (user);
                If u is not NULL, the login success if (U!= null) {request.getsession (). setattribute ("U", user);
            Request.getrequestdispatcher ("/index.jsp"). Forward (Request,response);
            }else {//Otherwise login failed, re-login Response.sendredirect (Request.getcontextpath () + "/log.jsp");
        }}catch (Exception e) {e.printstacktrace (); } public void DoPost (HttpServletRequest request,httpservletresponse response) throws Ioexception,servletexception
{doget (request,response);    }
} 

Registration:
We have increased the validation of user form registration information by adding an entity object UserForm used to encapsulate form data for user registration submissions, where the valid method of the object implements the validation of the user registration information
UserForm class as the entity object, We also put in the domain package, specifically implemented as follows:

Package com.itdream.domain;
Import Java.text.SimpleDateFormat;
Import Java.util.HashMap;

Import Java.util.Map;
 /** * Created by Dream on 2017/12/2.
    * * Public class UserForm {private int id;
    Private String username;
    private String password;
    Private String Repassword;
    Private String Email;

    Private String birthday;
    map<string,string> msg = new hashmap<> (); If the returned MSG is not empty, there is an error message; otherwise, registration validation passes public boolean valid () {if ("". Equals (username)) {msg.put ("Userna Me "," User name cannot be empty.
        "); }else if (!username.matches ("\\w{3,8}")) {Msg.put ("username"), the username must be a 3~8-bit letter.
        "); } if ("". Equals (password)) {msg.put ("password", "Password cannot be empty.")
        "); }else if (!password.matches ("\\d{3,8}")) {msg.put ("password", "Password must be a 3~8 bit number.")
        "); } if (!password.equals (Repassword)) {msg.put ("Repassword", "two times password must be entered consistently.")
        "); } if ("". Equals (email)) {msg.put ("email"), the mailbox cannot be empty.
        "); }else if (!email.matches ^[a-z0-9]+ ([. _\\\\-]*[a-z0-9]) *@ ([a-z0-9]+[-a-z0-9]*[a-z0-9]+.) {1,63}
        [a-z0-9]+$]) {msg.put ("email", "must conform to the format of the mailbox input"); } if ("". Equals (Birthday)) {msg.put ("Birthday", "Birthday cannot be empty.")
        ");
            }else {SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd");
            try{sdf.parse (birthday); }catch (Exception e) {msg.put ("Birthday", "birthday format is not correct.")
            ");
    } return Msg.isempty (); }//Omitting the Get,set method of the instance domain

So when you register the implementation, you need to join the form validation operation:

public class Regservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse Respon
        SE) throws ioexception,servletexception{request.setcharacterencoding ("UTF-8");
        Response.setcontenttype ("Text/html;charset=utf-8");
        Get form data User user = new user ();
        UserForm uf = new UserForm ();
            try{///The registration information submitted by the user into the UserForm class, first verify, if the checksum fails, then request forwarding, while the UF transmission beanutils.populate (Uf,request.getparametermap ());
                if (!uf.valid ()) {//msg is not empty, has error Request.setattribute ("UF", UF);
                Request.getrequestdispatcher ("/reg.jsp"). Forward (Request,response);
            Return
        }}catch (Exception e) {e.printstacktrace ();
       //If executed here, stating that the checksum is successful, inject the data into the user class userservice US = new Userserviceimpl (); try{/** uses beanutils to implement automatic set of object data, but there are problems with the time setting Org.apache.commons.beanutils.converters.DateTimeConverter
     . toDate      DateConverter does not support the default String to ' Date ' conversion.**/convertutils.register (new Dateloca
           Leconverter (), date.class);
           Beanutils.populate (User,request.getparametermap ());
           Call business logic//registered user if present, throw exception userexcisexception Boolean b = Us.finduserbyname (User.getusername ());
       Us.register (user);
            }catch (userexcisexception e) {request.setattribute ("error", E.getmessage ());
        Request.getrequestdispatcher ("/reg.jsp"). Forward (Request,response);
        }catch (Exception e) {e.printstacktrace (); //distribution to Response.getwriter (). Write ("registered successfully.")
        1s skip to homepage ... ");
    Response.setheader ("Refresh", "1;url=" +request.getcontextpath () + "/index.jsp");
        public void DoPost (HttpServletRequest request,httpservletresponse response) throws ioexception,servletexception{
    Doget (Request,response); }
}

Logoff: This is very simple, you need to destroy the session

public class Logoutservlet extends HttpServlet {public
    void doget (HttpServletRequest request, HttpServletResponse Response) throws ioexception,servletexception{
        request.getsession (). invalidate ();//session destruction
        Response.sendredirect (Request.getcontextpath () + "/index.jsp");
    }
    public void DoPost (HttpServletRequest request,httpservletresponse response) throws ioexception,servletexception{
        doget (request,response);
    }

Jsp:
INDEX.JSP: When you log in, the user information is saved in the Session object with the variable u, so you can determine whether the user is logged in according to whether U is null or not

LOG.JSP:

Reg.jsp: At the time of registration, if the user already exists, the error message is saved in the error variable of the request domain object, and the checksum information is placed in the UF variable.


Some additions:
Convertutils.register Register Converter: When using the Beanutils populate method (this method can implement the user submitted form data automatically injected into the entity object, dynamic acquisition, do not need us to set up), in fact, will call convert to convert, but con Verter only supports some basic types, not even java.util.Date types. And one of the more stupid places is when you encounter a type that you don't know, it throws an exception.
This time you need to register the converter with the type. For example, it means that data that needs to be converted to date type is processed by Datelocaleconverter this converter.
Convertutils.register (New Datelocaleconverter (), date.class);

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.