Javaweb in servlet Development (5)--web Development mode: Mode I and Mode II

Source: Internet
Author: User

1. servlet Development

2. Model I mode

The client accesses the JSP, calls inside the JavaBean, but through the JavaBean call processing the database operation, JavaBean has the specialized processing database the operation, the database mainly takes the DAO mainly, goes out the database also contains the business processing.

3. Model II Development model

Servlet Features: Can receive the user's request, but also can call the Java program, because it is running in Java program, it must be higher than the JSP performance, and high security performance.

Eventually, all of the servlet's operations are presented in a JSP, so that the servlet's shortcomings are avoided.

JavaBean completes a specific single function, JSP completes the display function, the servlet is responsible for connecting JSP and JavaBean.

Jsp+servlet+javabean, this design is very suitable for large-scale project development, and easy to maintain.

3. MVC design Pattern

4. Application of MVC design pattern

5.1 SQL implementation
CREATE TABLE User (Useridvarchar () PRIMARY KEY, Namevarchar (+) NOT NULL, Passwordvarchar (+) not null);/*============= ========== inserting test data =======================*/insert into user (Userid,name,password) VALUES (' admin ', ' Administrator ', ' Admin ');
5.2 Database connections
public class DatabaseConnection {private static final String Dbdriver = "Com.mysql.jdbc.Driver";p rivate static final Strin G Dburl = "Jdbc:mysql://localhost/struts?useunicode=true&characterencoding=utf-8";p rivate static final String DBUSER = "root";p rivate static final String Dbpassword = "Alice";p rivate Connection conn;private static int count = 0;publ IC DatabaseConnection () {System.out.println ("************* count =" + this.count++); try {class.forname (dbdriver); This.conn = Drivermanager.getconnection (Dburl, DBUSER, Dbpassword);} catch (ClassNotFoundException e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (SQLException e) {//TODO Auto-generated catch Blocke.printstacktrace ();}} Public Connection getconnection () {return this.conn;} public void Close () {if (this.conn! = null) {try {this.conn.close ();} catch (SQLException e) {e.printstacktrace ()}}}}
5.3 Vo Class
 Public classUser {PrivateString userid; PrivateString name; PrivateString password;  Public voidSetuserid (String userid) { This. UserID =userid; }     Public voidsetName (String name) { This. Name =name; }     Public voidSetPassword (String password) { This. Password =password; }     PublicString GetUserid () {return  This. UserID; }     PublicString GetName () {return  This. Name; }     PublicString GetPassword () {return  This. Password; }}
5.4 Iuserdao Interface
5.5 DAO Interface Implementation class
 Public classUserdaoimplImplementsIuserdao {PrivateConnection conn =NULL ; PrivatePreparedStatement pstmt =NULL ;  PublicUserdaoimpl (Connection conn) { This. conn =Conn; }     Public BooleanFindlogin (user user)throwsexception{BooleanFlag =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));//remove a user's real nameFlag =true ; }         This. Pstmt.close (); returnFlag; }} 
5.6 Userdaoproxy: Defining the proxy, responsible for opening and closing the database and invoking the real principal
 Public classUserdaoproxyImplementsIuserdao {PrivateDatabaseConnection DBC =NULL ; PrivateIuserdao DAO =NULL ;  PublicUserdaoproxy () {Try{             This. DBC =Newdatabaseconnection (); }Catch(Exception e) {e.printstacktrace (); }         This. DAO =NewUserdaoimpl (Dbc.getconnection ()); }     Public BooleanFindlogin (user user)throwsexception{BooleanFlag =false ; Try{flag= This. Dao.findlogin (user);//invoke real body, complete operation}Catch(Exception e) {Throwe; }finally{             This. Dbc.close (); }        returnFlag; }} 
5.7 Factory factory class: Get instantiation of DAO interface
 Public class daofactory {    publicstatic  Iuserdao getiuserdaoinstance () {        return  New  userdaoproxy ();    }}

5.8 Servlet Class

Receive request parameters, perform parameter validation, invoke DAO to complete specific login verification, and return login information based on DAO validation results.

 Public classLoginservletextendsHttpServlet { Public voidDoget (HttpServletRequest Req,httpservletresponse resp)throwsservletexception,ioexception{String Path= "Login.jsp" ; String userid= Req.getparameter ("userid") ; String Userpass= Req.getparameter ("Userpass") ; List<String> info =NewArraylist<string> ();//Collect Errors        if(userid==NULL|| "". Equals (userid)) {Info.add ("User ID cannot be empty!" ") ; }        if(userpass==NULL|| "". Equals (Userpass)) {Info.add ("The password cannot be empty!" ") ; }        if(Info.size () ==0) {//There's no record of any errors.User User =NewUser ();            User.setuserid (userid);            User.setpassword (Userpass); Try{                if(Daofactory.getiuserdaoinstance (). Findlogin (user)) {Info.add ("User Login success, welcome" + user.getname () + "Visit! ") ; } Else{Info.add ("User Login failed, wrong user name and password!" ") ; }            }Catch(Exception e) {e.printstacktrace (); }} req.setattribute ("Info", info);    Req.getrequestdispatcher (Path). Forward (REQ,RESP); }     Public voidDoPost (HttpServletRequest Req,httpservletresponse resp)throwsservletexception,ioexception{ This. Doget (REQ,RESP); }
<script language= "javascript" >function validate (f) {if (! ( /^\w{5,15}$/.test (F.userid.value)) {alert ("User ID must be 5~15 bit!") "); F.userid.focus (); return false;} if (! ( /^\w{5,15}$/.test (F.userpass.value)) {alert ("Password must be 5~15 bit!") "); F.userpass.focus (); return false;}} </script><%request.setcharacterencoding ("GBK");%><%list<string> info = (List<String>) Request.getattribute ("info"), if (info = null) {//has information returned iterator<string> iter = Info.iterator (); while ( Iter.hasnext ()) {%>

  

Javaweb in servlet development (5)--web Development mode: Mode I and Mode II

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.