Javaweb+jdbc+servlet+sqlserver Implementing the Login function

Source: Internet
Author: User

To create the Javaweb project first, you can refer to the following:

51013400

Attached Project structure:

1. Rewrite the contents of the login page index.jsp

<%--Created by IntelliJ idea. User:lxj ' PC date:2018/5/12 time:15:49 To change this template use File | Settings | File templates.--%><%@ page contenttype= "Text/html;charset=utf-8" language= "java"%>Package Org.user.util;import java.sql.*;p ublic class Dbutil {//mysql Drive pack name private static final String driver_name =    "Com.microsoft.sqlserver.jdbc.SQLServerDriver"; Database connection address private static final String URL = "Jdbc:sqlserver://localhost:1433;integratedsecurity=true;databasename=    Javaweb ";    User name private static final String user_name = ".";    Password private static final String PASSWORD = "";            public static Connection getconnection () {try {//load MySQL driver class class.forname (driver_name);        Get the database connection return drivermanager.getconnection (URL);            } catch (Exception e) {e.printstacktrace ();        return null; }} public static void Closeconn (Connection conn,statement stm, ResultSet rs) {if (stm!=null) {TR            y {stm.close ();            } catch (SQLException e) {e.printstacktrace ();       }} if (conn! = null) {try {         Conn.close ();            } catch (SQLException e) {e.printstacktrace ();            }} if (Rs!=null) {try{rs.close ();            }catch (SQLException e) {e.printstacktrace ();    }}} public static void Main (string[] args) {System.out.println (getconnection ()); }}

3. New Entity class user

Package Org.user.entity;public class User {    private String userName;    Private String PassWord;    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;    }}

4. New Class Userdao

Package Org.user.dao;import Java.sql.*;import Org.user.entity.user;import Org.user.util.dbutil;public class UserDao { Find user public based on username user finduserbyname (string userName) {//write SQL statement string sql= "select * from Login where        Username=? ";        Get Connected Connection conn= dbutil.getconnection ();        There is a return result ResultSet rs= null;        Instantiate a user object user user = new user ();            try {//PreparedStatement PS = conn.preparestatement (SQL) used to send SQL statements;            Set the parameters to pass in, here is Usern ps.setstring (1, userName);            Execute SQL statement rs=ps.executequery (); If you can find the result if (Rs.next ()) {//Then the found result one by one set into the user Object User.setusername (rs.getstring (1))                ;            User.setpassword (rs.getstring (2));        }} catch (SQLException e) {//TODO auto-generated catch block E.printstacktrace (); } finally {//close connection Dbutil.closeConn (Conn, NULL, RS);    }//The user is finally returned to return user;        } public static void Main (string[] args) {Userdao dao = new Userdao ();        User i = dao.finduserbyname ("Lxj");    System.out.println (I.getpassword ()); }}

5. New service class Loginservice

Package Org.user.service;import Org.user.dao.userdao;import Org.user.entity.user;public class LoginService {    public boolean CheckUser (String userName, String passWord) {        Userdao dao = new Userdao ();        User user = Dao.finduserbyname (userName);        SYSTEM.OUT.PRINTLN (user);        return user! = null && password.equals (User.getpassword ())? True:false;}    }

6. New Servlet class Loginservlet

Package Org.user.servlet;import Java.io.ioexception;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 Org.user.dao.UserDao; Import Org.user.entity.user;import Org.user.service.LoginService; @WebServlet (name = "Loginservlet") public class    Loginservlet extends HttpServlet {private static final long serialversionuid = 1L; The Sqljdbc_auth.dll file was placed under the D:\java-jdk8\bin path of this computer, and the unsuccessful login problem protected void service (HttpServletRequest request) was resolved. HttpServletResponse response) throws Servletexception, IOException {//Set encoding request.setcharacterencoding ("UT        F-8 ");        Response.setcharacterencoding ("Utf-8");        Gets the data submitted from the page String userName = Request.getparameter ("UserName");        String Userpass = Request.getparameter ("PassWord");        Loginservice service = new Loginservice (); Call the service method to set the user name secretThe code is passed to service Boolean flag = Service.checkuser (UserName, Userpass); String msg = flag? "        Success ":" Error ";        Request.setattribute ("msg", MSG);        if (msg== "Success") {Request.getrequestdispatcher ("login_success.jsp"). Forward (request, response);        } else{Request.getrequestdispatcher ("login_failure.jsp"). Forward (request, response); }    }}

7. Finally, the new login_success.jsp and login_failure.jsp files in the index.jsp sibling directory are used for login success or failure jump page prompts.

Tip: If a warning appears: Failed to load the Sqljdbc_auth.dll cause:-No sqljdbc_auth in Java.library.path, you can put Sqljdbc_auth.dll The file is placed in the Bin folder in your point JDK directory, for example, the D:\java-jdk8\bin path of my own computer is put into the Sqljdbc_auth.dll file

Javaweb+jdbc+servlet+sqlserver Implementing the Login function

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.