Javaweb's Servlet Login demo

Source: Internet
Author: User

Simply write a demo for registering and logging in

The following processes are described first

(1) The front page gets the user name and password entered by the user

(2) Send the message to the servlet

(3) Servlet database query, return the results of the query

Create a database first, and then include the user name and password two fields

DROP TABLE IF EXISTS ' user ';
CREATE TABLE ' user ' (
' Password ' varchar (255) CHARACTER SET utf8mb4 DEFAULT NULL,
' username ' varchar (255) DEFAULT NULL
) Engine=innodb DEFAULT Charset=utf8;------------------------------
--Records of user
-- ----------------------------
INSERT into ' user ' VALUES (' 123 ', ' Yue ');
INSERT into ' user ' VALUES (' llll ', ' 121 '); Project structure such as the need to import packages

Front desk three pages: login.jsp<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "
pageencoding= "UTF-8"%>
<%@ taglib prefix= "C" uri= "Http://java.sun.com/jsp/jstl/core"%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<title>login</title>
<style type= "Text/css" >
#errormsg {
color:red;
}
</style>
<body>
<c:if test= "${not Empty errormsg}" >
<p id= "ErrorMsg" >${errormsg}</p>
</c:if>
<form action= "${pagecontext.request.contextpath}/userservlet?method=login" method= "POST" >
Username:<input type= "text" name= "username" value= "${username}"/>
Password:<input type= "password" name= "password"/>
<input type= "Submit" value= "Login"/>
</form>

</body>

register.jsp

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "
pageencoding= "UTF-8"%>
<%@ taglib prefix= "C" uri= "Http://java.sun.com/jsp/jstl/core"%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<title>register</title>
<body>
<c:if test= "${not Empty errormsg}" >
<p id= "ErrorMsg" >${errormsg}</p>
</c:if>
<form action= "${pagecontext.request.contextpath}/userservlet?method=register" method= "POST" >
Username:<input type= "text" name= "username" value= "${username}"/>
Password:<input type= "password" name= "password"/>
<input type= "Submit" value= "register"/>
</form>
</body>

succ.jsp

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "
pageencoding= "UTF-8"%>
<%@ taglib prefix= "C" uri= "Http://java.sun.com/jsp/jstl/core"%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">
<title>insert title here</title>
<body>
<c:choose>
<c:when test= "${empty user}" >
You are not logged in
</c:when>
<c:otherwise>
Welcome to ${user.username}
</c:otherwise>
</c:choose>
</body>

Dbutil,class

