User Login with servlet (vi)

Source: Internet
Author: User


We use the servlet to implement a user login function. first, the database





DROP TABLE IF EXISTS ' user ';
CREATE TABLE ' user ' (
  ' id ' int (one) not NULL,
  ' username ' varchar () DEFAULT NULL,
  ' password ' varchar () DEFA ULT null,
  ' email ' varchar (default NULL,
  PRIMARY KEY (' id ')
) engine=innodb default Charset=utf8;

------------------------------
-Records of user
------------------------------
INSERT into ' user ' VALUES (' 1 ', ' Tom ', ' 123 ', ' tom@163.com ');
INSERT into ' user ' VALUES (' 2 ', ' Lucy ', ' 123 ', ' lucy@163.com ');


second, the front page



login.jsp


<% @ page language = "java" contentType = "text / html; charset = UTF-16"
     pageEncoding = "UTF-16"%>
<! DOCTYPE html PUBLIC "-// W3C // DTD HTML 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv = "Content-Type" content = "text / html; charset = UTF-16">
<title> Insert title here </ title>
</ head>
<body>

<form action = "/ servlet_first / login" method = "post">
Username: <input type = "text" name = "username"> <br/>
Password: <input type = "password" name = "password"> <br/>
<input type = "submit" name = "login"> <br/>
</ form>

</ body>
</ html>


Third、Servlet

package com.ken.login;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.ken.domain.User;
import com.ken.utils.DataSourceUtils;

public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// 1. get username and password
String username = request.getParameter ("username");
String password = request.getParameter ("password");

// 2. Verify that the username and password are correct from the database
QueryRunner runner = new QueryRunner (DataSourceUtils.getDataSource ());

String sql = "select * from user where username =? And password =?";
User user = null;
try {
user = runner.query (sql, new BeanHandler <User> (User.class), username, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace ();
}

// 3. Different display information to the user according to the returned result
if (user! = null) {
// The user logs in successfully
response.getWriter (). write (user.toString ());
} else {
// user login failed
response.getWriter (). write ("sorry your username or password is wrong");
}
}

protected void doPost (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet (request, response);
}
}



Fourth, connect to the database
  4.1 Tool class DataSourceUtils
package com.ken.utils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DataSourceUtils {

private static DataSource dataSource = new ComboPooledDataSource ();

private static ThreadLocal <Connection> tl = new ThreadLocal <Connection> ();

// You can directly get a connection pool
public static DataSource getDataSource () {
return dataSource;
}

// Get the connection object
public static Connection getConnection () throws SQLException {

Connection con = tl.get ();
if (con == null) {
con = dataSource.getConnection ();
tl.set (con);
}
return con;
}

// start transaction
public static void startTransaction () throws SQLException {
Connection con = getConnection ();
if (con! = null) {
con.setAutoCommit (false);
}
}

// transaction is rolled back
public static void rollback () throws SQLException {
Connection con = getConnection ();
if (con! = null) {
con.rollback ();
}
}

// Commit and close resources and release from ThreadLocall
public static void commitAndRelease () throws SQLException {
Connection con = getConnection ();
if (con! = null) {
con.commit (); // transaction commit
con.close (); // Close the resource
tl.remove (); // Remove from thread binding
}
}

// Close the resource method
public static void closeConnection () throws SQLException {
Connection con = getConnection ();
if (con! = null) {
con.close ();
}
}

public static void closeStatement (Statement st) throws SQLException {
if (st! = null) {
st.close ();
}
}

public static void closeResultSet (ResultSet rs) throws SQLException {
if (rs! = null) {
rs.close ();
}
}

}


4.2 c3p0-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
	<default-config>
		<property name="user">root</property>
		<property name="password">123456</property>
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<property name="jdbcUrl">jdbc:mysql:///servlet_first</property>
	</default-config> 
</c3p0-config> 

Fifth、web.xml

<?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_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>servlet_first</display-name>
	<servlet>
		<servlet-name>abc</servlet-name>
		<servlet-class>com.ken.servlet.QuickStartServlet</servlet-class>
		<init-param>
			<param-name>url</param-name>
			<param-value>jdbc:mysql:///mydb</param-value>
		</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>abc</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	<servlet>
		<servlet-name>QuickStartServlet2</servlet-name>
		<servlet-class>com.ken.servlet.QuickStartServlet2</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>QuickStartServlet2</servlet-name>
		<url-pattern>/quickStartServlet2</url-pattern>
	</servlet-mapping>
	<servlet>
		<description></description>
		<display-name>LoginServlet</display-name>
		<servlet-name>LoginServlet</servlet-name>
		<servlet-class>com.ken.login.LoginServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>LoginServlet</servlet-name>
		<url-pattern>/login</url-pattern>
	</servlet-mapping>
</web-app>








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.