JSP implement user login, registration and Exit Function _jsp programming

Source: Internet
Author: User
Tags comments trim oracle database

This article describes the use of JSP to implement user login, including user login, registration and exit functions.

1. System use case diagram

2. Page Flow chart

3. Database design
This example uses the Oracle database

Create a user table

Includes Id,username,password and email, a total of 4 fields

--Create TABLE 
CREATE TABLE P_user 
( 
 ID  VARCHAR2 () not NULL, 
 username VARCHAR2, 
 Password VARCHAR2, 
 email VARCHAR2) 
tablespace USERS 
 pctfree 
 1 
 Maxtrans 255 
 Storage 
 ( 
 initial minextents 
 1 
 maxextents 
 ); 
--ADD comments to the table 
Comment in table p_user is 
 ' user table '; 
--ADD comments to the columns 
comment in column p_user.id is 
 ' id '; 
Comment on column p_user.username is 
 ' username '; 
Comment on column p_user.password is 
 ' password '; 
Comment on column p_user.email is 
 ' email '; 

4. Page Design
4.1 login page
login.jsp

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <% String Path = Request.getcontextpath () 
; 
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >  

Page effects

3.2 Login Logic Processing page
login_action.jsp

<%@ page language= "java" import= "java.util.*" pageencoding= "utf-8"%> <%@ page import= "java.sql.*"%> 
String path = Request.getcontextpath (); 
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; 
 %> <% String username = request.getparameter ("username"); 
 String Password = request.getparameter ("password"); if (username==null| | "". Equals (Username.trim ()) | | password==null| | "". Equals (Password.trim ())) {//out.write ("User name or password cannot be empty!") 
  "); System.out.println ("User name or password cannot be empty!") 
  "); 
  Response.sendredirect ("login.jsp"); 
  Return 
 Request.getrequestdispatcher ("login.jsp"). Forward (request, response); 
 Boolean isValid = false; Connection con = null;//Create a database connection PreparedStatement pre = null;//Create Precompiled statement objects, usually with this instead of statement ResultSet result = Nu ll;//Create a result set object try {class.forname ("oracle.jdbc.driver.OracleDriver");//Load the Oracle driver//system.out.println ("Start tasting Try connecting to the database! 
  "); String url = "Jdbc:oracle:"+" THIN:@127.0.0.1:1521:ORCL;//127.0.0.1 is the native address, ORCL is Oracle's default database name string user = "Scott";//username, system default account name string PW D = "Tiger";//You install the password of the selected settings con = drivermanager.getconnection (url, user, pwd);//Get Connection//SYSTEM.OUT.PRINTLN ("Connection successful!") 
  "); String sql = "SELECT * from P_user where username=?" and password=? ";/ /precompiled statement, "? "represents the parameter pre = con.preparestatement (SQL);//Instantiate Precompiled Statement pre.setstring (1, username);//Set parameters, the preceding 1 represents the index of the parameter, not the index of the column name in the table PRE.S Etstring (2, password);//Set parameters, the preceding 1 indicates the index of the parameter, not the index result = Pre.executequery () of the column name in the table;//execute the query, note that the parentheses do not need to add the parameter if (Result.nex 
  T ()) {isValid = true; 
 } catch (Exception e) {e.printstacktrace (); 
    Finally {try {///one of the above objects will be closed, because it will affect performance and resource//attention to the order of shutdown, and the last use of the first close if (Result!= null) 
   Result.close (); 
   if (pre!= null) Pre.close (); 
   if (con!= null) con.close (); SYSTEM.OUT.PRINTLN (The database connection is closed!) 
  "); 
  catch (Exception e) {e.printstacktrace (); } if (isValid) {SysTEM.OUT.PRINTLN ("Login successful!") 
  "); 
  Session.setattribute ("username", username); 
  Response.sendredirect ("welcome.jsp"); 
 Return }else{System.out.println (Login failed!) 
  "); 
  Response.sendredirect ("login.jsp"); 
 Return 
 }%>

Use JDBC to connect to the database, or jump to the login page if the user name or password is empty login.jsp
If the username and password are not empty, connect to the database query user table, if you can query the record, indicating successful login, save the user information to the session, jump to the Welcome page welcome.jsp

If no record is queried based on user name and password, login fails, login.jsp to login page

3.3 Welcome Page
welcome.jsp

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <% String Path = Request.getcontextpath () 
; 
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >  

Displaying user information with El expressions
Effect


3.4 Welcome page Exit Logical Processing page
loginout.jsp

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <% String Path = Request.getcontextpath () 
; 
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >  

Remove user information from session, jump to login page login.jsp
3.5 registration page
register.jsp

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <% String Path = Request.getcontextpath () 
; 
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >  

Open the User registration page when clicking "Register" on the login page
Effect

3.6 Registering the Logical processing page
register_action.jsp

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <%@ page import= "java.sql.*"%> 
String path = Request.getcontextpath (); 
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; 
 %> <% String username = request.getparameter ("username"); 
 String Password1 = Request.getparameter ("Password1"); 
 String Password2 = Request.getparameter ("Password2"); 
 String email = request.getparameter ("email"); if (username==null| | "". Equals (Username.trim ()) | | password1==null| | "". Equals (Password1.trim ()) | | password2==null| | "". Equals (Password2.trim ()) | |! Password1.equals (Password2)) {//out.write ("User name or password cannot be empty!") 
  "); System.out.println ("User name or password cannot be empty!") 
  "); 
  Response.sendredirect ("register.jsp"); 
  Return 
 Request.getrequestdispatcher ("login.jsp"). Forward (request, response); 
 Boolean isValid = false; Connection con = null;//Create a database connection PreparedStatement pre = null;//Create Precompiled statement objects, usually with this instead of statement
 ResultSet results = null;//Create a result set object try {class.forname ("oracle.jdbc.driver.OracleDriver");//Load Oracle driver// System.out.println ("Start trying to connect to the database!") 
  ");  String url = "Jdbc:oracle:" + "THIN:@127.0.0.1:1521:ORCL";//127.0.0.1 is a native address, ORCL is the default database name for Oracle string user = "Scott"; Username, system default account name String pwd = "Tiger";//You install the password of the selected settings con = drivermanager.getconnection (url, user, pwd);/Get Connection//syst EM.OUT.PRINTLN ("Connection successful!") 
  "); String sql = "SELECT * from P_user where username=?"; /precompiled statement, "? "represents the parameter pre = con.preparestatement (SQL);//Instantiate Precompiled Statement pre.setstring (1, username);//Set parameters, the preceding 1 represents the index of the parameter, not the index of the column name in the table Resul t = pre.executequery ()///Execute query, note that no additional parameters are required in parentheses if (!result.next ()) {sql = INSERT into P_user (Id,username,password,ema IL) VALUES (?,?,?,?) "; /precompiled statement, "? "represents the parameter pre = con.preparestatement (SQL);//Instantiate Precompiled Statement pre.setstring (1, System.currenttimemillis () +" ");/set parameter, preceding 1 indicates parameter Index, not the index pre.setstring (2, username) of the column names in the table,//Set parameters, the preceding 1 represents the index of the parameter, not the index of the column name in the table pre.setstring (3, Password1//Set parameter, the preceding 1 represents the index of the parameter, not the index pre.setstring (4, email) of the column name in the table;//Set the parameter, the preceding 1 represents the index of the parameter, not the index of the column name in the table Pre.executeupdate ();//Execute 
  IsValid = true; 
 } catch (Exception e) {e.printstacktrace (); 
    Finally {try {///one of the above objects will be closed, because it will affect performance and resource//attention to the order of shutdown, and the last use of the first close if (Result!= null) 
   Result.close (); 
   if (pre!= null) Pre.close (); 
   if (con!= null) con.close (); SYSTEM.OUT.PRINTLN (The database connection is closed!) 
  "); 
  catch (Exception e) {e.printstacktrace (); } if (isValid) {SYSTEM.OUT.PRINTLN registered successfully, please log in! 
  "); 
  Response.sendredirect ("login.jsp"); 
 Return }else{System.out.println ("User name already exists!") 
  "); 
  Response.sendredirect ("register.jsp"); 
 Return 
 }%>

First, determine if the username and password are null, and the password and confirm the password is consistent, if the above conditions are not valid, return to the registration page register.jsp
If the above conditions are true, according to the user name to the database query, if you can query the record, the user name already exists, return to the registration page register.jsp

If the query does not have a record, this user name can be used for registration, use JDBC to insert 1 records into the user table, and then jump to the login page login.jsp

4. Summary
This example uses JSP to implement user login, in the process of writing, mainly encountered 2 small problems.

4.1 After the query, it is important to note that if the record exists, it needs to use the IF (!result.next ()) instead of the while loop used in the usual query, especially when registering.

4.2 About the JSP page compile error problem.

When you use return in a JSP script, be cautious, and there is a good chance of a compilation error.

The processing method is that the JSP main page uses only the JSP small script, guaranteed that after return does not need to compile the content to be able.

The above is the use of JSP to achieve user login simple introduction, I hope to help you learn.

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.