博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Servlet案例1:用户登录
阅读量:5119 次
发布时间:2019-06-13

本文共 7645 字,大约阅读时间需要 25 分钟。

数据库准备:

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

 

对应User类:

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

 

前端页面:

login.html:

Insert title here
用户名:
密码:
View Code

 

Servlet:

用到c3p0连接池,dbutils工具类,mysql驱动,注意导入相关包

utils包:

自定义连接池工具类:

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 DataSourceUtils {    private static DataSource dataSource = new ComboPooledDataSource();    private static ThreadLocal
tl = new ThreadLocal
(); // 直接可以获取一个连接池 public static DataSource getDataSource() { return dataSource; } // 获取连接对象 public static Connection getConnection() throws SQLException { Connection con = tl.get(); if (con == null) { con = dataSource.getConnection(); tl.set(con); } return con; } // 开启事务 public static void startTransaction() throws SQLException { Connection con = getConnection(); if (con != null) { con.setAutoCommit(false); } } // 事务回滚 public static void rollback() throws SQLException { Connection con = getConnection(); if (con != null) { con.rollback(); } } // 提交并且 关闭资源及从ThreadLocall中释放 public static void commitAndRelease() throws SQLException { Connection con = getConnection(); if (con != null) { con.commit(); // 事务提交 con.close();// 关闭资源 tl.remove();// 从线程绑定中移除 } } // 关闭资源方法 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配置文件:

root
xuyiqing
com.mysql.jdbc.Driver
jdbc:mysql:///web
View Code

 

核心类:

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 LoginServlet extends HttpServlet {    protected void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        //1.获取用户名密码        String username = request.getParameter("username");        String password = request.getParameter("password");        //2.数据库中验证        QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());        String sql = "select * from users where username=? and password=?";        User user = null;        try {            user = runner.query(sql,new BeanHandler
(User.class) ,username,password); } catch (SQLException e) { e.printStackTrace(); } if(user!=null){ //登录成功 response.getWriter().write(user.toString()); }else { //登录失败 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配置:

WEB2
index.html
index.htm
index.jsp
default.html
default.htm
default.jsp
LoginServlet
LoginServlet
login.LoginServlet
LoginServlet
/login
View Code

 

完成!

访问http://localhost:8080/WEB2/login.html

 

输入正确的用户名和密码点击登录

 

结果如下:

 

完成!

成功!

 

 

接下来,提升功能:

统计成功登录的人数:

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 utils.DataSourceUtils;public class LoginServlet extends HttpServlet {    @Override    public void init() throws ServletException {        int count = 0;        // 域对象        this.getServletContext().setAttribute("count", count);    }    protected void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        // 1.获取用户名密码        String username = request.getParameter("username");        String password = request.getParameter("password");        // 2.数据库中验证        QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());        String sql = "select * from users where username=? and password=?";        User user = null;        try {            user = runner.query(sql, new BeanHandler
(User.class), username, password); } catch (SQLException e) { e.printStackTrace(); } if (user != null) { // 登录成功 // 利用域对象的方法 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 { // 登录失败 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

 

转载于:https://www.cnblogs.com/xuyiqing/p/8407226.html

你可能感兴趣的文章
jQuery Mobile笔记
查看>>
8、RDD持久化
查看>>
第二次团队冲刺--2
查看>>
VMware Tools安装
查看>>
Linux上架设boost的安装及配置过程
查看>>
[转载]加密算法库Crypto——nodejs中间件系列
查看>>
zoj 2286 Sum of Divisors
查看>>
OO5~7次作业总结
查看>>
如何判断主机是大端还是小端(字节序)
查看>>
Centos7 日志查看工具
查看>>
使用Xshell密钥认证机制远程登录Linux
查看>>
OpenCV之响应鼠标(三):响应鼠标信息
查看>>
Android 画图之 Matrix(一)
查看>>
List<T>列表通用过滤模块设计
查看>>
【模板】最小生成树
查看>>
设计模式之结构型模式
查看>>
poj2569
查看>>
使用pygal_maps_world.i18n中数据画各大洲地图
查看>>
sql server必知多种日期函数时间格式转换
查看>>
jQuery EasyUI 的下拉选择combobox后台动态赋值
查看>>