Servlet编程实例 续4

来源:互联网 发布:听书软件安卓 编辑:程序博客网 时间:2024/05/18 15:05

---------------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()方法,

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

*/

InputStreamin=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;

}

  

publicvoid setUserName(String userName) {

this.userName = userName;

}

 

}

  

  

  

UserEntityExtd.java:

  

package com.siwuxie095.entity.extd;

  

import com.siwuxie095.entity.UserEntity;

  

public class UserEntityExtdextends UserEntity {

private String password;

  

public String getPassword() {

return password;

}

  

publicvoid 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 {

publicvoid save(Connection conn,UserEntityExtd user) throws SQLException;

publicvoid update(Connection conn,UserEntityExtd user) throws SQLException;

publicvoid 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 UserDaoImplimplements UserDao {

  

@Override

publicvoid 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

publicvoid 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

publicvoid 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();

 

publicboolean 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 CheckLoginServletextends HttpServlet {

private static finallong serialVersionUID =1L;

 

private CheckLoginService cls=new CheckLoginService();

 

public CheckLoginServlet() {

super();

}

  

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

doPost(request, response);

}

  

protectedvoid 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>

<metahttp-equiv="Content-Type"content="text/html; charset=UTF-8">

<title>登录页面</title>

  

<scripttype="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方式来提交 -->

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

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

<tr>

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

</tr>

<tr>

<td>用户名:</td>

<td><inputtype="text"name="uname"/></td>

</tr>

<tr>

<td>密码:</td>

<td><inputtype="password"name="upwd"/></td>

</tr>

<tr>

<tdcolspan="2"align="center">

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

<inputtype="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>

<metahttp-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>

<divid="message">

登录成功!<br/>

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

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

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

<ahref="<%= 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>

<metahttp-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>

  

<divid="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/>

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

</div>

  

</body>

</html>

  

  

  

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

  

<?xmlversion="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/javaeehttp://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】

0 0
原创粉丝点击