servlet+javabean+jsp to build Java Web registration and login function _java

Source: Internet
Author: User
Tags java web


The MVC structure diagram implemented by Java Web is as follows, in which the controller is implemented by servlet, the model is implemented by JavaBean, and most of the views are implemented by JSP page.



The basis of thought
Jsp+javabean Two-storey structure of the working principle should be more familiar, but also better understanding.
But one thing must be clear is that the user through the browser to send a Web page request, the request to the server to find the corresponding Web page, if it is the first request (the second do not have to explain the implementation), for JSP to generate a servlet, and then through the servlet engine to execute Servlet, which embeds the result of the call JavaBean into the page and returns it to the user's browser.
The essence of the Jsp+javabean+servlet three-tier structure is a controller:servlet to distribute the client browser's request. It would be helpful to understand the servlet if the role of the servlet acting as a controller is understood as preprocessing of the client's request. The Web.xml profile allows you to find the corresponding relationship between a user request and a particular servlet, each of which has a specific servlet object, so that the processing user requests is a Servlet object that inherits from HttpServlet.


﹤!--jspc servlet mappings start--﹥ ﹤servlet﹥ ﹤servlet-name﹥ms1﹤/servlet-name﹥ 
    . Firstaction﹤/servlet-class﹥ 
  ﹤/servlet﹥ 
 
  ﹤servlet﹥ 
    ﹤servlet-name﹥ms2﹤/servlet-name﹥ 
    ﹤servlet-class﹥news. Detailaction﹤/servlet-class﹥ 
  ﹤/servlet﹥ 
﹤!--jspc servlet mappings End--﹥ 
  ﹤servlet-mapping﹥ 
    ﹤servlet-name﹥ms1﹤/servlet-name﹥ 
    ﹤url-pattern﹥/newsmain﹤/url-pattern﹥ 
  ﹤/servlet-mapping﹥ 
 
  ﹤servlet-mapping﹥ 
    ﹤servlet-name﹥ms2﹤/servlet-name﹥ 
    ﹤url-pattern﹥/newsdetail﹤/url-pattern﹥ 
  ﹤/ Servlet-mapping﹥ 


As shown above, a section of the configuration servlet excerpt from Web.xml, the first part is primarily used to configure the servlet to be associated with a specific Servlet object, and the second part is primarily used to configure which servlet processing the request, the Servlet name Association, and the processing request Servlet processing objects are associated, for example, a request from a client browser to/newsmain, which is handled by the MS1 servlet and can be found by MS1 to the corresponding Serlet object news. Firstaction, or/newsmain-﹥ms1-﹥news. Firstaction, this is the meaning of the configuration file. To now understand the user/newsmain request will be news. Firstaction class objects to deal with, so say, to understand the program to understand the role of firstaction is what on the line. For example, here is an implementation of firstaction.


