Simple-Sealed User Login example for HttpServlet, example of user login combined with JDBC

Source: Internet
Author: User

Let's look at the user login example for HttpServlet

This small example encapsulates the servlet and request in a small
The requirement is to configure the username and password in web.xml, and then log in via HTML, jump to the servlet, and get configuration information via Getservletcontext (). Getinitparameter. Then obtain the request information through the Req.getparameter, if the username, the password matches correctly then the output succeeds can

First look at the configuration file:

    <!--configuration servlet-->
    <context-param>
        <param-name>user</param-name>
        < param-value>wyf</param-value>
    </context-param>
    <context-param>
        <param-name >password</param-name>
        <param-value>123456</param-value>
    </context-param>
   <servlet>
    <servlet-name>loginServlet</servlet-name>
    <servlet-class> com.safly.loginservlet2</servlet-class>
  </servlet>

  <servlet-mapping>
    < Servlet-name>loginservlet</servlet-name>
    <url-pattern>/loginServlet</url-pattern>
  </servlet-mapping>


Then look at a simple HTML interface login.html

<! DOCTYPE html>

Mygenericservlet

Package com.safly;
Import java.io.IOException;

Import java.util.Enumeration;
Import Javax.servlet.Servlet;
Import Javax.servlet.ServletConfig;
Import Javax.servlet.ServletContext;
Import javax.servlet.ServletException;
Import Javax.servlet.ServletRequest;

Import Javax.servlet.ServletResponse; Public abstract class Mygenericservlet implements Servlet, ServletConfig {public void Destroy () {} public S
    Ervletconfig Getservletconfig () {return servletconfig;
    Public String Getservletinfo () {return null;
    Private ServletConfig ServletConfig;
        public void init (ServletConfig config) throws servletexception {this.servletconfig = config;
    Init (); private void Init () throws servletexception {} public abstract void service (ServletRequest req, servletres

    Ponse Res) throws Servletexception, IOException; The following are implementation methods for ServletConfig public string Getinitparameter (string arg0) {return serVletconfig.getinitparameter (arg0);
    Public enumeration Getinitparameternames () {return servletconfig.getinitparameternames ();
    Public ServletContext Getservletcontext () {return servletconfig.getservletcontext ();
    Public String Getservletname () {return servletconfig.getservletname (); }
}

Myhttpservlet

Package com.safly;

Import java.io.IOException;
Import javax.servlet.ServletException;
Import Javax.servlet.ServletRequest;
Import Javax.servlet.ServletResponse;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;
            public class Myhttpservlet extends Mygenericservlet {public void service (ServletRequest req, servletresponse Res) Throws Servletexception, IOException {if (req instanceof httpservletrequest) {Httpservletre
            Quest request = (HttpServletRequest) req;
                if (res instanceof httpservletresponse) {httpservletresponse response = (httpservletresponse) res;
            Service (request, response); }} public void service (HttpServletRequest req, httpservletresponse res) throws Servletexce
        Ption, IOException {String method = Req.getmethod ();
        if (' Get '. Equalsignorecase (method)) {doget (req, res); } else if ("POST". Equalsignorecase (method)) {DoPost (req, res);

    } public void DoPost (HttpServletRequest req, httpservletresponse res) throws IOException {} public void Doget (HttpServletRequest req, httpservletresponse res) throws IOException {}}

LoginServlet2

Package com.safly;

Import java.io.IOException;
Import Java.io.PrintWriter;

Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

public class LoginServlet2 extends Myhttpservlet {public
    void DoPost (HttpServletRequest req, httpservletresponse Res)
            throws IOException {
        String username = req.getparameter ("user");
        String Password = req.getparameter ("password");

        String Inituser = Getservletcontext (). Getinitparameter ("user");
        String Initpassword = Getservletcontext (). Getinitparameter ("password");

        PrintWriter pw = Res.getwriter ();
        if (inituser.equals (username) && initpassword.equals (password)) {
            pw.print ("Helloo:" + username);
        } else {
            Pw.print ("sorryy:" + username);
        }
    }
}


To debug:
Http://localhost:8080/day01/login.html
Input wyf,123456
Then the browser output HELLOO:WYF the correct checksum
If output error output Sorryy:www (username entered is www)
Http://localhost:8080/day01/loginServlet

Examples of user logins combined with JDBC
The overall process is to create a user database that contains the names and passwords of the users logged in
Then through the HTML page login, jump to the servlet, through the req.getparameter to get the corresponding value, build SQL statements, JDBC database links to query whether the database has user information, if any, on the output login success can


The above is to create the MyDatabase database, and then create the user table, the fields are username, password

Before looking at the code, because JDBC is a database connection pool, some methods need to use the Mysql-connector-java-5.1.7-bin.jar
Just throw it under the web-inf-lib.


Let's take a look at Web.xml configuration information first:

    <!--configuration servlet-->
    <servlet>
        <servlet-name>loginServlet</servlet-name>
        < servlet-class>com.safly.loginservelt3</servlet-class>
    </servlet>
    <servlet-mapping >
        <servlet-name>loginServlet</servlet-name>
        <url-pattern>/loginservlet</ Url-pattern>
    </servlet-mapping>

Next, look at the HTML interface, just a username, password box

<form action= "Loginservlet" method= "POST" >
        user:<input type= "text" name= "username"/> password:< Input type= "text"
            name= "password"/><br> <input type= "Submit" value= "Submit"/>
    </form >

Then there's the servlet.

Package com.safly;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import Java.sql.DriverManager;
Import Java.sql.ResultSet;

Import java.sql.SQLException;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;
            public class LOGINSERVELT3 extends HttpServlet {public void DoPost (HttpServletRequest req, HttpServletResponse resp)
        Throws Servletexception, IOException {String username = req.getparameter ("username");
        String Password = req.getparameter ("password");

        System.out.println ("Username:" +username+ ", Password:" +password);
        Java.sql.Connection Connection = null;
        Java.sql.PreparedStatement statement = null;

        ResultSet ResultSet = null;
        PrintWriter pw = Resp.getwriter ();
            try {class.forname ("com.mysql.jdbc.Driver"); String url = "Jdbc:mysql://127.0.0.1:3306/mydatAbase ";
            String user = "root";
            String password2 = "root";


            Connection = drivermanager.getconnection (URL, user, password2); String sql = "SELECT count (ID) from user where username=?"

            and password=? ";
            statement = connection.preparestatement (SQL);
            Statement.setstring (1, username);

            Statement.setstring (2, password);


            ResultSet = Statement.executequery ();
                if (Resultset.next ()) {int count = Resultset.getint (1);
                System.out.println ("Resultset.count1:" +count);
                if (count = = 1) {pw.print ("Hello" + username);
                else {pw.print ("sorry" + username);
        A catch (Exception e) {e.printstacktrace ());
                finally {if (ResultSet!= null) {try {resultset.close (); } catch (SQLException e) {e.printstacktrace ();
                } if (statement!= null) {try {statement.close ();
                catch (SQLException e) {e.printstacktrace ();
                } if (connection!= null) {try {connection.close ();
                catch (SQLException e) {e.printstacktrace (); }
            }
        }
    }
}

Browser debugging:
Http://localhost:8080/day01/login.html
Enter WYFF, WYF

This shows that Wyff, WYF has 2 records in the database
The judge here is not strictly prohibited

if (count = = 1) {
                    pw.print ("Hello" + username);
                } else {
                    pw.print ("sorry" + username);
                }

On the output sorrywyff

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.