Servlet Case 1: User Logon, servlet case
Database preparation:
CREATE DATABASE web;USE web;CREATE TABLE users( id INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(64), PASSWORD VARCHAR(64), email VARCHAR(64) );INSERT INTO users (username,PASSWORD,email) VALUES("tom","123","tom@qq.com"),("lucy","123","lucy@qq.com");
View Code
Corresponding User class:
package domain;public class User { private int id; private String username; private String password; private String email; @Override public String toString() { return "User [id=" + id + ", username=" + username + ", password=" + password + ", email=" + email + "]"; } public int getId() { return id; } public void setId(int id) { this.id = id; } 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; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; }}
View Code
Front-end page:
Login.html:
<! DOCTYPE html> View Code
Servlet:
Use the c3p0 connection pool, dbutils tool class, and mysql driver. Import related packages.
Utils package:
Custom connection pool tool class:
Package 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 performanceutils {private static DataSource dataSource = new ComboPooledDataSource (); private static ThreadLocal <Connection> tl = new ThreadLocal <Connection> (); // you can directly obtain a connection pool public static DataSource getDataSource () {return dataSource;} // gets the Connection object public static Connection getConnection () throws SQLException {Connection con = tl. get (); if (con = null) {con = dataSource. getConnection (); tl. set (con) ;}return con ;}// enable the public static void startTransaction () throws SQLException {Connection con = getConnection (); if (con! = Null) {con. setAutoCommit (false) ;}// transaction rollback public static void rollback () throws SQLException {Connection con = getConnection (); if (con! = Null) {con. rollback () ;}/// submit and close resources and release 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 ();}}}
View Code
C3p0-config.xml configuration file:
<?xml version="1.0" encoding="UTF-8"?><c3p0-config> <default-config> <property name="user">root</property> <property name="password">xuyiqing</property> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql:///web</property> </default-config> </c3p0-config>
View Code
Core category:
Package 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 domain. user; import utils. dataSourceUtils; public class Lo GinServlet extends HttpServlet {protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// 1. obtain username and password String username = request. getParameter ("username"); String password = request. getParameter ("password"); // 2. queryRunner runner = new QueryRunner (performanceutils. getDataSource (); String SQL = "select * from users where username =? And password =? "; User user = null; try {user = runner. query (SQL, new BeanHandler <User> (User. class), username, password);} catch (SQLException e) {e. printStackTrace ();} if (user! = Null) {// logon successful response. getWriter (). write (user. toString ();} else {// logon Failure response. getWriter (). write ("Sorry! Your username or password is wrong. ") ;}} protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response );}}
View Code
Web. xml configuration:
<?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>WEB2</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> <servlet> <description></description> <display-name>LoginServlet</display-name> <servlet-name>LoginServlet</servlet-name> <servlet-class>login.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping></web-app>
View Code
Done!
Access http: // localhost: 8080/WEB2/login.html
Enter the correct username and password and click to log on.
The result is as follows:
Done!
Successful!
Next, we will improve our functions:
Count successful logon users:
Package login; import java. io. IOException; import java. SQL. SQLException; import javax. servlet. servletContext; 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 domain. user; import u Tils. dataSourceUtils; public class LoginServlet extends HttpServlet {@ Override public void init () throws ServletException {int count = 0; // domain object this. getServletContext (). setAttribute ("count", count);} protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// 1. obtain username and password String username = request. getParameter ("username"); String passwor D = request. getParameter ("password"); // 2. queryRunner runner = new QueryRunner (performanceutils. getDataSource (); String SQL = "select * from users where username =? And password =? "; User user = null; try {user = runner. query (SQL, new BeanHandler <User> (User. class), username, password);} catch (SQLException e) {e. printStackTrace ();} if (user! = Null) {// Login Succeeded // use the domain object method ServletContext context = this. getServletContext (); Integer count = (Integer) context. getAttribute ("count"); count ++; response. getWriter (). write (user. toString () + "You are the" + count + "person to log in successfully"); context. setAttribute ("count", count);} else {// logon Failure response. getWriter (). write ("Sorry! Your username or password is wrong. ") ;}} protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response );}}
View Code