Package com.hpe.util;
Import Java.io.FileReader;
Import java.io.IOException;
Import java.sql.Connection;
Import Java.sql.DriverManager;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSet;
Import java.sql.SQLException;
Import Java.util.properties;public class Dbutil {
private static String drivatename = null;
private static String URL = null;
private static String username = null;
private static String password = NULL;

static {
try {
Read configuration file, load jdbc four parameters
Properties Config = new properties ();
Config.load (New FileReader (DBUtil.class.getClassLoader () getresource ("jdbc.conf"). GetPath ());
Drivatename = Config.getproperty ("drivername");
url = config.getproperty ("url");
Username = Config.getproperty ("username");
Password = config.getproperty ("password");

System.out.println (Drivatename);

Load Driver class
Class.forName (Drivatename);
} catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
} catch (ClassNotFoundException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}

Establish a connection
public static Connection Getconn () {
Connection conn = null;

try {
conn = drivermanager.getconnection (URL, username, password);
} catch (SQLException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}

Return conn;
}

Close connection
public static void Closeconn (Connection conn) {
try {
Conn.close ();
} catch (SQLException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}

Close PreparedStatement
public static void Closepstmt (PreparedStatement pstmt) {
try {
Pstmt.close ();
} catch (SQLException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}

Close result set resultset
public static void Closerst (ResultSet rst) {
try {
Rst.close ();
} catch (SQLException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}

Jdbc.config

Drivername=com.mysql.jdbc.driver
Url=jdbc:mysql://localhost:3306/mydbjdbc
Username= (user)
password= (password)

Userservlet.java

Package Com.hpe.servlet;import java.io.IOException;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Import Javax.servlet.http.httpsession;import Com.hpe.po.User;
Import Com.hpe.service.userservice;public class Userservlet extends HttpServlet {
Private static final long serialversionuid = 1L;
Private UserService service = new UserService (); Landing
protected void Login (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Get User name and password
String username = request.getparameter ("username");
String Password = request.getparameter ("password");

Call a method in UserService to verify
User user = Service.login (username, password);
if (user! = null) {//Login succeeded
To save user information in a domain object
HttpSession session = Request.getsession ();
Session.setattribute ("user", user);
Forward to Success page
Request.getrequestdispatcher ("/succ.jsp"). Forward (request, response);
} else {//Login failed
Put the error message, user name into the domain
String errormsg = "User name or password error";
Request.setattribute ("ErrorMsg", errormsg);
Request.setattribute ("username", username);
Forward to landing page
Request.getrequestdispatcher ("/login.jsp"). Forward (request, response);
}

}
Registered
protected void Register (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {String username = request.getparameter ("username");
String Password = request.getparameter ("password");

User user = new user (username, password);

Registered
int result = Service.register (user);
if (result = = 1) {//success
To save user information in a domain object
HttpSession session = Request.getsession ();
Session.setattribute ("user", user);
Forward to Success page
Request.getrequestdispatcher ("/succ.jsp"). Forward (request, response);
} else {//failed
String errormsg = null;
ErrorMsg = "Registration Failed";
if (result = =-1) {//
ErrorMsg = "The user already exists";
}
Request.setattribute ("ErrorMsg", errormsg);
Fail forward to registration page
Request.getrequestdispatcher ("/register.jsp"). Forward (request, response);
}
}

protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
Gets the method parameter, which is called according to the parameter selection
String method = Request.getparameter ("method");
if (method.equals ("login")) {//Login
Login (request, response);
} else if (Method.equals ("register")) {//Register
Register (request, response);
}
}

protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
Doget (request, response);
}}

Userservice.class

Package Com.hpe.service;import Com.hpe.dao.UserDao;
Import Com.hpe.po.user;public class UserService {
Private Userdao DAO = new Userdao ();

Public User Login (String username,string password) {
Return Dao.finduser (username, password);
}

public int register (user user) {
User u =dao.findbyname (User.getusername ());
if (u!=null) {
return-1;
}
int result =dao.adduser (user);
return result;
}
} userdao.classpackage Com.hpe.dao;import java.sql.Connection;
Import Java.sql.ResultSet;
Import Java.sql.sqlexception;import Com.hpe.po.User;
Import Com.hpe.util.DBUtil;
Import java.sql.PreparedStatement; public class Userdao {//Login
Public User finduser (String username,string password)
{
String sql= "SELECT * from user where username=? and password=? ";
Connection conn = Dbutil.getconn ();

PreparedStatement pstmt = null;
ResultSet rSet = null;
User user = null;
try {
Create PreparedStatement
pstmt = conn.preparestatement (sql);
Setting parameters
Pstmt.setstring (1, username);
Pstmt.setstring (2, password);

RSet = Pstmt.executequery ();

if (Rset.next ()) {
String name = rset.getstring (1);
String pwd = rset.getstring (2);
user = new User (name, pwd);
}
} catch (SQLException e) {
TODO auto-generated Catch block
E.printstacktrace ();
} finally {
Close the resource before you turn it off
if (RSet! = null) {
Dbutil.closerst (RSet);
}
if (pstmt! = null) {
Dbutil.closepstmt (PSTMT);
}
IF (conn! = null) {
DBUTIL.CLOSECONN (conn);
}
}
return user;
}

Public User Findbyname (String username) {
String sql = "SELECT * from user where username=?";
Create a connection
Connection conn = Dbutil.getconn (); PreparedStatement pstmt = null;
ResultSet rSet = null;
User user = null;
try {
Create PreparedStatement
pstmt = conn.preparestatement (sql);
Setting parameters
Pstmt.setstring (1, username);
Run the SQL statement
/*
* Delete and change executeupdate () query ExecuteQuery ()
*/
RSet = Pstmt.executequery ();
Processing results
if (Rset.next ()) {
String name = rset.getstring (1);
String pwd = rset.getstring (2);
user = new User (name, pwd);
}
} catch (SQLException e) {
TODO auto-generated Catch block
E.printstacktrace ();
} finally {
Close the resource before you turn it off
if (RSet! = null) {
Dbutil.closerst (RSet);
}
if (pstmt! = null) {
Dbutil.closepstmt (PSTMT);
}
IF (conn! = null) {
DBUTIL.CLOSECONN (conn);
}
}

return user;
}

public int addUser (user user) {
SQL statements
String sql = "INSERT into user values (?,?)";
Create a connection
Connection conn = Dbutil.getconn (); PreparedStatement pstmt = null;
int result = 0;

try {
Create PreparedStatement
pstmt = conn.preparestatement (sql);
Setting parameters
Pstmt.setstring (1, User.getusername ());
Pstmt.setstring (2, User.getpassword ());
Run the SQL statement
/*
* Delete and change executeupdate () query ExecuteQuery ()
*/
result = Pstmt.executeupdate ();
} catch (SQLException e) {
TODO auto-generated Catch block
E.printstacktrace ();
} finally {
Close the resource before you turn it off
if (pstmt! = null) {
Dbutil.closepstmt (PSTMT);
}
IF (conn! = null) {
DBUTIL.CLOSECONN (conn);
}
}
return result;
}
} Package Com.hpe.po;public class User {
Private String username;
private String password;

Public User () {

}
Public User (string Username, string password) {
Super ();
This.username = Username;
This.password = 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;
}
@Override
Public String toString () {
Return "User [username=" + Username + ", password=" + password + "]";
}

I am a rookie, if there is improper or wrong, please correct me

Javaweb's Servlet Login demo

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.