Public final class Firstaction extends HttpServlet { 
 protected void service (HttpServletRequest req, HttpServletResponse resp) 
  throws Servletexception, IOException { 
 
 db db = new db (); 
 HttpSession session = Req.getsession (); 
 
 try { 
  Session.setattribute (Constants.news_list_key, NEWS 
   . Searchnewstitle (db)); 
 catch (Exception e) { 
  e.printstacktrace (); 
 } 
 
 Db.close (); 
 String target = "/p43_news/newsmain.jsp"; 
 Resp.sendredirect (target); 
 } 
 
 


This implementation can be seen when the server receives the client request to perform the News.searchnewstitle (DB) operation, and then puts the return value through the Session.setattribute into the session, and then passes the Resp.sendredirect (target) is transferred indirectly to newsmain.jsp, so that the corresponding values stored in the session can be obtained through the Session.getattribute function in newsmain.jsp.
Looking back is easy to see Jsp+javabean working principle and jsp+javabean+servlet working principle is different, two-tier structure must put the preprocessing in the JSP, such as News.searchnewstitle (db), The three-layer structure of the first preprocessing in the servlet, and then equivalent to the processing results through the session back to the JSP, so that JSP more attention to the display of the interface.



Login Registration Module Requirements
1 Registration
1.1 User's registration form (username, password, mailbox, nickname, authentication code)
1.2 Submit registration: To do (username, password, mailbox, nickname, authentication code) of the checksum.
1.2.1 Username, password, mailbox, nickname is done in the client browser, through JS to achieve.
The 1.2.2 Verification code is to be done on the server side of the program.
2. If the registration form of the calibration pass, then the business logic to judge.
2.1 If the user already exists, tell the user the error message.
2.2 If the mailbox already exists, tell the user the error message.
2.3 If none exists. Then proceed to step 3rd.
3. Save the user's information in the database
4. Register successfully, jump to login page
5. Landing
5.1 The user's login information sent to the background to verify
5.2 If the validation is successful, jump to the first page
5.3 If the jump fails, jump to the landing page and prompt for an error message.



Project directory Structure
the source code of the project is divided into four package files, which are used to access the model, view, controller and tool class, and the specific documents are as follows:






For views, we define three JSP pages, as follows:









Defining views
login.jsp Page


<%@ page language= "java" contenttype= "text/html; Charset=utf-8 " 
  pageencoding=" UTF-8 "%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" > 


index.jsp page


<%@ page language= "java" contenttype= "text/html; Charset=utf-8 " 
  pageencoding=" UTF-8 "%> <%@ taglib uri=" Http://java.sun.com/jsp/jstl/core "
prefix=" C " %> 
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" > 


regist.jsp page


<% @ page language = "java" contentType = "text / html; charset = UTF-8"
  pageEncoding = "UTF-8"%>
<! DOCTYPE html PUBLIC "-/ W3C // DTD HTML 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv = "Content-Type" content = "text / html; charset = UTF-8">
<title> Form for user registration </ title>
<script type = "text / javascript">
  function changeImage () {

    document.getElementById ("image"). src = "$ {pageContext.request.contextPath} / checkimage?" + new Date (). getTime ()

  }

  function validateForm () {

    // do username, password, email, nickname verification

    var username = document.getElementById ("username"). value;
    if (username == "") {

      alert ("username cannot be empty");
      return false;
    }

    var password = document.getElementById ("password"). value;
    if (password == "") {

      alert ("password cannot be empty");
      return false;
    }

    var repassword = document.getElementById ("repassword"). value;
    if (password! = repassword) {

      alert ("Passwords must match");
      return false;
    }

    var nickname = document.getElementById ("nickname"). value;
    if (nickname == "") {

      alert ("nickname cannot be empty");
      return false;
    }

    // ^ \\ s * \\ w + (?: \\. {0,1} [\\ w-] +) * @ [a-zA-Z0-9] + (?: [-.] [a -zA-Z0-9] +) * \\. [a-zA-Z] + \\ s * $
    var email = document.getElementById ("email"). value;
    if (email.match ("^ \\ s * \\ w + (?: \\. {0,1} [\\ w-] +) * @ [a-zA-Z0-9] + (?: [ -.] [a-zA-Z0-9] +) * \\. [a-zA-Z] + \\ s * $ ") == null) {

      alert ("Email address is incorrect");
      return false;
    }


  }
</ script>
</ head>
<body>
  <h3> User registration form </ h3>
  <font color = "red"> $ {message} </ font>

  <form action = "$ {pageContext.request.contextPath} / regist" onsubmit = "return validateForm ();" method = "post">
    <table border = "1">
      <tr>
        <td> user name </ td>
        <td>
          <input type = "text" name = "username" id = "username1" v>
        </ td>
      </ tr>
      <tr>
        <td> Password </ td>
        <td>
          <input type = "password" name = "password" id = "password">
        </ td>
      </ tr>
      <tr>
        <td> Please confirm your password </ td>
        <td>
          <input type = "password" name = "repassword" id = "repassword">
        </ td>
      </ tr>
      <tr>
        <td> nickname </ td>
        <td>
          <input type = "text" name = "nickname" id = "nickname">
        </ td>
      </ tr>
      <tr>
        <td> Email </ td>
        <td>
          <input type = "text" name = "email" id = "email">
        </ td>
      </ tr>
      <tr>
        <td> Verification code </ td>
        <td>
          <input type = "text" name = "checkcode">
          <img src = "$ {pageContext.request.contextPath} / checkimage"
          style = "cursor: pointer;" id = "image" onclick = "changeImage ();">
        </ td>
      </ tr>
      <tr>
        <td> </ td>
        <td>
          <input type = "submit" value = "register">
        </ td>
      </ tr>
    </ table>
  </ form>
</ body>
</ html> 


Defining a Model
User model:


Package Com.vs2022.model;

public class User {

  private String username;
  private String password;
  Private String nickname;
  private String Email;

  alt+shft+ S//Pop-up overlay Method dialog box. Public
  String GetUserName () {return
    username;
  }
  public void Setusername (String username) {
    this.username = username;
  }
  Public String GetPassword () {return
    password;
  }
  public void SetPassword (String password) {
    this.password = password;
  }
  Public String Getnickname () {return
    nickname;
  }
  public void Setnickname (String nickname) {
    this.nickname = nickname;
  }
  Public String Getemail () {return
    email;
  }
  public void Setemail (String email) {
    This.email = email;
  }

}


Useroperation model


Package Com.vs2022.model;

Import Com.vs2022.utils.DBUtil;

public class Useroperation {public

  final static int usernameexist=1;
  Public final static int emailexist=2;
  Public final static int success=3;
  Public final static int fail=4;

  public int regist (user user) {


    dbutil db = new Dbutil ();

    if (Db.serchusername (User.getusername ())) {
      //Description The user name already exists return 
      usernameexist
    }

    if (Db.serchemail (User.getemail ())) {
      //description mailbox already exists return 
      emailexist
    }


    If you go here, you can say that the mailbox user name does not exist, so let it register. Add to the database
    db.updateuser (user);

    return SUCCESS;
  }

  public int login (user user) {

    dbutil db = new Dbutil ();

    if (db.loginsuccess user.getusername (), User.getpassword ()) {
      //description found the username and password are all correct return
      SUCCESS;
    } return

    FAIL
  }

}


Checkcode model


Package Com.vs2022.model; 
Import Java.awt.Color; 
Import Java.awt.Font; 
Import Java.awt.Graphics; 
Import Java.awt.image.BufferedImage; 
Import java.io.IOException; 
Import Java.io.OutputStream;

Import java.util.Hashtable; 
Import Javax.imageio.ImageIO; 
Import javax.servlet.ServletException; 
Import Javax.servlet.http.HttpServletRequest; 
Import Javax.servlet.http.HttpServletResponse;


Import javax.servlet.http.HttpSession;
  public class Checkcode {private String getrandomstring () {int rannum = (int) (Math.random () * 9000) + 1000;

return rannum + "";} public void GetCode (int width, int height, httpservletrequest request, httpservletresponse response) throws Servletexcept
  Ion, ioexception{//Create image in memory bufferedimage image = new BufferedImage (width, height, bufferedimage.type_int_rgb);   Graphics G=image.getgraphics ();
  Creates a graphics object that acts as a brush G.setcolor (Color.getcolor ("F8f8f8"));  G.fillrect (0, 0, width, height); Draw Background Font mfont=new font ("italics", font.bold,16);Defines the font style g.setfont (Mfont);
  Sets the font g.setcolor (color.red);
  Generate random number String rans=getrandomstring ();
  Write random numbers into the HttpSession session = Request.getsession ();
  Session.setattribute ("Check", rans);
  Writes random numbers to the picture g.drawstring (Rans, 5, 20);
  Image entry into force g.dispose ();

Output image Imageio.write (image, "JPEG", Response.getoutputstream ());

 }
}


defines the controller
Loginservlet class


Package Com.vs2022.controller; 
Import java.io.IOException;

Import Java.io.PrintWriter; 
Import javax.servlet.ServletException; 
Import Javax.servlet.http.HttpServlet; 
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse; 
Import Com.vs2022.model.User;


Import com.vs2022.model.UserOperation; public class Loginservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse resp Onse) throws Servletexception, IOException {//Complete login logical String username = Request.getparameter ("username
    ");

    String Password = request.getparameter ("password");

    User user = new user ();
    User.setusername (username);

    User.setpassword (password);

    Invoke the business function JavaBean class to implement the specific business logic of login useroperation US = new useroperation (); 
    return value? 

    int i = us.login (user);
      if (i==4) {//Description login failure, username or password error request.setattribute ("message", "Username or password error"); Request.getrequestdispatcher ("LOgin.jsp "). Forward (request, response); }else{//Login successful, jump to the homepage of the site, with redirect//username to the session domain Request.getsession (). setattribute ("User
      Name ", username);
      Response.sendredirect ("index.jsp");


    Request.getrequestdispatcher ("index.jsp"). Forward (request, response); } public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioex
  ception {doget (request, response);

 }

}


Registservlet class


Package Com.vs2022.controller; 
Import java.io.IOException; 
Import javax.servlet.ServletException; 
Import Javax.servlet.http.HttpServlet; 
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;

Import Com.sun.org.apache.commons.beanutils.BeanUtils; 
Import Com.vs2022.model.User;


Import com.vs2022.model.UserOperation; public class Registservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse Res

    Ponse) throws Servletexception, IOException {//Solve the Post method of garbled request.setcharacterencoding ("UTF-8");
    Verify the validation code String Checkcode = Request.getparameter ("Checkcode");
    String check_code_session = (string) request.getsession (). getattribute ("check"); if (checkcode==null| |!
      Checkcode.equals (check_code_session)) {//Note that the validation code input is incorrect request.setattribute ("message", "Incorrect validation code input");
      Request.getrequestdispatcher ("regist.jsp"). Forward (request, response);
    Return//If you go here, it means that all the checksums are passed, and you need to call the user user = new user () that involves processing the business logic.
    Beanutils completes the encapsulation of the data into the Java Bean object, an open source jar implementation of the Apache Foundation.
      try {//Prerequisite: The field name of the JavaBean must be consistent with the key of the value submitted in the form, otherwise the encapsulation cannot be completed.
    Beanutils.populate (User, Request.getparametermap ());
      catch (Exception e) {e.printstacktrace ();
    throw new RuntimeException ("Sorry, encapsulation data failed");
    //So a new Java Bean class is designed to implement the business logic useroperation US = new useroperation ();

      try {int feedBack = us.regist (user);
        if (feedback==useroperation.emailexist) {//description mailbox already exists Request.setattribute ("message", "Mailbox already exists");



      Request.getrequestdispatcher ("regist.jsp"). Forward (request, response);  }else if (feedback==useroperation.usernameexist) {//description user name already exists request.setattribute ("message", "Username already exists")
        ");


      Request.getrequestdispatcher ("regist.jsp"). Forward (request, response); }else{//Description RegistrationSuccessful, jump to the login page.

      To use redirect Response.sendredirect ("login.jsp");
      } catch (Exception e) {e.printstacktrace ();
    throw new RuntimeException ("Add failed"); } public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexc
  eption {doget (request, response);

 }

}


Checkimageservlet class


 package com.vs2022.controller; 
Import java.io.IOException; 
Import javax.servlet.ServletException; 
Import Javax.servlet.http.HttpServlet; 
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;

Import Com.vs2022.model.CheckCode;  public class Checkimageservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse Response) throws Servletexception, IOException {//disable cache, regenerate Response.setheader ("Pragma", "No-cach", every time this page is accessed) 
    E "); 
    Response.setheader ("Cache-control", "No-cache");
    Response.setdateheader ("Expires", 0);
    Response.setcontenttype ("Image/jpeg");
    int width=40;
    int height=30;
  Generates an anonymous object for the Authenticode, and generates a validation code new Checkcode (). GetCode (Width,height,request,response); public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, ioexcept
  Ion {doget (request, response); }

}


defines the tool class
Dbutil class


Package com.vs2022.utils; 
Import java.sql.*;

Import Com.vs2022.model.User;

  public class Dbutil {Boolean binited = false; Load driver public void Initjdbc () throws ClassNotFoundException {//load MySQL JDBC driver class.forname ("Com.mysql.jdbc .
    Driver ");
    Binited = true;

  System.out.println ("Success loading Mysql driver!"); Public Connection getconnection () throws ClassNotFoundException, SQLException {if (!binited) {INITJ
    DBC ();
        The///connection URL is jdbc:mysql//server address/Database name//The following 2 parameters are login username and password Connection conn = drivermanager.getconnection (
    "jdbc:mysql://localhost:3306/database", "username", "password");
  Return conn;
    public boolean loginsuccess (string userName, String password) {Boolean returnvalue = false; String sql = "SELECT * from user where username=?"
    and password=? ";
    Connection conn = null;
    PreparedStatement Ps=null;

    int i=0;
      try {conn = getconnection ();
      Ps=conn.preparestatement (SQL); PS.setstring (1, userName);
      Ps.setstring (2, password);
      ResultSet Rs=ps.executequery ();
      if (Rs.next ()) {returnvalue=true;
    } catch (ClassNotFoundException e) {e.printstacktrace ();
    catch (SQLException e) {e.printstacktrace ();
  Return returnvalue;
    public boolean updateuser (user user) {Boolean flag=false;
    int i=0;
    Connection Conn=null;  
    PreparedStatement Ps=null; 
    String sql= "INSERT into User (Username,password,nickname,email) VALUES (?,?,?,?)";
      try {conn = getconnection ();
      Ps=conn.preparestatement (SQL); Ps.setstring (1, User.getusername ());
      Sets the value for the placeholder, which starts at 1, the first argument is the position of the placeholder, and the second parameter is the value of the placeholder.
      Ps.setstring (2, User.getpassword ());
      Ps.setstring (3, User.getnickname ());
      Ps.setstring (4, User.getemail ());
      I=ps.executeupdate ();
      if (i>0) {flag=true;
    } catch (ClassNotFoundException e) {e.printstacktrace (); }catch (SQLException e) {
      E.printstacktrace ();
  return flag;
    public boolean serchusername (String userName) {Boolean returnvalue = false;
    String sql = "SELECT * from user where username=?";
    Connection conn = null;
    PreparedStatement Ps=null;
      try {conn = getconnection ();
      Ps=conn.preparestatement (SQL);
      Ps.setstring (1, userName);
      ResultSet Rs=ps.executequery ();
      if (Rs.next ()) {returnvalue=true;
    } catch (ClassNotFoundException e) {e.printstacktrace ();
    catch (SQLException e) {e.printstacktrace ();
  Return returnvalue;
    public boolean serchemail (String email) {Boolean returnvalue = false;
    String sql = "SELECT * from user where email=?";
    Connection conn = null;
    PreparedStatement Ps=null;
    int i=0;
      try {conn = getconnection ();
      Ps=conn.preparestatement (SQL);
      Ps.setstring (1, email);
      ResultSet Rs=ps.executequery (); if (Rs.next ()) {ReturnvaLue=true;
    } catch (ClassNotFoundException e) {e.printstacktrace ();
    catch (SQLException e) {e.printstacktrace ();
  Return returnvalue;
 }
}




Related Article

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.