JSP应用JavaBean实现增删改查用户信息功能

1.com.weihai.bean包
User.java

package com.weihai.bean;

import java.io.Serializable;

//表示数据的javabean
//成员变量私有
//提供公开的set和get方法

public class User implements Serializable{

	
	/**
	 * 成员变量根据表中的字段确定
	 */
	private static final long serialVersionUID = 1L;
	private int id;
	private String username;
	private String password;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
}

2.com.weihai.conn包
DBConn.java

package com.weihai.conn;

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mysql.jdbc.Connection;


public class DBConn {
	public static final String dbDriver = "com.mysql.jdbc.Driver";
	public static final String dbURL = "jdbc:mysql://localhost:3306/db_shop";
	public static final String dbUsername = "root";
	public static final String dbPwd = "root";
	
	//连接数据库
	public static Connection getConntion() {
		Connection conn = null;
		try {
			Class.forName(dbDriver);
			}catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
			//创建数据库的连接
			
			try {
				conn = (Connection) DriverManager.getConnection(dbURL,dbUsername,dbPwd);
			}catch (SQLException e) {
				e.printStackTrace();
			}
			return conn;
	}
	//关闭与数据库连接
	public static void close(Connection conn,PreparedStatement pt,ResultSet rs){
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (pt != null) {
			try {
				pt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	public static void close(Connection conn,PreparedStatement pt){
		if (pt != null) {
			try {
				pt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

3.com.weihai.dao包
UserDao.java接口

package com.weihai.dao;
import java.util.ArrayList;
import com.weihai.bean.User;

/**
 * 实现对表admin_info的增删改查
 * @author Administrator
 *
 */
public interface UserDao {
	boolean login(String username,String password);
	boolean insert(User user);
	ArrayList<User> queryAll();
	boolean delete(User user);
	boolean update(User user);

}

4.com.weihai.dao.impl包
UserDaoImpl.java

package com.weihai.dao.impl;

import java.math.MathContext;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import com.weihai.bean.User;
import com.weihai.conn.DBConn;
import com.weihai.dao.UserDao;

/**
 * 访问数据库的JavaBean
 * 实现某种功能,我们称为功能Bean
 * @author 1
 *
 */
public class UserDaoImpl implements UserDao{
	/**
	    * 实现登录验证 方法定义三要素:方法名、参数、返回值
	 * @param username
	 * @param password
	 * @return
	 */
	public com.mysql.jdbc.Connection conn = null;
	public PreparedStatement pt = null;
	public ResultSet rs = null;
	
	/**
	 * 用户名密码验证
	 * @param username
	 * @param password
	 * @return
	 */
	public boolean login(String username, String password) {
		// 2.访问数据库,查询用户名密码
		boolean t=false;
        System.out.print(username);
		conn =DBConn.getConntion();
		// 解决Sql注入的方法,利用PreparedStatement:预处理的语句容器
		// PreparedStatement允许在sql语句中使用占位符?
		// PreparedStatement的优点:
		// 1.解决SQL注入
		// 2.提高程序的可读性和可维护性
		// 3.执行效率高
		String sql = "select * from admin_info where name=? and pwd=?";  
		try {
			pt = conn.prepareStatement(sql);
			pt.setString(1, username);
			pt.setString(2, password);
			// 执行SQL语句
			rs = pt.executeQuery();
			if(rs.next()){
				t=true;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 执行SQL语句之前需要给参数赋值
		DBConn.close(conn,pt,rs);
		return t;
	}
	/**
	 * 查询数据库的所有记录
	 * @return
	 */
    public ArrayList<User> queryAll(){
    	//使用泛型,解决强转的问题
    	ArrayList<User> users = new ArrayList<User>();
		//2.访问数据库,查询用户名密码
		//(1)加载数据库驱动
    	conn =DBConn.getConntion();
		//(3)创建语句容器
		String  sql= "select * from admin_info";
		try {
			pt = conn.prepareStatement(sql);
			//(4)执行Sql语句
			 rs = pt.executeQuery();
			//遍历结果集,把结果集转存到users中
			 while(rs.next()){
					//一条记录对应一个User对象
					User user = new User();
					user.setId(rs.getInt("id"));
					user.setUsername(rs.getString("name"));
					user.setPassword(rs.getString("pwd"));
					//需要把每个user添加到Users中
					users.add(user);			
			}
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		//关闭数据库连接
		DBConn.close(conn,pt,rs);
		return users;
    }
    /**
     * 增加用户
     */
    public  boolean insert(User user){
    	boolean t=false;
    	conn =DBConn.getConntion();
		// 解决Sql注入的方法,利用PreparedStatement:预处理的语句容器
		// PreparedStatement允许在sql语句中使用占位符?
		// PreparedStatement的优点:
		// 1.解决SQL注入
		// 2.提高程序的可读性和可维护性
		// 3.执行效率高
		String sql = "insert into admin_info(name,pwd) values(?,?)";  
		try {
			pt = conn.prepareStatement(sql);
			pt.setString(1, user.getUsername());
			pt.setString(2, user.getPassword());
			// 执行SQL语句
			int i= pt.executeUpdate();
			if(i>0){
				t=true;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 执行SQL语句之前需要给参数赋值
		DBConn.close(conn,pt);
		return t;
    }
    /**
     * 删除用户
     */
    public boolean delete(User user) {
		// 2.访问数据库,查询用户名密码
		boolean t=false;
		conn =DBConn.getConntion();
		String sql = "delete from admin_info where name=? and pwd=?";  
		try {
			pt = conn.prepareStatement(sql);
			pt.setString(1, user.getUsername());
			pt.setString(2, user.getPassword());
			// 执行SQL语句
			int i= pt.executeUpdate();
			if(i>0){
				t=true;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 执行SQL语句之前需要给参数赋值
		DBConn.close(conn,pt,rs);
		return t;
	}
    /**
     * 修改用户
     */
    public boolean update(User user) {
		// 2.访问数据库,查询用户名密码
		boolean t=false;
		conn =DBConn.getConntion();
		
		String sql = "update admin_info set name=?, pwd=? where id= ?";  
		try {
			pt = conn.prepareStatement(sql);
			
			pt.setInt(1, user.getId());
			pt.setString(2, user.getUsername());
			pt.setString(3, user.getPassword());
			// 执行SQL语句
			int i= pt.executeUpdate();
			if(i>0){
				t=true;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 执行SQL语句之前需要给参数赋值
		DBConn.close(conn,pt,rs);
		return t;
	}
}

5.com.weihai.factory包
DaoFactory.java

package com.weihai.factory;

import com.weihai.dao.UserDao;
import com.weihai.dao.impl.UserDaoImpl;
/**
 * 工厂模式
 * 返回Dao对象
 * @author Administrator
 *
 */
public class DaoFactory {
	/**
	 * 返回UserDaoImpl的对象
	 * 父类可以指向子类的对象
	 * @return
	 */
	public static UserDao getUserDao() {
		return new UserDaoImpl();
	}

}

6.登录页面
login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String username = "";
String pwd = "";
//读取cookie
Cookie[] cookies = request.getCookies();
for(Cookie cookie:cookies){
	if("username".equals(cookie.getName())){
		username = cookie.getValue();
	}
	if("password".equals(cookie.getName())){
		pwd = cookie.getValue();
	}
}
%>
<form action="check.jsp" method="post">
用     户     名:<input type="text" name="username"/><br/>
用户密码 :<input type="text" name="password"/><br/>
<input type="submit" value="登录"/>
<input type="reset" value="取消"/><br/>
</form>
</body>
</html>

check.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%-- <%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.PreparedStatement"%> --%>
<%@page import="java.sql.*" %>
<%@page import="com.weihai.dao.*,com.weihai.dao.impl.*" %>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
	request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
String password = request.getParameter("password");

UserDaoImpl userDao = new UserDaoImpl();
boolean t = userDao.login(username,password);

if(t){//查询
//if("username".equals(name)&& "pwd".equals(psw)){
	
	Cookie cookie1 = new Cookie("username",username);
	Cookie cookie2 = new Cookie("password",password);
	
	//存储cookie需要设置存活时间 秒
	cookie1.setMaxAge(7*24*60*60);
	cookie2.setMaxAge(7*24*60*60);
	
	response.addCookie(cookie1);
	response.addCookie(cookie2);
	
	session.setAttribute("username", username);
	
	session.setAttribute("password", password);
	session.setMaxInactiveInterval(1);
	/* rs.close();
	userDao.pt.close();
	userDao.conn.close(); */
	
response.sendRedirect("success.jsp");
}
else{
response.sendRedirect("error.jsp");
}
%>
</body>
</html>

success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>成功页面</title>
</head>
<body>
<%@ include file="validate.jsp"%>
<%
//String name = request.getParameter("userName");
//String name = (String)session.getAttribute("username");
%>
用户:<%= name %><br>
登录成功<br/>
</body>
</html>

error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>错误页面</title>
</head>
<body>
<p>登录失败</p><br/>
<a href="login.jsp">重新登录</a>
</body>
</html>

validate.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String name = (String)session.getAttribute("username");
if(name==null||name.isEmpty()){
	response.sendRedirect("error_session.jsp");
}
%>
</body>
</html>

zhuce.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="doZhuce.jsp" method="post">
用     户     名:<input type="text" name="username"/><br/>
用户密码 :<input type="text" name="password"/><br/>
<input type="submit" value="注册"/>
<input type="reset" value="取消"/><br/>
</form>
</body>
</html>

doZhuce.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@page import="java.sql.*" %>
    <%@page import="com.weihai.bean.*,com.weihai.dao.*,com.weihai.dao.impl.*" %>
    <%@page import="java.util.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = new User();
user.setUsername(username);
user.setPassword(password);
%>
<%
	UserDaoImpl userDao = new UserDaoImpl();
boolean t = userDao.insert(user);
if(t){
	out.print("添加成功!");
}else{
	out.print("添加失败!");
}
%>
</body>
</html>

delete.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="doDelete.jsp" method="post">
用     户     名:<input type="text" name="username"/><br/>
用户密码 :<input type="text" name="password"/><br/>
<input type="submit" value="删除"/>
<input type="reset" value="取消"/><br/>
</form>
</body>
</html>

doDelete.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@page import="java.sql.*" %>
    <%@page import="com.weihai.bean.*,com.weihai.dao.*,com.weihai.dao.impl.*" %>
    <%@page import="java.util.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = new User();
user.setUsername(username);
user.setPassword(password);
%>
<%
	UserDaoImpl userDao = new UserDaoImpl();
boolean t = userDao.delete(user);
if(t){
	out.print("删除用户成功!");
}else{
	out.print("用户名或用户密码错误,删除用户失败!");
}
%>
</body>
</html>

update.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="doUpdate.jsp" method="post">
请输入要修改的用户的id:<input type="text" name="id"/><br/>
用     户     名:<input type="text" name="username"/><br/>
用户密码 :<input type="text" name="password"/><br/>
<input type="submit" value="修改"/>
<input type="reset" value="取消"/><br/>
</form>
</body>
</html>

doUpdate.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
        <%@page import="java.sql.*" %>
    <%@page import="com.weihai.bean.*,com.weihai.dao.*,com.weihai.dao.impl.*" %>
    <%@page import="java.util.*" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
int id = Integer.parseInt(request.getParameter("id"));
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = new User();
user.setId(id);
user.setUsername(username);
user.setPassword(password);
%>
<%
	UserDaoImpl userDao = new UserDaoImpl();
boolean t = userDao.insert(user);
if(t){
	out.print("修改成功!");
}else{
	out.print("id错误,修改失败!");
}
%>
</body>
</html>

query.jsp

<%@page import="com.weihai.factory.DaoFactory"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@page import="java.sql.*" %>
    <%@page import="com.weihai.bean.*,com.weihai.dao.*" %>
    <%@page import="java.util.*" %>
    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

<%
    //利用工厂创建的dao对象,隐藏实现类的细节
	UserDao userDao = DaoFactory.getUserDao();
    ArrayList<User> users = userDao.queryAll();

//遍历结果集
for(int i=0;i<users.size();i++){
	User user = users.get(i);
	out.print(user.getUsername()+"  ");
	out.print(user.getPassword());
	out.println("<br/>");
}
%>
</body>
</html>
上一篇:java创建和读取xml


下一篇:Mybatis--select标签传递多个参数(Map方式、JavaBean方式)