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. ML学习笔记- 神经网络

    神经网络 有的模型可以有多种算法.而有的算法可能可用于多种模型.在神经网络中,对外部环境提供的模式样本进行学习训练,并能存储这种模式,则称为感知器;对外部环境有适应能力,能自动提取外部环境变化特征,则 ...

  2. LVS(Linux Viretual Server) 负载均衡器 + 后端服务器

    ##定义: LVS是Linux Virtual Server的简写,意即Linux虚拟服务器,是一个虚拟的服务器集群系统. ##结构: 一般来说,LVS集群采用三层结构,其主要组成部分为: A.负载调 ...

  3. vue入门--初始化

    VUE初始化时,可以用vue init webpack-simple或者vue init webpack.前者是简易版的工程,后者是标准的初始化.工程创建成功后,打开发现两个的目录结构有很大不同.si ...

  4. Microsoft Edge 首个 Chromium 内核版释出

    翻译功能释出 navigator.userAgent"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, ...

  5. <Android Framework 之路>Android5.1 Camera Framework(一)

    Android5.0 Camera Framework 简介 CameraService启动 CameraService是在MediaServer启动过程中进行的 main_mediaserver.c ...

  6. DataBaseFactory基础了解

     <add name="Connection str" connectionString="data source=.;pwd=12;uid=sa;database ...

  7. POJ 3624 Charm Bracelet【01背包】

    解题思路:直接套公式就能做的01背包, for(i=1;i<=n;i++) { for(v=w[i];v<=m;v++) f[i,v]=max(f[i,v],f[i-1,v-w[i]]+d ...

  8. ZBrush软件中的笔触类型

    在ZBrush® 中我们通过各种笔触类型,确定在使用ZBrush®画笔进行绘制时画笔的变化方式及状态.使用多种画笔绘制根据选择不同的笔触组合绘制,能够得到繁多变化丰富的制作效果. 选择笔触的类型 点击 ...

  9. js正则表达式注册页面表单验证

    可以这样校验 <html> <head> <meta http-equiv="Content-Type" content="text/htm ...

  10. There are multiple modules with names that only differ in casing.

    client?4c0e:153 ./src/components/Paginate.vue There are multiple modules with names that only differ ...