"Servlet" Connection MySQL implementation verification password login (with detailed analysis and Lib attachment)

Source: Internet
Author: User
Tags oracleconnection

These days have been the content of repeated learning, servlet,filter,session,mysql,jsp.

Today with a complete small project as a summary of the basics of getting started with BS.

The user enters the user name and password on the JSP page, passes through the filter to enter the servlet, matches the data in the database, the password and the user name input is correct, jumps the Welcome interface, otherwise returns the login page to reenter.


Project Projectone_firsttrybs are:

SRC below are: Four package (Servlet,filter,model,util) and one database profile jdbc.properties.

Underneath the webcontent are: Jsp,meta-inf,web-inf and Web. Xml.

Specific index


Lib has a lot of class library, I compressed into. rar on the resources.


I use tomcat3.0 here, so web. XML is not configured by itself.


First, I wrote three JSP pages: login.jsp, error.jsp,welcome.jsp. Login is responsible for user input user name and password, is a login page, error is the user input error when the jump to a transit page; Welcome is the Welcome page for landing success. The images folder has a background image bg.jpg.

login.jsp

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><%@ page import=" javax.servlet.http.* "%><%@ page import=" Com.yan.model.User "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >Under the Form tab, action points to the servlet file under your project, because the servlet has a user name and password in the validation database, and filter is entered after each request by default. Under normal circumstances, the servlet should be entered through the filter.


error.jsp

<%@ 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" >
There's only one button on my error.jsp that returns login.jsp to get the address back from the servlet login.jsp


welcome.jsp

<% @page import= "com.yan.model.User"%><%@ 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" >In the script, the user class is placed inside the session to get the username and password entered by the user, and the corresponding ID in the database.


Web. XML is also put up, so far, the content of webcontent is over.

<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://java.sun.com/xml/ns/javaee" xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee/http Java.sun.com/xml/ns/javaee/web-app_3_0.xsd "id=" webapp_id "version=" 3.0 ">  <display-name>projectone_ firsttrybs</display-name>  <welcome-file-list>    <welcome-file>index.html</ welcome-file>    <welcome-file>index.htm</welcome-file>    <welcome-file>index.jsp</ welcome-file>    <welcome-file>default.html</welcome-file>    <welcome-file>default.htm </welcome-file>    <welcome-file>default.jsp</welcome-file>  </welcome-file-list>  </web-app>


SRC inside, I first put the configuration of the database, and then the specific servlet and filter implementation. Because the database directly copied the past, do not understand.

Jbdc.porpertise

#mysql DB Properties#mysql_db_driver_class=com.mysql.jdbc.driver#mysql_db_url=jdbc:mysql://localhost:3306/userdb        //3306 is the port number of my connection to MYSQL, you write your #mysql_db_username=pankaj#mysql_db_password=pankaj123#oracle DB propertiesoracle_db _driver_class=oracle.jdbc.driver.oracledriver#oracle_db_url=jdbc:oracle:thin:@192.168.100.36:1521:tfsoracle_db _url=jdbc:oracle:thin:@10.50.9.63:1521:orcloracle_db_username=pbyl1030oracle_db_password=pbtestforhr2014# Oracle DB Properties 2oracle_db_driver_class2=oracle.jdbc.driver.oracledriveroracle_db_url2=jdbc:oracle:thin:@ 192.168.100.36:1521:easdbtestoracle_db_username2=pbyl1030oracle_db_password2= PBYL20140418FORTESTMYSQLDRIVERCLASS=COM.MYSQL.JDBC.DRIVERMYSQLJDBCURL=JDBC:MYSQL://Host IP Address: port number/library name mysqluser= rootmysqlpassword= your password to log in to MySQL



Oracleconnection.java

