---------------siwuxie095

JSP+Servlet+JDBC

继续完善登录实例,将校验逻辑改为:从数据库中获取用户信息进行校验

数据库准备

在 Navicat for MySQL 中创建连接:user_conn,创建数据库:user_db,

创建表:user,并内置数据:

JDBC 驱动准备

下载 MySQL 的 JDBC 驱动,下载链接:

https://dev.mysql.com/downloads/connector/j/

mysql-connector-java-5.1.41.zip 解压后一览:

将 mysql-connector-java-5.1.41-bin.jar 放入 WEB-INF 的 lib 文件夹中,

选中该 jar 文件并执行操作:右键->Build Path->Add to Build Path

编写代码

点击选择 src,右键->New->File,创建文件:dbconfig.properties

此时,工程结构目录一览:

后端代码:

ConnectionFactory.java:

package com.siwuxie095.util;

import java.io.InputStream;

import java.sql.Connection;

import java.sql.DriverManager;

import java.util.Properties;

//数据库连接工厂类

public class ConnectionFactory {

//四个成员变量用于保存从属性文件中读取到的数据库配置信息

private static String driver;

private static String dburl;

private static String user;

private static String password;

//定义ConnectionFactory类型的成员变量

private static final ConnectionFactory factory=new ConnectionFactory();

//定义Connection类型的成员变量,用于保存数据库连接

private Connection conn;

/**

* 用 static 声明一个静态代码块

* 静态代码块用于初始化类,可以为类的属性赋值

*

* 当JVM加载类时,会执行其中的静态代码块

*

* 因为是在加载类的过程中执行的,所以静态代码块只会执行一次

*

* 这里是从属性文件中读取相关的配置信息

*/

static{

/**

* 创建一个 Properties 对象,Properties 在 java.util 包中,

* 继承自 Hashtable 类,可以用来保存属性文件中的键值对,

* Properties 的方法专门用于处理属性文件中的键值对

*/

Properties prop=new Properties();

try {

/**

* 获取属性文件中的内容:

* 首先获取当前类的类加载器,使用类加载器的getResourceAsStream()方法,

* 读取属性文件中内容,并读取到一个输入流中

*/

InputStream in=ConnectionFactory.class.getClassLoader()

.getResourceAsStream("dbconfig.properties");

//从输入流中读取属性列表,即键值对

prop.load(in);

} catch (Exception e) {

System.out.println("========配置文件读取错误========");

}

//将读取到的值赋值给成员变量

driver=prop.getProperty("driver");

dburl=prop.getProperty("dburl");

user=prop.getProperty("user");

password=prop.getProperty("password");

//属性文件的加载---编写完成

}

//定义一个默认构造方法(空的构造方法)

//构造方法私有化是单例化一个类的第一步

private ConnectionFactory(){

}

//定义getInstance()方法,用来获取一个ConnectionFactory的实例

//单例模式,保证在程序运行期间,只有一个ConnectionFactory实例存在

public static ConnectionFactory getInstance() {

return factory;

}

//创建一个获取数据库连接的方法 makeConnection()

public Connection makeConnection() {

try {

Class.forName(driver);

conn=DriverManager.getConnection(dburl,user,password);

} catch (Exception e) {

e.printStackTrace();

}

return conn;

}

}

UserEntity.java:

package com.siwuxie095.entity;

public abstract class UserEntity {

protected String userName;

public String getUserName() {

return userName;

}

public void setUserName(String userName) {

this.userName = userName;

}

}

UserEntityExtd.java:

package com.siwuxie095.entity.extd;

import com.siwuxie095.entity.UserEntity;

public class UserEntityExtd extends UserEntity {

private String password;

public String getPassword() {

return password;

}

public void setPassword(String password) {

this.password = password;

}

@Override

public String toString() {

return "UserEntityExtd [password=" + password + ", userName=" + userName + "]";

}

}

UserDao.java:

package com.siwuxie095.dao;

import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.SQLException;

import com.siwuxie095.entity.extd.UserEntityExtd;

public interface UserDao {

public void save(Connection conn,UserEntityExtd user) throws SQLException;

public void update(Connection conn,UserEntityExtd user) throws SQLException;

public void delete(Connection conn,UserEntityExtd user) throws SQLException;

public ResultSet get(Connection conn,UserEntityExtd user) throws SQLException;

}

UserDaoImpl.java:

package com.siwuxie095.dao.impl;

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import com.siwuxie095.dao.UserDao;

import com.siwuxie095.entity.extd.UserEntityExtd;

public class UserDaoImpl implements UserDao {

@Override

public void save(Connection conn, UserEntityExtd user) throws SQLException {

PreparedStatement ps=conn

.prepareStatement("insert into user(uname,upwd) values(?,?)");

ps.setString(1, user.getUserName());

ps.setString(2, user.getPassword());

ps.execute();

}

@Override

public void update(Connection conn, UserEntityExtd user) throws SQLException {

String updateSql="update user set uname=?,upwd=? where uname=?";

PreparedStatement ps=conn.prepareStatement(updateSql);

ps.setString(1, user.getUserName());

ps.setString(2, user.getPassword());

ps.execute();

}

@Override

public void delete(Connection conn, UserEntityExtd user) throws SQLException {

PreparedStatement ps=conn.prepareStatement("delete from user where uname=?");

ps.setString(1, user.getUserName());

ps.execute();

}

@Override

public ResultSet get(Connection conn, UserEntityExtd user) throws SQLException {

PreparedStatement ps=conn

.prepareStatement("select * from user where uname=? and upwd=?");

ps.setString(1, user.getUserName());

ps.setString(2, user.getPassword());

return ps.executeQuery();

}

}

