使用javaweb进行用户管理系统的增删改查,分页和条件查询
程序员文章站
2022-05-02 12:27:18
...
使用javaweb进行用户管理系统的增删改查,分页和条件查询
主要实现增删改查,分为customer表和user表,customer表主要是客户实现增删改查,分页,和条件查询,user表主要是实现用户的登陆和注册功能
dao层的接口:
(customerDao)dao层接口的代码:
package cn.cyp.dao;
import cn.cyp.bean.Customer;
import cn.cyp.bean.pageBean;
import java.util.List;
import java.util.Map;
/**
* @Author:cyp
* @date:2019/8/14 19:54
* @Desc:
*/
public interface customerDao {
//查询所有用户
List<Customer> selectAllCustomer();
//进行添加判断邮箱
Customer ckEmailName(String email);
//增加用户
Boolean addCustomer(Customer customer);
// 删除用户
void deleteCustomer(int id);
//修改
//修改数据
Customer updateCustomer(int id);
//编辑数据
Boolean editeCustomer(Customer customer);
//显示查询的总共有多少条
int findTotalCounts(Map<String, String[]> map);
//查询每页显示的数据是什么
List<Customer> findTotalCustomers(pageBean pageBean, Map<String, String[]> map);
}
(userDao)dao层接口:
package cn.cyp.dao;
import cn.cyp.bean.User;
/**
* @Author:cyp
* @date:2019/8/16 8:20
* @Desc:
*/
public interface userDao {
User userLogin(User user);
Boolean registerUser(User user);
User registerOk(String username);
}
dao层接口的实现:
(customerDaoImpl)dao层接口实现的代码:
package cn.cyp.dao.impl;
import cn.cyp.bean.Customer;
import cn.cyp.bean.pageBean;
import cn.cyp.dao.customerDao;
import cn.cyp.util.jdbcUtil;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @Author:cyp
* @date:2019/8/14 19:55
* @Desc:dao层,发送sql语句到db中
*/
public class customerDaoImpl implements customerDao {
//jdbc模板操作
JdbcTemplate template = new JdbcTemplate(jdbcUtil.getDataSource());
//查询所有人的信息
@Override
public List<Customer> selectAllCustomer() {
String sql = "select * from customer";
List<Customer> list = template.query(sql, new BeanPropertyRowMapper<Customer>(Customer.class));
return list;
}
//检查邮箱
@Override
public Customer ckEmailName(String email) {
String sql = "select * from customer where email=?";
try {
return this.template.queryForObject(sql, new BeanPropertyRowMapper<Customer>(Customer.class), email);
} catch (DataAccessException e) {
e.printStackTrace();
}
return null;
}
//添加客户的信息
@Override
public Boolean addCustomer(Customer customer) {
//定义sql语句
String sql = "insert into customer(name,sex,age,addr,qq,email) values(?,?,?,?,?,?) ";
//执行sql
int add = template.update(sql, customer.getName(), customer.getSex(),
customer.getAge(), customer.getAddr(), customer.getQq(), customer.getEmail());
if (add > 0) {
return true;
}
return false;
}
//删除用户信息
@Override
public void deleteCustomer(int id) {
String sql = "delete from customer where id=?";
template.update(sql, id);
}
//查询数据库是否有需要修改的数据
@Override
public Customer updateCustomer(int id) {
String sql = "select * from customer where id=id";
List<Customer> customers = template.query(sql, new BeanPropertyRowMapper<Customer>(Customer.class));
for (Customer customer1 : customers) {
if (customer1.getId() == id) {
return customer1;
}
}
return null;
}
@Override
public Boolean editeCustomer(Customer customer) {
String sql = "update customer set name=?,sex=?,age=?,addr=?,qq=?,email=? where id=?";
int edit = template.update(sql, customer.getName(), customer.getSex(),
customer.getAge(), customer.getAddr(), customer.getQq(), customer.getEmail(), customer.getId());
if (edit > 0) {
return true;
}
return false;
}
/**
* 分页功能的实现,查询总共有多少条数
*/
@Override
public int findTotalCounts(Map<String, String[]> map) {
// String sql = "select count(1) from customer";
// try {
// return template.queryForObject(sql, Integer.class);
// } catch (Exception e) {
// e.printStackTrace();
// throw new RuntimeException("sql查询条数语句出现异常");
// }
StringBuilder sql =new StringBuilder("select count(1) from customer where 1=1");
//设置可变参数
List<Object> list=new ArrayList<>();
Set<String> keySet = map.keySet();
for (String key:keySet){
//排除pageNum
if ("pageNum".equals(key)){
//跳出本次循环
continue;
}
String value=map.get(key)[0];
if (value!=null&&!value.equals("")){
sql.append(" and " + key + " like ?");
list.add("%" +value+ "%");
}
}
return template.queryForObject(sql.toString(), Integer.class,list.toArray());
}
//查询每页显示的数目
@Override
public List<Customer> findTotalCustomers(pageBean pageBean, Map<String, String[]> map) {
StringBuilder sql =new StringBuilder("select * from customer where 1=1");
//将参数放在list集合中
List<Object> list = new ArrayList<>();
//将map1集合中的内容循环遍历进行判断
Set<String> key = map.keySet();
for(String key1:key){
//排除pageNum
if ("pageNum".equals(key1)){
//跳出本次循环
continue;
}
String value = map.get(key1)[0];
if (key1!= null && !key1.equals("")){
sql.append(" and " + key1 + " like ?");
list.add("%" +value+ "%");
}
}
//进行拼接分页
sql.append(" limit ?,?");
list.add(pageBean.getStartIndex());
list.add(pageBean.getPageSize());
try {
//list.toArray转化成
return this.template.query(sql.toString(), new BeanPropertyRowMapper<Customer>(Customer.class), list.toArray());
} catch (DataAccessException e) {
e.printStackTrace();
throw new RuntimeException("sql查询分页出现异常");
}
}
}
(userDaoImpl)dao层接口实现的代码:
package cn.cyp.dao.impl;
import cn.cyp.bean.User;
import cn.cyp.dao.userDao;
import cn.cyp.util.jdbcUtil;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.Date;
/**
* @Author:cyp
* @date:2019/8/16 8:19
* @Desc:
*/
public class userDaoImpl implements userDao {
//jdbc模板操作
JdbcTemplate template = new JdbcTemplate(jdbcUtil.getDataSource());
//查询登陆的用户是否是数据库中的
@Override
public User userLogin(User user) {
String sql = "select * from user where username=? and pwd=?";
try {
return template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), user.getUsername(), user.getPwd());
} catch (DataAccessException e) {
e.printStackTrace();
}
//使用list进行获取
// String username = user.getUsername();
// String pwd = user.getPwd();
//
// String sql="select * from admin ";
// List<User> list = template.query(sql, new BeanPropertyRowMapper<User>(User.class));
// for(User user1:list){
// if(user1.getUsername().equals(username.trim()) & user1.getPwd().equals(pwd.trim())){
// return user;
// }
// }
return null;
}
//添加用户,进行判断该用户是否已经存在,使名字唯一
@Override
public User registerOk(String username) {
String sql = "select * from user where username=?";
try {
return this.template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), username);
} catch (DataAccessException e) {
e.printStackTrace();
}
return null;
}
@Override
public Boolean registerUser(User user) {
Date date=new Date();
String sql="insert into user(username,pwd,nickname,createtime,updatetime) values(?,?,?,?,?)";
int update = template.update(sql, user.getUsername(), user.getPwd(),user.getNickname(),date,date);
if (update>0){
return true;
}
return null;
}
}
service层的接口:
(customerService)service层接口的代码:
package cn.cyp.service;
import cn.cyp.bean.Customer;
import cn.cyp.bean.pageBean;
import java.util.List;
import java.util.Map;
/**
* @Author:cyp
* @date:2019/8/14 19:12
* @Desc:
*/
public interface customerService {
//查询所有用户
List<Customer> selectAllCustomer();
// 增加用户
Boolean addCustomer(Customer customer);
// 删除用户
void deleteCustomer(int id);
//删除选中的用户
void deleteCheckedCustomer(String[] items);
//修改用户
//判断用户id是不是选择的id
Customer updateCustomer(int id);
//进行编辑用户的信息
boolean editCustomer(Customer customer);
//关于分页的方法
pageBean findCustomerPage(pageBean pageBean, Map<String, String[]> map);
}
(userService)service层接口的代码:
package cn.cyp.service;
import cn.cyp.bean.User;
/**
* @Author:cyp
* @date:2019/8/15 22:05
* @Desc:
*/
public interface userService {
User userLogin(User user);
Boolean registerUser(User user);
}
service层的接口的实现:
(userServiceImpl)service层接口实现的代码:
package cn.cyp.service.impl;
import cn.cyp.bean.User;
import cn.cyp.dao.userDao;
import cn.cyp.dao.impl.userDaoImpl;
import cn.cyp.service.userService;
import cn.cyp.util.MD5Utils;
/**
* @Author:cyp
* @date:2019/8/15 22:05
* @Desc:
*/
public class userServiceImpl implements userService {
@Override
public User userLogin(User user){
//创建dao对象,调用dao里面的方法,进行判断
userDao userDao =new userDaoImpl();
return userDao.userLogin(user);
}
//判断用户是否存在
@Override
public Boolean registerUser(User user) {
//进行md5加密
user.setPwd(MD5Utils.getPWD(user.getPwd()));
//创建dao对象,调用dao里面的方法,进行判断
userDao userDao =new userDaoImpl();
//判断用户名是否为空
User u=userDao.registerOk(user.getUsername());
if (u==null){
userDao.registerUser(user);
return true;
}
return false;
}
}
(addCustomerServlet)添加客户功能的实现,web层的代码:
package cn.cyp.web;
import cn.cyp.bean.Customer;
import cn.cyp.service.customerService;
import cn.cyp.service.impl.customerServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
/**
* @Author:cyp
* @date:2019/8/16 20:38
* @Desc:添加用户信息的页面
*/
@WebServlet(urlPatterns = "/addCustomerServlet")
public class addCustomerServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//通过map获取页面上输入框的所有内容
response.setContentType("text/html;charset=utf-8");
//设置post请求字符集
request.setCharacterEncoding("utf-8");
Map<String, String[]> map = request.getParameterMap();
Customer customer = new Customer();
//进行封装实体类
try {
BeanUtils.populate(customer, map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
customerService addCustomerService = new customerServiceImpl();
Boolean customer1 = addCustomerService.addCustomer(customer);
if (customer1 == true) {
response.getWriter().print("添加成功");
request.getRequestDispatcher("/pageBeanServlet").forward(request, response);
} else {
response.getWriter().print("添加失败");
request.setAttribute("msg","邮箱已存在");
// 当邮箱存在的时候,进行回显到添加界面
request.setAttribute("old", customer);
request.getRequestDispatcher("addCustomer.jsp").forward(request, response);
}
}
}
servlet
(deleteCustomerServlet)删除客户功能的实现,web层的代码:
package cn.cyp.web;
import cn.cyp.service.customerService;
import cn.cyp.service.impl.customerServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @Author:cyp
* @date:2019/8/17 14:47
* @Desc:
*/
@WebServlet(urlPatterns = "/deleteCustomerServlet")
public class deleteCustomerServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取前台传来的id值
String idstr = request.getParameter("id");
int id=Integer.parseInt(idstr);
customerService deleteCustomerService = new customerServiceImpl();
deleteCustomerService.deleteCustomer(id);
//删除成功
response.sendRedirect(request.getContextPath()+"/pageBeanServlet");
// request.getRequestDispatcher("/selectCustomerServlet").forward(request,response);
System.out.println("删除成功");
}
}
(deleteCheckedCustomerServlet)删除选中客户功能的实现,web层的代码:
package cn.cyp.web;
import cn.cyp.service.customerService;
import cn.cyp.service.impl.customerServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* @Author:cyp
* @date:2019/8/20 18:08
* @Desc:
*/
@WebServlet(urlPatterns = "/deleteCheckedCustomerServlet")
public class deleteCheckedCustomerServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String[] items = request.getParameterValues("items");
customerService deleteCustomerService = new customerServiceImpl();
deleteCustomerService.deleteCheckedCustomer(items);
response.sendRedirect(request.getContextPath()+"/pageBeanServlet");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
(pageBeanServlet)分页和条件查询功能的实现 ,web层的代码:
package cn.cyp.web;
import cn.cyp.bean.pageBean;
import cn.cyp.service.customerService;
import cn.cyp.service.impl.customerServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
/**
* @Author:cyp
* @date:2019/8/22 9:34
* @Desc:
*/
@WebServlet(urlPatterns = "/pageBeanServlet")
public class pageBeanServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//解决乱码问题
request.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
//条件查询,获取前台传过来的pageNum,name,sex,age
Map<String, String[]> map=request.getParameterMap();
//实例化一个pageBean变量
pageBean pageBean=new pageBean();
// 使用BeanUtil封装实体类
try {
BeanUtils.populate(pageBean,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
// 注入业务层
customerService customerService=new customerServiceImpl();
pageBean pageBean1=customerService.findCustomerPage(pageBean,map);
//将pageBean的值传到浏览器
request.setAttribute("pageBean",pageBean1);
//实现输入框的值回显的功能
request.setAttribute("map",map);
request.getRequestDispatcher("/list.jsp").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
(selectCustomerServlet)查询所有用户功能的实现 ,web层的代码:
package cn.cyp.web;
import cn.cyp.bean.Customer;
import cn.cyp.service.customerService;
import cn.cyp.service.impl.customerServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/**
* @Author:cyp
* @date:2019/8/14 19:17
* @Desc:
*/
@WebServlet(urlPatterns= "/selectCustomerServlet")
public class selectCustomerServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
customerService selectCustomerService =new customerServiceImpl();
//使用list集合来接收从service传过来的值
List<Customer> list= selectCustomerService.selectAllCustomer();
request.setAttribute("list",list);
request.getRequestDispatcher("/list.jsp").forward(request,response);
}
}
(updateCustomerServlet)修改用户功能的实现 ,web层的代码:
package cn.cyp.web;
import cn.cyp.bean.Customer;
import cn.cyp.service.customerService;
import cn.cyp.service.impl.customerServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
/**
* @Author:cyp
* @date:2019/8/16 19:45
* @Desc:修改操作
*/
@WebServlet(urlPatterns= "/updateCustomerServlet")
public class updateCustomerServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//通过map获取页面上输入框的所有内容
response.setContentType("text/html;charset=utf-8");
//设置post请求字符集
request.setCharacterEncoding("utf-8");
Map<String, String[]> map = request.getParameterMap();
Customer customer = new Customer();
//进行封装实体类
try {
BeanUtils.populate(customer, map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
customerService updateCustomerService = new customerServiceImpl();
boolean customer1 = updateCustomerService.editCustomer(customer);
if (customer1 == true) {
response.getWriter().print("添加成功");
request.getRequestDispatcher("/pageBeanServlet").forward(request, response);
} else {
response.getWriter().print("添加失败");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
String idstr = request.getParameter("id");
int id=Integer.parseInt(idstr);
customerService updateCustomerService = new customerServiceImpl();
Customer customer1 = updateCustomerService.updateCustomer(id);
//判断是否是需要的id
if (customer1!=null) {
request.setAttribute("customer",customer1);
request.getRequestDispatcher("/updateCustomer.jsp").forward(request,response);
}
System.out.println("查询不到");
}
}
(userLoginServlet)user登陆功能的实现
package cn.cyp.web;
import cn.cyp.bean.User;
import cn.cyp.service.impl.userServiceImpl;
import cn.cyp.service.userService;
import cn.cyp.util.MD5Utils;
import org.apache.commons.beanutils.BeanUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
/**
* @Author:cyp
* @date:2019/8/15 21:06
* @Desc: 查询所有的人员的信息的dao层
*/
@WebServlet(urlPatterns = "/userLoginTestServlet")
public class userLoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//获取用户输入的验证码
String img = request.getParameter("img");
//获取服务器验证码的内容,session
HttpSession session = request.getSession();
//获取登陆框的内容
String imgsession =(String) session.getAttribute("CHECKCODE_SERVER");
//判断不匹配的情况
if(!img.equalsIgnoreCase(imgsession)){
request.setAttribute("imgmsg","验证码错误");
request.getRequestDispatcher("/login.jsp").forward(request,response);
return;
}
//再进行获取从前台输入的内容
Map<String, String[]> map = request.getParameterMap();
User user =new User();
//将从登陆框中获取的内容通过传参传到后面,进行判断
try {
//进行MD5解码
user.setUsername(MD5Utils.getPWD(user.getPwd()));
BeanUtils.populate(user,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
userService userLoginService =new userServiceImpl();
User adminService1 = userLoginService.userLogin(user);
if(adminService1!=null){
//表示成功之后将用户名记住
// Cookie cookie=new Cookie("name",username);
// //设置生存时间
// cookie.setMaxAge(60*60);
// //响应给浏览器
// response.addCookie(cookie);
response.sendRedirect(request.getContextPath()+"/pageBeanServlet");
//创建ssession对象
HttpSession session1 = request.getSession();
session1.setAttribute("username",user.getUsername());
response.getWriter().print("登陆成功");
}else{
request.getRequestDispatcher("/login.jsp").forward(request,response);
response.getWriter().print("登录失败");
}
}
}
(userOutLoginServlet)user注销功能的的实现,web层的代码:
package cn.cyp.web;
import javax.servlet.ServletException;
import javax.servlet.SessionCookieConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
/**
* @Author:cyp
* @date:2019/8/16 15:17
* @Desc:
*/
@WebServlet(urlPatterns= "/userOutLoginServlet")
public class userOutLoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
//获取session对象
HttpSession session = request.getSession();
//手动去销毁session对象
session.invalidate();
request.getRequestDispatcher("/login.jsp").forward(request,response);
}
}
(userRegisterServlet)user注册功能的的实现,web层的代码:
package cn.cyp.web;
import cn.cyp.bean.User;
import cn.cyp.dao.impl.userDaoImpl;
import cn.cyp.service.impl.userServiceImpl;
import cn.cyp.service.userService;
import org.apache.commons.beanutils.BeanUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
/**
* @Author:cyp
* @date:2019/8/19 15:12
* @Desc:
*/
@WebServlet(urlPatterns = "/userRegisterServlet")
public class userRegisterServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String img = request.getParameter("img");
//创建session对象
HttpSession session = request.getSession();
String code = (String)session.getAttribute("code");
//进行判断输入框的内容和验证码是否一致
if(!code.equalsIgnoreCase(img)) {
request.setAttribute("imgmsg","验证码错误");
request.getRequestDispatcher("/register.jsp").forward(request,response);
return;
}
Map<String, String[]> map = request.getParameterMap();
User user = new User();
try {
BeanUtils.populate(user,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//进行判断用户名和密码不能为空
if(user.getUsername()==null||user.getPwd()==null||user.getUsername()==""||user.getPwd()==""){
request.getRequestDispatcher("/register.jsp").forward(request,response);
}
//进行判断该用户是否存在
userService userService = new userServiceImpl();
Boolean flag = userService.registerUser(user);
if (flag) {
System.out.println("添加成功");
request.getRequestDispatcher("login.jsp").forward(request,response);
}else {
System.out.println("添加失败");
}
}
}
jsp部分的代码
(addCustomer.jsp)添加用户的页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/jquery/1.11.3/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
function check() {
//验证年龄
var age = document.getElementById("ageid");
if(isNaN(age.value)){
document.getElementById("spanage").innerHTML="年龄只能是数字";
return false;
}
if(age.value.length==0){
document.getElementById("spanage").innerHTML="年龄不能为空";
return false;
}
//验证邮箱
var emailid = document.getElementById("emailid");
//不区分邮箱大小写
var regExp = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/
if (!regExp.test(emailid.value)) {
document.getElementById("spanemail").innerHTML="请输入正确的邮箱";
return false;
}
return true;
}
</script>
</head>
<body>
<h2 align="center">请输入添加用户信息</h2>
<div style="text-align:center;padding-left: 300px" class="container table-responsive">
<form action="${pageContext.request.contextPath}/addCustomerServlet" method="post" onsubmit="return check()">
<table class="table table-bordered table-hover" style="width: 600px;">
<tr>
<td>姓名:</td>
<td><input type="text" name="name" id="nameid" value="${old.name}" ></td>
</tr>
<tr>
<td>性别:</td>
<td>
<input type="radio" checked="checked" name="sex" value="女"
<c:if test="${old.sex=='女'}">checked</c:if>
/>女
<input type="radio" name="sex" value="男"
<c:if test="${old.sex=='男'}">checked</c:if>/>男
</td>
</tr>
<tr>
<td>年龄:</td>
<td>
<input type="text" name="age" id="ageid" value="${old.age}">
<span id="spanage" style="color: red"></span>
</td>
</tr>
<tr>
<td>籍贯:</td>
<td>
<select name="addr" id="addrid">
<option value="河南省" selected="selected" <c:if test="${old.addr=='河南省'}">selected</c:if>>河南省</option>
<option value="郑州" <c:if test="${old.addr=='郑州'}">selected</c:if>>郑州</option>
<option value="开封" <c:if test="${old.addr=='开封'}">selected</c:if>>开封</option >
<option value="商丘" <c:if test="${old.addr=='商丘'}">selected</c:if>>商丘</option>
</select>
</td>
</tr>
<tr>
<td>qq:</td>
<td><input type="text" name="qq" id="qqid" value="${old.qq}"></td>
</tr>
<tr>
<td>邮箱:</td>
<td>
<input type="text" name="email" id="emailid" value="${old.email}">
<span id="spanemail"style="color: red">${msg}</span>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" class="btn btn-primary" value="提交">
<input type="reset" class="btn btn-primary" value="重置">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/pageBeanServlet">返回</a>
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
**(list.jsp)显示首页面**
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bootstrap 101 Template</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/jquery/1.11.3/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
//获取全选/全不选的id
function checkall() {
var checkinputid = document.getElementById("checkinputid");
// 获取所有名字为id的对象
var items = document.getElementsByName("items");
// 进行循环遍历
for (var i = 0; i < items.length; i++) {
//使得全选,全不选的内容为选中,选不中
items[i].checked = checkinputid.checked;
}
}
function isdelete() {
//是否删除所选的内容
var b = window.confirm("您确定删除吗?");
if (b) {
alert("确定");
} else {
alert("取消")
}
}
// 进行判断有没有选择复选框
window.onload = function () {
document.getElementById("selectdelete").onclick = function () {
// 取得所有选中的checkbox
var items = document.getElementsByName("items");
var str = "";
//遍历checkbox
for (var i = 0; i < items.length; i++) {
if (items[i].checked == true) {
str += items[i].value + ",";
}
}
if (str == "") {
alert("请先选择复选框")
} else {
var b = window.confirm("确定要删除编号:" + str);
if (b) {
document.getElementById("formid").submit();
}
}
}
}
// 分页的方法
function go(pageNum) {
location.href = "${pageContext.request.contextPath}/pageBeanServlet?name=${map.name[0]}&age=${map.age[0]}&sex=${map.sex[0]}&pageNum=" + pageNum;
}
</script>
<head>
<title>Title</title>
</head>
<body>
<%--<form action="${pageContext.request.contextPath}/deleteCheckedCustomerServlet" method="post">--%>
<div class="row">
<div class="col-lg-1"></div>
<div class="col-lg-6">
欢迎<font size="5px" color="red">${sessionScope.username}</font>登陆:
</div>
</div>
<div class="row">
<div class="col-lg-1"></div>
<div class="col-lg-6">
<a href="${pageContext.request.contextPath}/userOutLoginServlet"><font size="3px" color="red">注销</font></a>
</div>
</div>
<h1 style="text-align: center;color: red">用户管理系统</h1>
<div class=" container" style="margin-top: 60px;">
<div class="container" style="margin-top: 20px;margin-bottom: 10px">
<%--模糊查询--%>
<div class="row">
<form action="${pageContext.request.contextPath}/pageBeanServlet" method="post">
<div class="col-lg-2">
<input type="text" class="form-control" name="name" value="${map.name[0]}" placeholder="按姓名查">
</div>
<div class="col-lg-2">
<input type="text" class="form-control" name="age" value="${map.age[0]}" placeholder="按年龄查">
</div>
<div class="col-lg-2">
<input type="text" class="form-control" name="sex" value="${map.sex[0]}" placeholder="按性别查">
</div>
<div class="col-lg-3">
<%--onclick='window.location.href<c:if test="${pageBean.totalCounts==0}">="index.jsp"</c:if>'--%>
<input type="submit" class="btn btn-warning btn-md " value="查询" >
</div>
</form>
<div class="col-lg-3" style="padding-right: 0px">
<a class="btn btn-primary" href="addCustomer.jsp">添加客户</a>
<a class="btn btn-primary" href="javaScript:void(0);" id="selectdelete">删除客户</a>
<%--<button class="btn btn-primary" onclick="javascript:window.location.reload();" >刷新</button>--%>
<a class="btn btn-primary" href="${pageContext.request.contextPath}/pageBeanServlet">刷新</a>
<%--<input type="submit" class="btn btn-primary" value="删除选中" onclick="isdelete()">--%>
</div>
</div>
</div>
<form id="formid" action="${pageContext.request.contextPath}/deleteCheckedCustomerServlet" method="post">
<table class="table table-bordered table-hover" <c:if test="${pageBean.totalCounts==0}">hidden</c:if> >
<tr class="success">
<th>
<input type="checkbox" id="checkinputid" onclick="checkall()">全选/全不选
</th>
<th>编号</th>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
<th>籍贯</th>
<th>qq</th>
<th>邮箱</th>
<th>操作</th>
</tr>
<c:forEach items="${requestScope.pageBean.list}" var="list">
<tr>
<td>
<input type="checkbox" name="items" id="items" value="${list.id}">
</td>
<td>${list.id}</td>
<td>${list.name}</td>
<td>${list.sex}</td>
<td>${list.age}</td>
<td>${list.addr}</td>
<td>${list.qq}</td>
<td>${list.email}</td>
<td>
<a class="btn btn-default btn-lg"
href="${pageContext.request.contextPath}/updateCustomerServlet?id=${list.id}">修改</a>
<a class="btn btn-default btn-lg"
href="${pageContext.request.contextPath}/deleteCustomerServlet?id=${list.id}">删除</a></td>
</tr>
</c:forEach>
</table>
</form>
<%--分页--%>
<%--如果在数据库没有搜到相关信息,提示一句话"未查到相关信息"--%>
<div <c:if test="${pageBean.totalCounts!=0}">hidden</c:if> >
<span style="color: red;font-size: 40px;text-align: center">未查询到内容</span>
</div>
<div>
<nav class="nav1">
<ul class="pagination pagination-lg">
<li>
<span>当前页${pageBean.pageNum}/${pageBean.totalPages}</span>
<a <c:if test="${pageBean.totalCounts==0}">hidden</c:if> href="javascript:void(0);" onclick="go(1)">首页</a>
<a <c:if test="${pageBean.totalCounts==0}">hidden</c:if> href="javascript:void(0);" onclick="go(${pageBean.beforePage})" aria-label="Previous">
<span aria-hidden="true">上一页</span>
</a>
</li>
<%--分页栏--%>
<c:forEach items="${pageBean.pageBar}" var="bar">
<c:if test="${pageBean.pageNum==bar}">
<%--显示**状态active--%>
<li class="active"><a href="">${bar}</a></li>
</c:if>
<c:if test="${pageBean.pageNum!=bar}">
<li class=""><a href="javascript:void(0)" onclick="go(${bar})">${bar}</a></li>
</c:if>
</c:forEach>
<li>
<%--判断最大条数是不是0--%>
<a <c:if test="${pageBean.totalCounts==0}">hidden</c:if> href="javascript:void(0);" onclick="go(${pageBean.nextPage})" aria-label="Next">
<span aria-hidden="true">下一页</span>
<a <c:if test="${pageBean.totalCounts==0}">hidden</c:if> href="javascript:void(0);" onclick="go(${pageBean.totalPages})">尾页</a>
<span>共${pageBean.totalCounts}条</span>
</a>
</li>
</ul>
</nav>
</div>
</div>
</body>
</html>
(login.jsp)登陆界面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/jquery/1.11.3/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
//传到submit中的条件
function demo1() {
var inputusername = document.getElementById("inputusername");
var inputpwd = document.getElementById("inputpwd");
if ((inputusername.value=="") || (inputpwd.value=="")){
alert("请检查您的用户名和密码");
return false;
}
return true;
}
function demo() {
var img = document.getElementById("_img");
//通过拼接字符串的方式,对验证码进行切换
img.src="${pageContext.request.contextPath}/checkCodeServlet?"+new Date().getTime();
}
</script>
</head>
<body background="img/bg3.jpg" style="width: 100%" >
<div class="row" style="padding-top: 50px">
<div class="col-lg-5"></div>
<div class="col-lg-2"><h1>管理员登陆</h1></div>
</div>
<div class="container" style="padding-left: 250px ;padding-top: 50px;">
<form class="form-horizontal" action="${pageContext.request.contextPath}/userLoginTestServlet" method="post"
onsubmit="return demo1();">
<div class="form-group">
<label for="inputusername" class="col-lg-2 control-label">用户名</label>
<div class="col-lg-4">
<input type="text" class="form-control" name="username" id="inputusername" placeholder="请输入用户名">
</div>
</div>
<div class="form-group">
<label for="inputPassword" class="col-lg-2 control-label">密码</label>
<div class="col-lg-4">
<input type="password" class="form-control" name="pwd" id="inputPassword" placeholder="请输入密码">
</div>
<div class="“col-lg-2">
<span id="spanid"></span>
</div>
</div>
<div class="form-inline">
<label for="checkcode" class="col-lg-2 control-label">验证码</label>
<input type="text" class="form-control" name="img" id="checkcode" placeholder="请输入验证码">
<img src="${pageContext.request.contextPath}/checkCodeServlet" id="_img" onclick="demo()">
${requestScope.imgmsg}
</div>
<div class="form-group" style="margin-top: 10px;margin-left: 10px">
<div class="col-lg-offset-2 col-lg-10">
<input type="submit" class="btn btn-primary" value="登陆">
没有账号,点击<a class="" href="register.jsp" style="text-decoration: none">注册</a>
</div>
</div>
</form>
</div>
</body>
</html>
(register.jsp)注册界面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/jquery/1.11.3/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
//检查验证码是否一致
function demo200() {
var _img = document.getElementById("_img");
//通过拼接字符串的方式,对验证码进行切换
_img.src = "${pageContext.request.contextPath}/Checkcode?" + new Date().getTime();
}
<%--清除所有框的历史记录--%>
window.onload = function () {
var tagName = document.getElementsByTagName("input");
for (var i = 0; i < tagName.length; i++) {
tagName[i].setAttribute("autocomplete", "off");
}
}
//返回的一个方法的true或者false结果
function checkdemo(){
<%--检查输入的用户名是否符合要求--%>
var username = document.getElementById("inputname");
var regUsername=/^[a-zA-Z][a-zA-Z0-9]{3,15}$/;
if (!regUsername.test(username.value)) {
document.getElementById("strongid").innerHTML ="用户名由英文字母和数字组成的4-16位字符,以字母开头";
return false;
}
//检查密码的格式是否正确
/*密码验证*/
var inputPassword1 = document.getElementById("inputPassword1");
var regpwd=/^[a-zA-Z0-9]{4,10}$/;
if(!regpwd.test(inputPassword1.value)){
document.getElementById("strongid").innerHTML="密码不能含有非法字符,长度在4-10之间";
return false;
}
//检查两次输入的密码是否一致
var inputPassword2 = document.getElementById("inputPassword2");
if (inputPassword1.value != inputPassword2.value) {
document.getElementById("strongid").innerHTML = "两次输入的密码不一致";
return false;
}
return true;
}
</script>
</head>
<body background="img/bg3.jpg" style="width: 100%">
<div class="row" style="padding-top: 50px">
<div class="col-lg-5"></div>
<div class="col-lg-2"><h1>管理员注册</h1></div>
</div>
<div class="container" style="padding-left: 250px ;padding-top: 50px;">
<form class="form-horizontal" action="${pageContext.request.contextPath}/userRegisterServlet" method="post"
onsubmit="return checkdemo()">
<div class="form-group">
<label for="inputname" class="col-lg-2 control-label">用户名</label>
<div class="col-lg-4">
<input type="text" class="form-control" name="username" id="inputname" placeholder="请输入用户名">
</div>
</div>
<div class="form-group">
<label for="inputNickname" class="col-lg-2 control-label">昵称</label>
<div class="col-lg-4">
<input type="text" class="form-control" name="nickname" id="inputNickname" placeholder="请输入昵称">
</div>
</div>
<div class="form-group">
<label for="inputPassword1" class="col-lg-2 control-label">密码</label>
<div class="col-lg-4">
<input type="password" class="form-control" name="pwd" id="inputPassword1" placeholder="请输入密码">
</div>
<div class="“col-lg-2">
<span id="spanid"></span>
</div>
</div>
<div class="form-group">
<label for="inputPassword2" class="col-lg-2 control-label">确认密码</label>
<div class="col-lg-4">
<input type="password" class="form-control" id="inputPassword2" placeholder="请再次确认密码">
</div>
</div>
<div class="form-inline">
<label for="checkcode" class="col-lg-2 control-label">验证码</label>
<input type="text" class="form-control" name="img" id="checkcode" placeholder="请输入验证码">
<img src="${pageContext.request.contextPath}/Checkcode" id="_img" onclick="demo200()">
</div>
<div class="form-group" style="margin-top: 10px;margin-left: 10px">
<div class="col-lg-offset-2 col-lg-10">
<button type="submit" class="btn btn-primary">注册</button>
<button type="reset" class="btn btn-primary">重置</button>
</div>
</div>
<div class="container" style="padding-left: 140px">
<%--出错信息框--%>
<div class="alert alert-warning alert-dismissible" role="alert" style="text-align: center;width: 350px;height: 50px">
<button type="button" class="close" data-dismiss="alert">
<span class="glyphicon glyphicon-remove"></span>
</button>
<strong id="strongid">${imgmsg}</strong>
</div>
</div>
</form>
</div>
</body>
</html>
(updateCustomer.jsp)修改用户的界面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/jquery/1.11.3/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script>
<%--进行判断id,id不可被修改--%>
</script>
</head>
<body>
<h2 align="center">修改用户数据</h2>
<div style="text-align:center;padding-left: 300px" class="container table-responsive">
<form action="${pageContext.request.contextPath}/updateCustomerServlet" method="post">
<table class="table table-bordered table-hover" style="width: 600px;">
<tr>
<td>id:</td>
<td>
<input type="text" name="id" value="${customer.id}" id="idid" readonly="readonly" onclick="demo()">
<span id="spanid" style="color: red">id不可被修改</span>
</td>
</tr>
<tr>
<td>姓名:</td>
<td><input type="text" name="name" value="${customer.name}" id="nameid"></td>
</tr>
<tr>
<td>性别:</td>
<td>
<input type="radio" checked="checked" name="sex" value="女"
<c:if test="${customer.sex=='女'}">checked</c:if>/>女
<input type="radio" name="sex" <c:if test="${customer.sex=='男'}">checked</c:if> value="男"/>男
</td>
</tr>
<tr>
<td>年龄:</td>
<td>
<input type="text" name="age" value="${customer.age}" id="ageid">
<span id="spanage"style="color: red"></span>
</td>
</tr>
<tr>
<td>籍贯:</td>
<td>
<select name="addr" id="addrid">
<option value="河南省" selected="selected" <c:if test="${customer.addr=='河南省'}">selected</c:if>>河南省</option>
<option value="郑州" <c:if test="${customer.addr=='郑州'}">selected</c:if>>郑州</option>
<option value="开封" <c:if test="${customer.addr=='开封'}">selected</c:if>>开封</option >
<option value="商丘" <c:if test="${customer.addr=='商丘'}">selected</c:if>>商丘</option>
</select>
</td>
</tr>
<tr>
<td>qq:</td>
<td><input type="text" name="qq" value="${customer.qq}" id="qqid"></td>
</tr>
<tr>
<td>邮箱:</td>
<td>
<input type="text" name="email" value="${customer.email}" id="emailid">
<span id="spanemail"style="color: red"></span>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" class="btn btn-primary" value="提交">
<input type="reset" class="btn btn-primary" value="重置">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/pageBeanServlet">返回</a>
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
工具类的编写
需要验证码工具类(Checkcode),(checkCodeServlet),
jdbc数据库(jdbcUtil),MD5Utils(加密),MyFilter.java(过滤器)
为了解决页面显示乱码问题,配合myFilter.java过滤器进行配置web.xml
配置web.xml如下代码:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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></display-name>
<!-- 处理乱码 -->
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>cn.cyp.util.MyFilter</filter-class>
<init-param>
<param-name>type</param-name>
<param-value>text/html</param-value>
</init-param>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
工具类:jdbc
jdbc连数据库:
package cn.cyp.util;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
public class jdbcUtil {
// 工具类的抽取
// 定义成员们变量DataSource
private static DataSource ds;
static {
Properties pro = null;
try {
//1.加载配置文件
pro = new Properties();
InputStream is = jdbcUtil.class.getClassLoader().getResourceAsStream("druid.properties");
pro.load(is);
//2.获取DataSource
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection() throws Exception {
return ds.getConnection();
}
// 释放资源
public static void close(Connection conn, Statement stmt) {
try {
if (stmt != null) {
stmt.close();
stmt = null;//gc垃圾回收机制会优先处理这些对象
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (conn != null) {
conn.close();
conn = null;//gc垃圾回收机制会优先处理这些对象
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void close(Connection conn, Statement stmt, ResultSet rs) {
try {
if (rs != null) {
rs.close();
rs = null;//gc垃圾回收机制会优先处理这些对象
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (stmt != null) {
stmt.close();
stmt = null;//gc垃圾回收机制会优先处理这些对象
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (conn != null) {
conn.close();
conn = null;//gc垃圾回收机制会优先处理这些对象
}
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接池的办法
public static DataSource getDataSource() {
return ds;
}
}
MD5Utils(加密)
package cn.cyp.util;
import java.security.MessageDigest;
import java.security.MessageDigest;
/*
* 负责给字符串数据进行加密
*/
public class MD5Utils {
public static String getPWD( String strs ){
/*
* 加密需要使用JDK中提供的类
*/
StringBuffer sb = new StringBuffer();
try{
MessageDigest digest = MessageDigest.getInstance("MD5");
byte[] bs = digest.digest(strs.getBytes());
/*
* 加密后的数据是-128 到 127 之间的数字,这个数字也不安全。
* 取出每个数组的某些二进制位进行某些运算,得到一个具体的加密结果
*
* 0000 0011 0000 0100 0010 0000 0110 0001
* &0000 0000 0000 0000 0000 0000 1111 1111
* ---------------------------------------------
* 0000 0000 0000 0000 0000 0000 0110 0001
* 把取出的数据转成十六进制数
*/
for (byte b : bs) {
int x = b & 255;
String s = Integer.toHexString(x);
if( x > 0 && x < 16 ){
sb.append("0");
sb.append(s);
}else{
sb.append(s);
}
}
}catch( Exception e){
System.out.println("加密失败");
}
return sb.toString();
}
}
checkCodeServlet(验证码)
package cn.cyp.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 验证码
*/
@WebServlet(urlPatterns = "/checkCodeServlet")
public class checkCodeServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
//服务器通知浏览器不要缓存
response.setHeader("pragma","no-cache");
response.setHeader("cache-control","no-cache");
response.setHeader("expires","0");
//在内存中创建一个长80,宽30的图片,默认黑色背景
//参数一:长
//参数二:宽
//参数三:颜色
int width = 80;
int height = 30;
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//获取画笔
Graphics g = image.getGraphics();
//设置画笔颜色为灰色
g.setColor(Color.GRAY);
//填充图片
g.fillRect(0,0, width,height);
//产生4个随机验证码,12Ey
String checkCode = getCheckCode();
//将验证码放入HttpSession中
request.getSession().setAttribute("CHECKCODE_SERVER",checkCode);
//设置画笔颜色为黄色
g.setColor(Color.YELLOW);
//设置字体的小大
g.setFont(new Font("黑体",Font.BOLD,24));
//向图片上写入验证码
g.drawString(checkCode,15,25);
//将内存中的图片输出到浏览器
//参数一:图片对象
//参数二:图片的格式,如PNG,JPG,GIF
//参数三:图片输出到哪里去
ImageIO.write(image,"PNG",response.getOutputStream());
}
/**
* 产生4位随机字符串
*/
private String getCheckCode() {
String base = "0123456789ABCDEFGabcdefg";
int size = base.length();
Random r = new Random();
StringBuffer sb = new StringBuffer();
for(int i=1;i<=4;i++){
//产生0到size-1的随机值
int index = r.nextInt(size);
//在base字符串中获取下标为index的字符
char c = base.charAt(index);
//将c放入到StringBuffer中去
sb.append(c);
}
return sb.toString();
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}
MyFilter.java(过滤器)
package cn.cyp.util;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
/**
* 解决乱码问题
* @author Administrator
*
*/
public class MyFilter implements Filter {
private String type;
private String encoding;
@Override
public void destroy() {
// 容器正常关闭 该方法会被执行..
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
// 过滤器业务方法编写 默认 拦截后续资源的访问的
// 重写getParameter 方法!
// 思想: 自己编写 HttpServletRequest接口实现类 覆盖getParameter 方法 自己定义解码 utf-8
MyRequest myrequest = new MyRequest(request);// 构造方法注入 对象
response.setContentType(type+";charset="+encoding);// perperties xml
// class MYRequest implements HttpServletRequest /////{ getParamter getParameterValue getParam..Map}
// 自己定义request 具备 getParameter系统方法 重写 保留 request其他api 的使用
chain.doFilter(myrequest, response);// request response 传递下去 ... 将request response 对象传递后续 servlet /jsp
}
@Override
public void init(FilterConfig config) throws ServletException {
type = config.getInitParameter("type");
encoding = config.getInitParameter("encoding");
}
}
// 找接口 中间类 Wrapper 包装类 加强 paramter 默认iso-8859-1 继承 HttpServletRequestWrapper 加强 getParameterXX sun 公司 设计类
class MyRequest extends HttpServletRequestWrapper {
private HttpServletRequest request;// 获取 为加强 request 对象
private boolean flag = false;
public MyRequest(HttpServletRequest request) {
super(request);
// TODO Auto-generated constructor stub
this.request = request;
}
@Override
public String getParameter(String name) {
// 首先获取请求方式 ... key 表单 input name 对应属性值 value 表单用户提交信息数据 String[]
Map<String, String[]> map = getParameterMap();
if (map != null && map.size() != 0) {
String[] values = map.get(name);
if (values != null && values.length != 0) {
return values[0];
}
}
return super.getParameter(name);
}
@Override
public String[] getParameterValues(String name) {
Map<String, String[]> map = getParameterMap();
if (map != null && map.size() != 0) {
String[] values = map.get(name);
if (values != null && values.length != 0) {
return values;
}
}
return super.getParameterValues(name);
}
@Override
public Map getParameterMap() {
// get/post
String method = request.getMethod();
if ("post".equalsIgnoreCase(method)) {
try {
request.setCharacterEncoding("utf-8");
return request.getParameterMap();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
// 后续代码调用 getParameter getParameterValues 重复调用 getParameterMap
// 引入标记 开关 boolean 1--100 素数 双色球 6 1 1-33 6个红球 01 02 ...33 08
if ("get".equalsIgnoreCase(method)) {
if (!flag) {
// 必须要获取 map 遍历map 将 String[] 值获取 每一个数组元素都要 先编码后解码
Map<String, String[]> map = request.getParameterMap();// 原始request 获取数据 iso-88590-1解码
if (map != null && map.size() != 0) {
for (String key : map.keySet()) {
// 每一次循环 获取 map key
String[] values = map.get(key);
if (values != null && values.length != 0) {
// 先编码 后解码 forIn 简化查询
for (int i = 0; i < values.length; i++) {
try {
values[i] = new String(values[i].getBytes("iso-8859-1"), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
}
}
flag = true;
return map;
}
}
return super.getParameterMap();// 其他的请求
}
}