Package Com.yan.util;import Java.io.filenotfoundexception;import Java.io.ioexception;import java.io.InputStream; Import Java.sql.connection;import java.sql.sqlexception;import java.util.properties;import javax.sql.DataSource; Import Org.apache.commons.dbcp.basicdatasource;import Org.apache.commons.dbutils.queryrunner;public class        OracleConnection {private static DataSource DataSource; private static void Initoracle () {Properties props = new Properties (); InputStream in = Null;//props.load (tosaveerr          Log.class.getClassLoader (). getResourceAsStream ("save2logdb.properties"));              try {in = OracleConnection.class.getClassLoader (). getResourceAsStream ("jdbc.properties"); Props.load (in);} catch (FileNotFoundException e) {System.out.println ("jdbc.properties not Found"); E.printstacktrace ();} catch (        IOException e) {System.out.println ("read error in Jdbc.properties"); E.printstacktrace ();} Basicdatasource Dbcpdatasource = new Basicdatasource();        Dbcpdatasource.seturl (Props.getproperty ("Mysqljdbcurl"));        Dbcpdatasource.setdriverclassname (Props.getproperty ("Mysqldriverclass"));        Dbcpdatasource.setusername (Props.getproperty ("Mysqluser"));        Dbcpdatasource.setpassword (Props.getproperty ("Mysqlpassword"));        Dbcpdatasource.setdefaultautocommit (TRUE);        Dbcpdatasource.setmaxactive (10);        Dbcpdatasource.setmaxidle (5);        Dbcpdatasource.setmaxwait (500);        Oracleconnection.datasource = (dataSource) Dbcpdatasource;    System.out.println ("Initialize dbcp ..."); } public static Connection getconnection () {try {if (oracleconnection.datasource==null) {Inito    Racle ();        return OracleConnection.dataSource.getConnection ();        }else {return OracleConnection.dataSource.getConnection (); }} catch (SQLException e) {e.printstacktrace ();}    return null; } public static Queryrunner Getqueryrunner () {if (ORACLECONNECTION.DATASOURCE==null) {initoracle ();        return new Queryrunner (Oracleconnection.datasource);        }else {return new Queryrunner (Oracleconnection.datasource); }    }}


User.java, the variables in the inside of your database in the field, such as my database has three fields id,name,passwd, then the User.java inside the three string should also be id,name,passwd.

Where the name and passwd are user-defined, and the ID is not known to the user, I define the ID in the database is (write not the formal grammar, you can understand the line):

' ID ' (int (8), not NULL, AUTO INCREMENT, PRIMARY KEY)

Here's User.java.

Package Com.yan.model;import Java.io.serializable;public class User implements Serializable {private static final long SE Rialversionuid = -1734127774270588940l;private string Id;private string name;private string Passwd;public string GetId () {return ID;} public void SetId (String id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public String getpasswd () {return passwd;} public void setpasswd (String passwd) {this.passwd = passwd;}}


There are two filter files in the filter package, Logfilter.java and Authorityfilter.java,log are log filters that record requests from the beginning to the end of the process; The authority is a path filter that intercepts or releases each access situation.

Logfilter.java

Package Com.yan.filter;import Java.io.ioexception;import Javax.servlet.filter;import javax.servlet.FilterChain; Import Javax.servlet.filterconfig;import Javax.servlet.servletcontext;import javax.servlet.ServletException; Import Javax.servlet.servletrequest;import Javax.servlet.servletresponse;import Javax.servlet.annotation.webfilter;import javax.servlet.http.httpservletrequest;//log filter, record login filter information, can be displayed in the console, You can also enter database @webfilter (filtername = "Logfilter", Urlpatterns = {"/*"}) public class Logfilter implements Filter {private    Filterconfig Fconfig;    public void init (Filterconfig fconfig) throws servletexception {this.fconfig = Fconfig;}        public void Destroy () {this.fconfig = null;} Core filtering section public void DoFilter (ServletRequest request, servletresponse response, Filterchain chain) throws IOException, servletexception {/*---------The following code is used to preprocess a user request---------*//Get ServletContext object for logging ServletContext cont     ext = This.fConfig.getServletContext (); Long before = System.currenttimemillis ();        System.out.println ("Start filtering ...");        Convert requests to httpservletrequest requests HttpServletRequest hrequest = (httpservletrequest) request;        Log Context.log ("filter has intercepted the user's request address:" + hrequest.getservletpath ());         Filter is only chained, the request is still released to the destination address chain.dofilter (request, response);        /*---------The following code is used to perform post-processing on the server response---------*/long after = System.currenttimemillis ();        Log Context.log ("Filter End");        Record the log Context.log again ("The request was located to" + Hrequest.getrequesturi () + "time Spent:" + (After-before));} Public Logfilter () {}}


Authorityfilter.java

Package Com.yan.filter;import Java.io.ioexception;import Javax.servlet.filter;import javax.servlet.FilterChain; Import Javax.servlet.filterconfig;import Javax.servlet.servletexception;import javax.servlet.ServletRequest; Import Javax.servlet.servletresponse;import Javax.servlet.annotation.webfilter;import Javax.servlet.annotation.webinitparam;import Javax.servlet.http.httpservletrequest;import javax.servlet.http.httpsession;//Login filter, log whether the user is logged in @webfilter (filtername = "Authorityfilter", Urlpatterns = {"/*"}, InitParams = {@WebInitParam (name = "Encoding", value = "GBK"), @WebInitParam (name = "LoginPage", value = "/jsp/login.jsp"), @WebInitParam (name = "Checkservlet", value = "/checkservlet"), @WebInitParam (name = "Prologin", value = "/jsp/welcome.jsp    ")}) public class Authorityfilter implements Filter {private Filterconfig fconfig; Public Authorityfilter () {}public void Destroy () {this.fconfig = null;} public void DoFilter (ServletRequest request, servletresponse response, Filterchain chain) throwS IOException, servletexception {//Gets the configuration parameter of the filter string encoding = Fconfig.getinitparameter ("encoding"); String LoginPage = Fconfig.getinitparameter ("LoginPage"); String Prologin = Fconfig.getinitparameter ("Prologin"); String Checkservlet = Fconfig.getinitparameter ("Checkservlet");//sets the character set for the request encoding request.setcharacterencoding ( encoding); HttpServletRequest requ = (httpservletrequest) request; HttpSession session = Requ.getsession (true);//Get Customer Request page String requestpath = Requ.getservletpath ();// If the user of the session range is null, that is, there is no login//and users are requesting neither the landing page nor the login page/* 1. If user is null, that is never logged in, you should jump to the login page * 2. If users are not accessing the login page, You should jump to the login page * 3. If the user has not visited Checkservlet, you should jump to the login page * */if (Session.getattribute ("user") = = null &&!requestpath. EndsWith (LoginPage) &&!requestpath.endswith (Checkservlet)) {//forward to login page request.setattribute ("Tip", " You are not logged in "); Request.getrequestdispatcher (LoginPage). Forward (request, response);} else {//"release" Request Chain.dofilter (request, Response);}} public void init (Filterconfig FconFig) throws Servletexception {this.fconfig = Fconfig;}} 


The process of Checkservlet.java is mainly: extracting parameters from login.jsp, connecting database, judging, jumping

Package Com.yan.servlet;import Java.io.ioexception;import Java.sql.resultset;import java.sql.sqlexception;import Java.util.arraylist;import Java.util.list;import Javax.servlet.servletexception;import Javax.servlet.annotation.webservlet;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Javax.servlet.http.httpsession;import Javax.swing.joptionpane;import Org.apache.commons.dbutils.handlers.beanlisthandler;import Com.mysql.jdbc.connection;import Com.mysql.jdbc.preparedstatement;import Com.yan.model.user;import Com.yan.util.oracleconnection;import java.awt.* ; import Javax.swing.*;import java.util.regex.*; @WebServlet ("/checkservlet") public class Checkservlet<attenaudit    > extends HttpServlet {private static final long serialversionuid = 1L;    Public Checkservlet () {super (); } public void process (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexception {System.out.println ("Start executing Checkservlet.java now");    String u = request.getparameter ("username");            String p = request.getparameter ("passwd"); String sql = "SELECT * from User where name =?" and passwd =?            " ; The U and P are placed inside the object and passed to userlist list<user> userlist = new arraylist<user> (); try {userlist = Oracleconnection.get Queryrunner (). query (SQL, new beanlisthandler<user> (User.class), New Object[]{u,p});}    catch (SQLException e) {e.printstacktrace ();} UserList content is not NULL represents the combination of user name and password entered exists in the database; null indicates username or password error if (userlist.size () >0) {HttpSession session = Request.getses    Sion (TRUE);         Session.setattribute ("User", Userlist.get (0));    Take the first set of values inside the userlist object[u,p] Request.getrequestdispatcher ("/jsp/welcome.jsp"). Forward (request, response); } else {joptionpane.showmessagedialog (null, "username or password is wrong, please re-enter!)    "," Oops, "joptionpane.warning_message); Response.sendredirect ("..    /jsp/error.jsp "); Request.getrequestdispatcher ("/jSp/error.jsp "). Forward (request, response); }} protected void Doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioex ception {process (request, response);} protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Process (request, response);}}


Next, start the test.

First you start Tomcat, then enter http://localhost:8080/ProjectOne_FirstTryBS/login.jsp in the browser and enter login.jsp


If you enter an error, there will be a pop-up window, which will be reflected on the console.



Jump to error.jsp and back to login.jsp. Enter the correct words,


It can be extracted from welcome.jsp from the following statement by passing the argument.

Request.getrequestdispatcher ("/jsp/welcome.jsp"). Forward (request, response);



Above, is the whole process.



"Servlet" Connection MySQL implementation verification password login (with detailed analysis and Lib attachment)

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.