index.jsp
<body> <jsp:forward page= "/web-inf/login.jsp" ></jsp:forward> </body>
for security, the JSP page is generally set under the Web-inf directory. Then leave an entrance and go to Web-inf to jump.
login.jsp
<body style= "Text-align:center; margin:0 Auto; >
A simple login page, enter user name and password, submit to gohallui this servlet processing
Gohallui
public class Gohallui extends HttpServlet {public void doget (HttpServletRequest request, httpservletresponse response) Throws Servletexception, IOException {response.setcontenttype ("text/html;charset=utf-8"); PrintWriter out=response.getwriter ();//Get the user ID and password passed from the landing page string id=request.getparameter ("id"); String p=request.getparameter ("password");//First determine if the user is logged on or if the session where the user has logged in has expired if (Request.getsession (). getattribute ("Loginuser")!=null) {//Prepare the data to be displayed for the next page Bookservice bookservice=new Bookservice (); ArrayList Al=bookservice.getallbook ();//Put the data to be displayed on request because of the shortest life cycle of the request Request.setattribute ("books", AL); Request.getrequestdispatcher ("/web-inf/hall.jsp"). Forward (request, response); return;//Don't go down! }//Create a Users object ()//string->intusers loginuser=new users (Integer.parseint (ID), p);//Use the business logic class to complete the validation. Usersservice usersservice=new Usersservice (); if (Usersservice.checkuser (Loginuser)) {//description is a legitimate user, jump to the shopping hall.// Put the user information into the session request.getsession (). SetAttribute ("Loginuser", loginuser);//Create a shopping cart Mycart mycart=new mycart (); rEquest.getsession (). SetAttribute ("Mycart", mycart);//to the next page hall.jsp prepare the data to be displayed Bookservice bookservice=new Bookservice (); ArrayList Al=bookservice.getallbook ();//Put the data to be displayed in request, because the request object has a minimum life cycle of Request.setattribute ("books", AL); Request.getrequestdispatcher ("/web-inf/hall.jsp"). Forward (request, response);} else{//illegal Request.getrequestdispatcher ("/web-inf/login.jsp"). Forward (request, response);}} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { This.doget (request, Response);}}
This servlet has done a lot of work, for the time being the user login and verification.1. Create the Users Object
Users.java
Package com.wxh.domain;//This is a javabean that corresponds to the users table in the database. public class Users {private int id;private string Name;private string pwd;private string Email;private string tel;private int grade;public Users (int id, String pwd) {super (); this.id = Id;this.pwd = pwd;} public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public String getpwd () {return pwd;} public void SetPwd (String pwd) {this.pwd = pwd;} Public String Getemail () {return email;} public void Setemail (String email) {this.email = email;} Public String Gettel () {return Tel;} public void Settel (String tel) {This.tel = tel;} public int Getgrade () {return grade;} public void Setgrade (int grade) {This.grade = grade;}}
2. Using the Usersservice classUsersservice.java
Package Com.wxh.service;import java.util.ArrayList; Import Com.wxh.utils.*;import com.wxh.domain.users;//This is a class that specializes in dealing with business logic//processing and the Users table related business logic public class Usersservice {// Verify that the user is a legitimate method, and legitimately return other information for that user//not only to judge the user, but also to take the user itself as a data to use the public boolean checkUser (users user) {//to the database to verify string sql= " SELECT * from users where id=? and pwd=? "; String Paras[]={user.getid () + "", User.getpwd ()}; ArrayList al=new SqlHelper (). executeQuery (SQL, paras); if (Al.size () ==0) {return false;} Else{object[] objects= (object[]) al.get (0);//encapsulates an object array into the Users object User.setname ((String) objects[1]); User.setemail (( String) (objects[3]); User.setgrade (Integer.parseint (objects[5].tostring ()));//The user's other information needs to be removed after the login, So encapsulate to an object return true;}}}
here Usersservice also calls the SqlHelper class to complete some operations on the database. Sqlhelper.java
This is a tool class that is used primarily to complete CRUD operations on databases public class SqlHelper {private static Connection ct=null;//connection private static ResultSet Rs=null ;//result private static PreparedStatement ps=null;public ArrayList executeQuery (String sql,string []paras) {ArrayList al= New ArrayList (); try {Ct=dbutil.getcon ();p s=ct.preparestatement (SQL);//Assign a value of SQL question mark for (int i = 0; i < paras.length; i++) { Ps.setstring (i+1, paras[i]);} Rs=ps.executequery ()///Very useful resultsetmetadata rsmd=rs.getmetadata ();//Usage RS can be to how many columns int columnnum= Rsmd.getcolumncount ();//Loop out data from A1 encapsulated to Arraylistwhile (Rs.next ()) {Object []objects=new object[columnnum];for (int i=0 ; i<objects.length;i++) {objects[i]=rs.getobject (i+1);//Returns an array of objects}al.add (objects);} Return al;} catch (Exception e) {e.printstacktrace (); throw new RuntimeException (E.getmessage ());} Finally{dbutil.close (RS,PS,CT);}} Public ResultSet executeQuery (String sqlstr) {Statement stmt = null;try{//Get Connected Ct=dbutil.getcon ();//ps= Ct.preparestatement (sqlstr); stmt = Ct.createstatement ();//Create result Set rs = Stmt.executequery (sqlstr); Returns the result set to return RS; catch (SQLException e) {System.out.print ("error");} return null;}}
The Dbutil class is used here again.Dbutil.java
This is the database Tools class for getting connections and closing connections public class Dbutil {private static Connection ct=null;//connection private static ResultSet rs=null;// Result private static PreparedStatement ps=null;//connection database parameter private static string url = "";p rivate static string drivername = "";p Rivate static string username = "";p rivate static string password = "";//Load driver Static{try {Properties properties=new Proper Ties (); InputStream Is=dbutil.class.getclassloader (). getResourceAsStream ("com/wxh/utils/dbinfo.properties"); Properties.load (IS);//property file read information Drivername=properties.getproperty ("Driver"); Username=properties.getproperty (" Username ");p assword=properties.getproperty (" password "); Url=properties.getproperty (" url ");} catch (Exception e) {e.printstacktrace (); System.exit (-1);}} Get connected public static Connection Getcon () {try {class.forname (drivername); ct= drivermanager.getconnection (url,username , password);//note configuration file} catch (Exception e) {e.printstacktrace ();} Return ct;//who calls who gets connection}public static void main (String args []) {System.out.println (DrivernAME); SYSTEM.OUT.PRINTLN (username); SYSTEM.OUT.PRINTLN (password); System.out.println (URL);} Close resource function public static void close (ResultSet rs,statement Ps,connection CT) {if (rs!=null) {try{rs.close ();} catch (Exception e) {}rs=null;//uses garbage collection}if (ps!=null) {try{ps.close ();} catch (SQLException e) {e.printstacktrace ();} Ps=null;} if (ct!=null) {try{ct.close ();} catch (SQLException e) {e.printstacktrace ();} Ct=null;}}}
Properties file that holds database connection parametersDbinfo.properties
Url=jdbc:oracle:thin:@127.0.0.1:1521:testdriver=oracle.jdbc.driver.oracledriver username=hr PASSWORD=HR
——— from "Hanshunping detail JSP"
Hanshunping the JSP Shopping cart project-User login and verification