1、前提:在Mysql数据库下建立数据库web13,在web13下创建一张表user,插入几条数据如下:

2、创建HTML文件,命名为login,作为登录界面(以post方式提交)

 <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/WEB13_sevrlet/login" method="post">
用户名:<input type="text" name="username"><br/>
密码:<input type="password" name="password"><br/>
<input type="submit" value="登录"><br/>
</form>
</body>
</html>

3、创建连接池

c3p0-config.xml文件如下:

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

DataSourceUtils.java文件如下:(可作为套用模板)

 package com.itheima.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>(); // 直接可以获取一个连接池
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();
}
}
}

4、编写Servlet实现类

User类代码如下:

 package com.itheima.domain;

 public class User {
private int id;
private String name;
private String password; public User(){ } public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
}
}

LoginServlet.java代码如下:

 package com.itheima.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 com.itheima.domain.User;
import com.itheima.utils.DataSourceUtils; public class LoginServlet extends HttpServlet { @Override
public void init() throws ServletException{
//在Servletcontext域中存一个数据count
int count=0;
this.getServletContext().setAttribute("count", count);
} public 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 user where username=? and password=?";
User user=null;
try {
user=runner.query(sql, new BeanHandler<User>(User.class),username,password);
} catch (SQLException e) {
e.printStackTrace();
}
//3.根据返回的结果给用户不同显示信息
if(user!=null){
//从Servletcontext中取出count进行++运算
ServletContext context=this.getServletContext();
Integer count=(Integer)context.getAttribute("count");
count++;
//用户登录成功
response.getWriter().write(user.toString()+"--you are success login person"+count);
context.setAttribute("count", count);
}else{
//用户登录失败
response.getWriter().write("Sorry,your username or password is wrong!");
}
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

5、编写Servlet配置文件,代码如下:

 <?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>WEB13_sevrlet</display-name>
<context-param>
<param-name>driver</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</context-param> <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>com.itheima.login.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping> <servlet>
<description></description>
<display-name>ContextServlet</display-name>
<servlet-name>ContextServlet</servlet-name>
<servlet-class>com.itheima.context.ContextServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ContextServlet</servlet-name>
<url-pattern>/context</url-pattern>
</servlet-mapping> </web-app>

6、测试,访问“http://localhost:8080/WEB13_sevrlet/login.html”

分别输入“Tom”,“123”,登录结果如下:

分别输入“Lucy”,“1234”,登录结果如下:

分别输入“Jack”,“123”,登录结果如下:

Servlet学习(三)——实例:用户登录并记录登陆次数的更多相关文章

  1. 云服务器 ECS Linux 保存用户登录操作命令记录

    转载自 : https://help.aliyun.com/knowledge_detail/41210.html 云服务器 ECS Linux 如果要保存用户登录操作记录,则可以通过在 /etc/p ...

  2. 基于Servlet的MVC模式用户登录实例

    关于MVC模式的简单解释 M Model,模型层,例如登录实例中,用于处理登录操作的类: V View,视图层,用于展示以及与用户交互.使用html.js.css.jsp.jQuery等前端技术实现: ...

  3. Cookie的应用——Servlet实现三天免登录

    1.工程结构: 2.Servlet的运用: (1)登录界面: protected void doGet(HttpServletRequest request, HttpServletResponse ...

  4. mybatis 和servlet使用MVC实现用户登录,注册,退出

    普通实现: USerMapper.java: package com.bjsxt.mapper; import org.apache.ibatis.annotations.Param; import ...

  5. DBCP(MySql)+Servlet+BootStrap+Ajax实现用户登录与简单用户管理系统

    目  录   简介 本次项目通过Maven编写 本文最后会附上代码 界面截图 登录界面 注册界面 登录成功进入主页 增加用户操作 删除用户操作 修改用户操作 主要代码 Dao层代码 DBCP代码 Se ...

  6. Servlet课程0426(十二)Servlet MV模式下用户登录及查看用户表中所有用户

    Welcome.java //登录界面 package com.tsinghua; import javax.servlet.http.*; import java.io.*; import java ...

  7. linux学习(三)-----linux用户管理、实用指令

    用户管理 基本介绍 说明: 1.Linux 系统是一个多用户多任务的操作系统,任何一个要使用系统资源的用户,都必须首先向 系统管理员申请一个账号,然后以这个账号的身份进入系统. 2.Linux 的用户 ...

  8. Servlet学习三——传输文件

    最先在考虑传输文件时,想通过java写一个文件上传案例,传给Servlet,Servlet再保存至数据库中,但苦于一直没找到实例,听说Flex有实际的例子,就直接用Flex例子来测试了.本文的顺序为: ...

  9. XMPP学习——2、用户登录

    最近在学习XMPP的使用,打算完成一个完整较为完整地Demo示例,通过这个示例掌握xmpp的使用与开发.同时打算在这个示例中学习使用一下其他的开源类库,在此作为记录学习. 包括服务器端--Openfi ...

随机推荐

  1. php开启CURL支持

    window下安装php_curl支持 1. 找到php.ini 修改extension=php_curl.dll 把前面的分号去掉2. 把 php_curl.dll libeay32.dll ssl ...

  2. 敬请关注 Linr 公众号

  3. DB2导出表结构、表数据小结

    一.DB2命令行导出数据库全库表结构 ① Win+R进入到DB2安装目录的BIN目录下,执行命令:DB2CMD,进入到DB2 CLP窗口. 命令:DB2CMD ② 创建一个data文件夹 命令:MKD ...

  4. IE,表头固定

    <html>  <head>   <title>表头固定</title>    <style type="text/css"& ...

  5. git + grunt 环境配置

        1⃣️ssh key生成步骤 一.设置Git的user.name和user.email: $ git config --global user.name "xiongzuyan&qu ...

  6. 什么是2.5D与3D编辑模式

    ZBrush®其实就是一个带有三维特性的二维软件,它不仅具有绘制二维图像的功能,而且也具有对三维物体进行编辑的功能,就是所谓的2.5D(Pixol技术). 学习ZBrush之前有必要了解一下2.5D的 ...

  7. 百度图标echarts.js的使用

    echarts官网:http://echarts.baidu.com/api.html#echarts echarts是百度公司开的一种开源制作图片工具,是一个专门制作图表的开源工具,功能非常强大,地 ...

  8. 注解实战Beforeclass和Afterclass

    package com.course.testng;import org.testng.annotations.*; public class BasicAnnotation { //最基本的注解,用 ...

  9. 01 C#基础

    第一天 .net平台(中国移动互联网平台): .net框架(信号塔): CLR(公共语言运行时) .Net类 库 我们使用的语言是——C# 2.解决方案项目与类的关系: 解决方案:公司 项目:部门 类 ...

  10. Vue.mixin Vue.extend(Vue.component)的原理与区别

    1.本文将讲述 方法 Vue.extend Vue.mixin 与 new Vue({mixins:[], extend:{}})的区别与原理 先回顾一下 Vue.mixin 官网如下描述: Vue. ...