CheckLoginService.java:

package com.siwuxie095.service;

import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.SQLException;

import com.siwuxie095.dao.UserDao;

import com.siwuxie095.dao.impl.UserDaoImpl;

import com.siwuxie095.entity.extd.UserEntityExtd;

import com.siwuxie095.util.ConnectionFactory;

public class CheckLoginService {

private UserDao userDao=new UserDaoImpl();

public boolean check(UserEntityExtd user){

Connection conn=null;

try {

conn=ConnectionFactory.getInstance().makeConnection();

conn.setAutoCommit(false);

ResultSet rs=userDao.get(conn, user);

while (rs.next()) {

return true;

}

} catch (SQLException e) {

e.printStackTrace();

try {

conn.rollback();

} catch (SQLException e1) {

e1.printStackTrace();

}

}finally {

try {

conn.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

return false;

}

}

CheckLoginServlet.java:

package com.siwuxie095.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import com.siwuxie095.entity.extd.UserEntityExtd;

import com.siwuxie095.service.CheckLoginService;

public class CheckLoginServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

private CheckLoginService cls=new CheckLoginService();

public CheckLoginServlet() {

super();

}

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

doPost(request, response);

}

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

String userName=request.getParameter("uname");

String password=request.getParameter("upwd");

RequestDispatcher rd=null;

String forward=null;

if (userName==null && password==null) {

request.setAttribute("msg", "用户名或密码为空!");

forward="/error.jsp";

}else {

UserEntityExtd user=new UserEntityExtd();

user.setUserName(userName);

user.setPassword(password);

boolean bool=cls.check(user);

if (bool) {

forward="/success.jsp";

}else {

request.setAttribute("msg", "用户名或密码错误,请重新输入!");

forward="/error.jsp";

}

}

rd=request.getRequestDispatcher(forward);

rd.forward(request, response);

}

}

前端代码:

login.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!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-8">

<title>登录页面</title>

<script type="text/javascript">

function check(form){

if(document.forms.loginForm.uname.value==""){

alert("请输入用户名!");

document.forms.loginForm.uname.focus();

return false;

}

if(document.forms.loginForm.upwd.value==""){

alert("请输入密码!");

document.forms.loginForm.upwd.focus();

return false;

}

}

</script>

<style type="text/css">

body {

color: #000; font-size =14px;

margin: 20px, auto;

}

</style>

</head>

<body>

<!-- 添加表单,url在部署描述符中进行配置,使用post方式来提交 -->

<form action="<%= request.getContextPath() %>/checkLoginServlet" method="post" name="loginForm">

<table border="1" cellspacing="0" cellpadding="5" bordercolor="silver" align="center">

<tr>

<td colspan="2" align="center" bgcolor="#E8E8E8">用户登录</td>

</tr>

<tr>

<td>用户名:</td>

<td><input type="text" name="uname" /></td>

</tr>

<tr>

<td>密码:</td>

<td><input type="password" name="upwd" /></td>

</tr>

<tr>

<td colspan="2" align="center">

<input type="submit" name="submit" onclick="return check(this);" />

<input type="reset" name="reset" />

</td>

</tr>

</table>

</form>

</body>

</html>

success.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!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-8">

<title>登录成功提示页面</title>

<style type="text/css">

body {

color: #000; font-size =14px;

margin: 20px, auto;

}

#message {

text-align: center;

}

</style>

</head>

<body>

<div id="message">

登录成功!<br/>

您提交的信息为:<br/>

用户名:<%= request.getParameter("uname") %><br/>

密码:<%= request.getParameter("upwd") %><br/>

<a href="<%= request.getContextPath() %>/login.jsp">返回登录页面</a>

</div>

</body>

</html>

error.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"

pageEncoding="UTF-8"%>

<!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-8">

<title>登录失败提示页面</title>

<style type="text/css">

body {

color: #000; font-size =14px;

margin: 20px, auto;

}

#message {

text-align: center;

}

</style>

</head>

<body>

<div id="message">

登录失败!<br/>

错误提示:

<%

Object obj=request.getAttribute("msg");

if(obj!=null){

out.print(obj.toString());

}else{

out.print("无");

}

%><br/>

您提交的信息为:<br/>

用户名:<%= request.getParameter("uname") %><br/>

密码:<%= request.getParameter("upwd") %><br/>

<a href="<%= request.getContextPath() %>/login.jsp">返回登录页面</a>

</div>

</body>

</html>

在部署描述符 web.xml 中注册 servlet:

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">

<display-name>MyServlet</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>

<servlet-name>CheckLoginServlet</servlet-name>

