首页 > 代码库 > Servlet编程实例 续4

Servlet编程实例 续4

---------------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=http://www.mamicode.com/=""){

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

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

return false;

}

if(document.forms.loginForm.upwd.value=http://www.mamicode.com/=""){

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 目录下,如果没有,手动创建即可

   

选择工程 HelloServlet,右键->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