<servlet-class>com.siwuxie095.servlet.CheckLoginServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>CheckLoginServlet</servlet-name>

<url-pattern>/checkLoginServlet</url-pattern>

</servlet-mapping>

</web-app>

部署描述符 web.xml 在 WEB-INF 目录下,如果没有,手动创建即可

选择工程 MyServlet,右键->Java EE Tools->Generate Deployment Descriptor Stub

访问:localhost:8080/MyServlet/login.jsp,分别输入 siwuxie095 和 8888

跳转到:localhost:8080/MyServlet/checkLoginServlet

注意:高版本的 JDBC 驱动需要指明是否进行 SSL 连接

即 加上:?characterEncoding=utf8&useSSL=false

或:

即 加上:?useUnicode=true&characterEncoding=utf-8&useSSL=false

【made by siwuxie095】

Servlet编程实例 续4的更多相关文章

  1. Servlet编程实例 续2

    -----------------siwuxie095 Servlet 跳转之请求的重定向 继续完善登录实例,如下: login.jsp 不变,修改 LoginServlet,新建两个 JSP 文件 ...

  2. Servlet编程实例 续3

    ----------------siwuxie095 Servlet 跳转之请求的转发 修改 LoginServlet.java: package com.siwuxie095.servlet; im ...

  3. Servlet编程实例 续1

    -----------------siwuxie095                                 在 LoginServlet 中,右键->Open Type Hierar ...

  4. Servlet编程实例1

    编程目的:使用JSP+servlet,来实现一个登陆页面,登陆成功则提示成功,登陆失败则提示失败. 编程要求:登陆页面由login.jsp负责显示,登陆成功由success.jsp负责显示,登陆失败由 ...

  5. Servlet编程实例

    ---------------siwuxie095 登录实例: 从 login.jsp 提交登录信息到 LoginServlet,在 LoginServlet 中打印登录信息 工程结构目录如下: Lo ...

  6. Servlet编程实例2

    上次实验中利用HttpServletRespon.sendRedict()方法来实现页面的转跳,而这种重定向请求的方法无法传递缓存的内容. 所以为了做出改进,这次使用RequestDispatcher ...

  7. Servlet编程实例-servlet学习之旅(三)

    LoginServlet代码: public class LoginServlet extends HttpServlet{ @Override protected void service(Http ...

  8. Servlet编程

    Servlet编程 1. servlet概念及相关接口简介 java Servlet是运行在web服务器或应用服务器上的程序,他是作为来自web浏览器或其他HTTP客户端的请求和HTTP服务器山的数据 ...

  9. Servlet编程-步步为营

    [环境]eclipse j2ee;Tomcat 7.0; [模型1] package com.zhiqi; import ...; public class TestServlet extends H ...

随机推荐

  1. simple -- abstract

    <?php abstract class Operation { protected $_NumberA = 0; protected $_NumberB = 0; protected $_Re ...

  2. CodeForces - 580C Kefa and Park 【BFS】

    题目链接 http://codeforces.com/problemset/problem/580/C 题意 根节点是 1 然后所有的叶子结点都是饭店 从根节点到叶子结点的路径上 如果存在 大于m 个 ...

  3. 在数据库中使用数字ID作为主键的表生成主键方法

    在数据库开发中,很多时候建一个表的时候会使用一个数字类型来作为主键,使用自增长类型自然会更方便,只是本人从来不喜欢有内容不在自己掌控之中,况且自增长类型在进行数据库复制时会比较麻烦.所以本人一直使用自 ...

  4. Docker 搭建本地Registry

    Docker已经将Registry开源,Registry本身也是一个容器. 1. 修改配置/etc/docker/daemon.json,去掉docker默认的https的访问   里面的内容是一个j ...

  5. C# 中获取CPU序列号/网卡mac地址

    1.cpu序列号2.mac序列号3.硬盘id在给软件加序列号时这三个应该是最有用的,可以实现序列号和机器绑定,对保护软件很有好处.哈哈.   using System; using System.Ma ...

  6. Linux离线同步时间

    Linux离线同步时间 思路:以其中一台时间为准 脚本 #!/bin/shcurrent=`date '+%H:%M:%S'` for i in bigdata1 bigdata2 bigdata3 ...

  7. Linux下c++11多线程聊天室

    刚看的c++11多线程,写个聊天室试试编译的时候加上 c++11 和 多线程库g++ -Wall -std=c++0x -pthread -o server server.cppserver 和cli ...

  8. python基础-循环语句while

    循环语句:while\for\嵌套 循环控制语句:break\continue break:跳出整个循环,不会再继续循环下去 continue:跳出本次循环,继续下一次循环 while循环: coun ...

  9. 9th

    2017-2018-2 20179212<网络攻防实践>第9周作业 视频学习 KaliSecurity压力测试工具 压力测试通过确定一个系统的瓶颈或者不能接受的性能点,来获得系统能够提供的 ...

  10. java枚举学习enum

    java 1.5以后才出现enum的关键字 所有的enum类都继承自Enum类,所以enum类无法再继承其他的类,可以实现接口,枚举类出了不能被继承其余的与普通类的特性一致, 枚举类的构造函数只能自己 ...