1.web层
2.业务逻辑层
3.数据访问层
1.创建javaweb项目
2.WEB-INF/lib下导入依赖jar包
3.前端框架导入(js,css,fonts文件夹)
4.src下 dao文件夹存放 数据访问层的 接口和实现类
5.service文件夹存放 业务逻辑层的 接口和实现类
6.web文件夹存放 web层的 servlet 和 其他
7.domain文件夹下存放 javaBean类
8.util文件夹下存放 工具类
9.src目录下存放JDBC连接池配置文件
1.1.1 login.jsp代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html lang="zh-CN">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>管理员登录title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/jquery-2.1.0.min.js">script>
<script src="js/bootstrap.min.js">script>
head>
<body>
<div class="container" style="width: 400px;">
<h3 style="text-align: center;">管理员登录h3>
<form action="${pageContext.request.contextPath}/servletLogin" method="post">
<div class="form-group">
<label for="user">用户名:label>
<input type="text" name="username" class="form-control" id="user" placeholder="请输入用户名"/>
div>
<div class="form-group">
<label for="password">密码:label>
<input type="password" name="password" class="form-control" id="password" placeholder="请输入密码"/>
div>
<div class="form-inline">
<label for="vcode">验证码:label>
<input type="text" name="verifycode" class="form-control" id="verifycode" placeholder="请输入验证码" style="width: 120px;"/>
<a href="javascript:refreshCode()"><img src="${pageContext.request.contextPath}/checkCodeServlet" title="看不清点击刷新" id="vcode"/>a>
div>
<hr/>
<div class="form-group" style="text-align: center;">
<input class="btn btn btn-primary" type="submit" value="登录">
div>
form>
<div class="alert alert-warning alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" >
<span>×span>button>
<strong>${login_msg}strong>
div>
div>
<script type="text/javascript">
function refreshCode() {
document.getElementById("vcode").src = "${pageContext.request.contextPath}/checkCodeServlet?"+new Date().getTime();
}
script>
body>
html>
1.2.1 ServletLogin.java代码
package web.servlet;
import domain.User;
import org.apache.commons.beanutils.BeanUtils;
import service.Impl.UserServiceImpl;
import service.UserService;
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;
@WebServlet(name = "ServletLogin", urlPatterns = "/servletLogin")
public class ServletLogin extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//1.获取参数
String vcode = request.getParameter("verifycode");
Map<String, String[]> map = request.getParameterMap();
//1.验证码校验
HttpSession session = request.getSession();
String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
//确保验证码一次性
session.removeAttribute("CHECKCODE_SERVER");
if(!checkcode_server.equalsIgnoreCase(vcode)){
//显示错误数据 转发
request.setAttribute("login_msg","验证码错误");
request.getRequestDispatcher("/login.jsp").forward(request,response);
return;
}
//2.封装对象
User user = new User();
try {
BeanUtils.populate(user,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
// 2.查询数据库
UserService service = new UserServiceImpl();
User loginUser = service.login(user);
// 3.判断user是否为空
if (loginUser != null) {
session.setAttribute("user",loginUser);
request.getRequestDispatcher("/index.jsp").forward(request,response);
}else {
request.setAttribute("login_msg","用户名或密码错误");
request.getRequestDispatcher("/login.jsp").forward(request,response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
1.2.2 CheckCodeServlet代码(用java创建验证码)
package web.servlet;
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("/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);
}
}
1.3.1 UserService.interface接口代码
package service;
import domain.PageBean;
import domain.User;
import java.util.List;
import java.util.Map;
/**
* 用户管理的业务接口
*/
public interface UserService {
/**
* 查询用户所有信息
* @return
*/
public List<User> findAll();
/**
* 用户登录
* @param user
* @return
*/
User login(User user);
/**
* 添加用户
* @return
*/
void add(User user);
/**
* 删除用户
*/
void delete(String id);
/**
* 查询某一个需要修改的用户信息
* @param id
* @return
*/
User findCharacter(String id);
/**更新用户信息
* @param user
*/
void update(User user);
/**删除选中的信息
* @param map
*/
void deleteChecked(Map<String, String[]> map);
/**分页查询
* @param n
* @return
*/
List<User> pagingUser(String n);
/**得到PageBean对象
* @param pageNow
* @param rows
* @param condition
* @return
*/
PageBean<User> getPageBean(String pageNow, String rows, Map<String, String[]> condition);
}
1.3.2 UserServiceImpl.java代码
package service.Impl;
import dao.Impl.UserDaoImpl;
import dao.UserDao;
import domain.PageBean;
import domain.User;
import service.UserService;
import java.util.List;
import java.util.Map;
public class UserServiceImpl implements UserService {
/*三层架构分别是
* 界面层 业务逻辑层 数据访问层
* 在业务逻辑层当中 创建一个接口 创建一个实现类
* 在实现类当中定义一个成员变量为 数据访问层的接口的引用对应的实现类对象
* 调用数据访问层的方法 返回一个从数据库查询出来的User List集合*/
private UserDao userDao = new UserDaoImpl();
@Override
public List<User> findAll() {
return userDao.findAll();
}
@Override
public User login(User user) {
return userDao.login(user.getUsername(),user.getPassword());
}
@Override
public void add(User user) {
userDao.add(user);
}
@Override
public void delete(String id) {
userDao.delete(Integer.parseInt(id));
}
@Override
public User findCharacter(String id) {
return userDao.findCharacter(id);
}
@Override
public void update(User user) {
userDao.update(user);
}
@Override
public void deleteChecked(Map<String, String[]> map) {
userDao.deleteChecked(map);
}
@Override
public List<User> pagingUser(String n) {
//不仅要返回userList 而且还得调用findAll查出所有数据 / rows 返回总页数
//所以返回pageBean、
return userDao.pagingUser(n);
}
@Override
public PageBean<User> getPageBean(String pageNow, String rows, Map<String, String[]> condition) {
Integer _pageNow = Integer.parseInt(pageNow);
Integer _rows = Integer.parseInt(rows);
//0.创建PageBean
PageBean<User> pageBean = new PageBean<>();
//1.开始索引
Integer start = (_pageNow-1)*_rows;
//2.所有数据的个数
Integer dataCount = userDao.findAllCount(condition);
System.out.println(dataCount);
//3.分页个数
Integer pageCount = dataCount%_rows == 0 ? dataCount/_rows:dataCount/_rows+1;
//4.本页显示的User列表List
List<User> userList = userDao.getUserList(start,_rows,condition);
//5.给PageBean里边封装数据
pageBean.setList(userList);
pageBean.setDataCount(dataCount);
pageBean.setPageCount(pageCount);
pageBean.setRows(_rows);
pageBean.setPageNow(_pageNow);
/*前端的数据都是后端给的
* 所以考虑问题的时候 先考虑后端 只需要根据前端的需求 去处理或者创建出来相应的数据就好了 不用去考虑前端
* 直接从地址栏中去访问后端数据 模拟前端数据 就好了
* 先考虑后端 再考虑前端*/
return pageBean;
}
}
1.4.1 UserDao.interface代码
package dao;
import domain.User;
import java.util.List;
import java.util.Map;
/**
* 用户调用DAO
*/
public interface UserDao {
List<User> findAll();
User login(String username, String password);
void add(User user);
void delete(Integer id);
User findCharacter(String id);
void update(User user);
void deleteChecked(Map<String, String[]> map);
List<User> pagingUser(String n);
Integer findAllCount(Map<String, String[]> condition);
List<User> getUserList(Integer start, Integer rows, Map<String, String[]> condition);
}
1.4.2 UserDaoImpl.java代码
package dao.Impl;
import dao.UserDao;
import domain.User;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import util.JDBCUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class UserDaoImpl implements UserDao {
private JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
@Override
public List<User> findAll() {
//操作数据库
String sql = "select * from user ";
List<User> users = jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class));
return users;
}
@Override
public User login(String username, String password) {
try {
String sql = "select * from user where username=? and password = ?";
User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), username, password);
return user;
} catch (DataAccessException e) {
e.printStackTrace();
return null;
}
}
@Override
public void add(User user) {
String sql = "insert into user values(null,?,?,?,?,?,?,null,null)";
jdbcTemplate.update(sql,user.getName(),user.getGender(),user.getAge(),user.getAddress(),user.getQq(),user.getEmail());
}
@Override
public void delete(Integer id) {
String sql = "delete from user where id = ?";
jdbcTemplate.update(sql,id);
}
@Override
public User findCharacter(String id) {
Integer i = Integer.parseInt(id);
String sql = "select * from user where id = ?";
User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), i);
return user;
}
@Override
public void update(User user) {
String sql = "update user set name = ? ,gender= ? ,age = ? ,address = ?, qq = ? ,email = ? where id = ? ";
jdbcTemplate.update(sql,user.getName(),user.getGender(),user.getAge(),user.getAddress(),user.getQq(),user.getEmail(),user.getId());
}
@Override
public void deleteChecked(Map<String, String[]> map) {
Set<String> strings = map.keySet();
for (String string : strings) {
String[] value = map.get(string);
for (String s : value) {
String sql = "delete from user where id = ? ";
jdbcTemplate.update(sql,s);
}
}
}
@Override
public List<User> pagingUser(String n) {
int i = Integer.parseInt(n);
String sql = "select * from user limit ?,?";
List<User> users= jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class), 2 * (i - 1), 5);
return users;
}
@Override
public Integer findAllCount(Map<String, String[]> condition) {
// "select count(*) from user where 1=1 and name like '%李%' and address like '%北京%' limit 0,10"
String string = "select count(*) from user where 1=1 ";
StringBuilder stringBuilder = new StringBuilder(string);
Set<String> keys = condition.keySet();
List<Object> list = new ArrayList<>();
for (String key : keys) {
if("pageNow".equals(key) || "rows".equals(key)){
continue;
}
String[] values = condition.get(key);
for (String value : values) {
stringBuilder.append(" and "+key+" like ? ");
list.add("%"+value+"%");
}
}
String sql = stringBuilder.toString();
Integer integer = jdbcTemplate.queryForObject(sql, Integer.class, list.toArray());
// String sql = "select count(*) from user ";
// Integer integer = jdbcTemplate.queryForObject(sql, Integer.class);
// return integer;
return integer;
}
@Override
public List<User> getUserList(Integer start, Integer rows, Map<String, String[]> condition) {
// 在方法当中直接加断点 按下一步就能进到方法里
// 预期的到 select * from user where 1=1 and name like '%李%' and address like '%北京%' limit 0,10;
String string = "select * from user where 1=1 ";
StringBuilder stringBuilder = new StringBuilder(string);
List<Object> list = new ArrayList<>();
Set<String> set = condition.keySet();
//value 里是 %李% 北京 key是 name address email
for (String key : set) {
if("pageNow".equals(key) || "rows".equals(key)){
continue;
}
String[] values = condition.get(key);
for (String value : values) {
stringBuilder.append(" and "+key+" like ? ");
list.add("%"+value+"%");
}
}
stringBuilder.append(" limit ?,?");
list.add(start);
list.add(rows);
String sql = stringBuilder.toString();
List<User> query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class), list.toArray());
// String sql = "select * from user limit ?,?";
// List query = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class), start, rows);
return query;
}
}
2.1 add.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>添加用户title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/jquery-2.1.0.min.js">script>
<script src="js/bootstrap.min.js">script>
head>
<body>
<div class="container">
<center><h3>添加联系人页面h3>center>
<form action="${pageContext.request.contextPath}/servletAddUser" method="post">
<div class="form-group">
<label for="name">姓名:label>
<input type="text" class="form-control" id="name" name="name" placeholder="请输入姓名">
div>
<div class="form-group">
<label>性别:label>
<input type="radio" name="gender" value="男" checked="checked"/>男
<input type="radio" name="gender" value="女"/>女
div>
<div class="form-group">
<label for="age">年龄:label>
<input type="text" class="form-control" id="age" name="age" placeholder="请输入年龄">
div>
<div class="form-group">
<label for="address">籍贯:label>
<select name="address" class="form-control" id="address">
<option value="广东">广东option>
<option value="广西">广西option>
<option value="湖南">湖南option>
select>
div>
<div class="form-group">
<label for="qq">QQ:label>
<input type="text" class="form-control" name="qq" id="qq" placeholder="请输入QQ号码"/>
div>
<div class="form-group">
<label for="email">Email:label>
<input type="text" class="form-control" name="email" id="email" placeholder="请输入邮箱地址"/>
div>
<div class="form-group" style="text-align: center">
<input class="btn btn-primary" type="submit" value="提交" />
<input class="btn btn-default" type="reset" value="重置" onclick="resetUser()"/>
<input class="btn btn-default" type="button" value="返回" onclick="backUser()" />
div>
form>
div>
<script>
function backUser() {
location.href = "${pageContext.request.contextPath}/servletPaging"
}
function resetUser() {
var elementsByClassName = document.getElementsByClassName("common_event");
console.log(elementsByClassName);
for (var i = 0; i <elementsByClassName.length ; i++) {
// console.log(value);
//debugger;
elementsByClassName[i].value="";
//value = "";
// console.log(value)
}
}
function resetUser1() {
location.href = "${pageContext.request.contextPath}/servletResetUser";
}
script>
body>
html>
2.2 ServletAddUser.java
package web.servlet;
import domain.User;
import org.apache.commons.beanutils.BeanUtils;
import service.Impl.UserServiceImpl;
import service.UserService;
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;
@WebServlet(name = "ServletAddUser", urlPatterns = "/servletAddUser")
public class ServletAddUser extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
/*
* 1.jsp页面当中访问到服务器
* 2.服务器接收jsp发送过来请求 接收信息
* 3.封装成user对象
* 4.业务逻辑层和数据访问层 查询数据库
* 5.如果有返回一个全数据的user*/
// 1.获取add.jsp页面的数据
Map<String, String[]> map = request.getParameterMap();
//2.封装前端数据
User user = new User();
try {
BeanUtils.populate(user,map);
// BeanUtils.populate();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//3.创建业务逻辑层和数据访问层
UserService userService = new UserServiceImpl();
userService.add(user);
response.sendRedirect(request.getContextPath()+"/servletPaging");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
3.1 ServletFindUser.java代码 实现回显数据
package web.servlet;
import domain.User;
import service.Impl.UserServiceImpl;
import service.UserService;
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;
@WebServlet(name = "ServletFindUser", urlPatterns = "/servletFindUser")
public class ServletFindUser extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
/*通过jsp传进来的id 查询出来想修改的用户信息
* 把查询出来的信息 回显到jsp上*/
// 1.得到jsp页面是页面上的数据
String id = request.getParameter("id");
//2.查询到需要修改的用户信息
UserService userService = new UserServiceImpl();
User user = userService.findCharacter(id);
// 3.数据存放在request域当中 将这个数据转发给
request.setAttribute("user",user);
request.getRequestDispatcher("/update.jsp").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
3.2 ServletUpdateUser.java 更改用户信息
package web.servlet;
import domain.User;
import org.apache.commons.beanutils.BeanUtils;
import service.Impl.UserServiceImpl;
import service.UserService;
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;
@WebServlet(name = "ServletUpdateUser", urlPatterns = "/servletUpdateUser")
public class ServletUpdateUser extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
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();
}
UserService userService = new UserServiceImpl();
userService.update(user);
response.sendRedirect(request.getContextPath()+"/servletPaging");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
3.3 update.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html lang="zh-CN">
<head>
<%--<base href=""/>--%>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>修改用户title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/jquery-2.1.0.min.js">script>
<script src="js/bootstrap.min.js">script>
head>
<body>
<div class="container" style="width: 400px;">
<h3 style="text-align: center;">修改联系人h3>
<form action="${pageContext.request.contextPath}/servletUpdateUser?id=${user.id}" method="post">
<%--<input type="hidden" name="id" value="${name.id}">--%>
<div class="form-group">
<label for="name">姓名:label>
<input type="text" class="form-control common_event" id="name" name="name" readonly="readonly" value="${user.name}" />
div>
<div class="form-group">
<label>性别:label>
<c:if test="${empty user.gender}">
<input type="radio" name="gender" value="男" />男
<input type="radio" name="gender" value="女" />女
c:if>
<c:if test="${user.gender == '男'}">
<input type="radio" name="gender" value="男" checked/>男
<input type="radio" name="gender" value="女" />女
c:if>
<c:if test="${user.gender == '女'}">
<%--男--%>
<input type="radio" name="gender" value="男" />男
<input type="radio" name="gender" value="女" checked/>女
c:if>
div>
<div class="form-group">
<label for="age">年龄:label>
<input type="text" class="form-control common_event" id="age" name="age" value="${user.age}" />
div>
<div class="form-group">
<label for="address">籍贯:label>
<select name="address" class="form-control" id="address">
<c:if test="${empty user.address}">
<option >请选择option>
<option value="广东" >广东option>
<option value="广西">广西option>
<option value="湖南">湖南option>
c:if>
<c:if test="${user.address == '广东'}">
<option value="广东" selected>广东option>
<option value="广西">广西option>
<option value="湖南">湖南option>
c:if>
<c:if test="${user.address == '广西'}">
<option value="广东">广东option>
<option value="广西" selected>广西option>
<option value="湖南">湖南option>
c:if>
<c:if test="${user.address == '湖南'}">
<option value="广东">广东option>
<option value="广西">广西option>
<option value="湖南" selected>湖南option>
c:if>
select>
div>
<div class="form-group">
<label for="qq">QQ:label>
<input type="text" class="form-control common_event" name="qq" id="qq" value="${user.qq}" />
div>
<div class="form-group">
<label for="email">Email:label>
<input type="text" class="form-control common_event" id="email" name="email" value="${user.email}" />
div>
<div class="form-group" style="text-align: center">
<input class="btn btn-primary" type="submit" value="提交" />
<input class="btn btn-default" type="button" value="重置" onclick="resetUser()"/>
<input class="btn btn-default" type="button" value="返回" onclick="backUser()"/>
div>
form>
div>
<script>
function backUser() {
location.href = "${pageContext.request.contextPath}/servletPaging"
}
function resetUser() {
var elementsByClassName = document.getElementsByClassName("common_event");
console.log(elementsByClassName);
for (var i = 0; i <elementsByClassName.length ; i++) {
// console.log(value);
//debugger;
elementsByClassName[i].value="";
//value = "";
// console.log(value)
}
}
function resetUser1() {
location.href = "${pageContext.request.contextPath}/servletResetUser";
}
script>
body>
html>
4.1 ServletDelete.java 删除选中单个
package web.servlet;
import service.Impl.UserServiceImpl;
import service.UserService;
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;
@WebServlet(name = "ServletDelete", urlPatterns = "/servletDelete")
public class ServletDelete extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String id = request.getParameter("id");
UserService userService = new UserServiceImpl();
userService.delete(id);
response.sendRedirect(request.getContextPath()+"/servletPaging");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
4.2 删除选中多个
package web.servlet;
import org.apache.commons.beanutils.BeanUtils;
import service.Impl.UserServiceImpl;
import service.UserService;
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.Map;
@WebServlet(name = "ServletDeleteChecked", urlPatterns = "/servletDeleteChecked")
public class ServletDeleteChecked extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
/*删除选中
* 1.多选框值 确定选中的id值 多选框的name为hobby value为${user.id}
* 2.创建deleteChecked() 将获取到的id集合作为参数
* 3.执行sql语句 删除相应的信息
* 4.重定向到UserListServlet*/
Map<String, String[]> map = request.getParameterMap();
UserService userService = new UserServiceImpl();
userService.deleteChecked(map);
response.sendRedirect(request.getContextPath()+"/servletPaging");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
5.1 ServletPaging.java
package web.servlet;
import domain.PageBean;
import domain.User;
import service.Impl.UserServiceImpl;
import service.UserService;
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;
import java.util.Map;
@WebServlet(name = "ServletPaging", urlPatterns = "/servletPaging")
public class ServletPaging extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
// 接收参数
String pageNow = request.getParameter("pageNow");
String rows = request.getParameter("rows");
Map<String, String[]> condition = request.getParameterMap();
if(pageNow==null || "".equals(pageNow)){
pageNow = "1";
}
if(rows == null || "".equals(rows)){
rows= "10";
}
// 调用方法 获取PageBean
UserService userService = new UserServiceImpl();
// List users = userService.pagingUser(pageNow);
PageBean<User> pageBean = userService.getPageBean(pageNow,rows,condition);
System.out.println(pageBean);
// PageBean放到域中
// request.setAttribute("users",users);
request.setAttribute("pageBean",pageBean);
request.setAttribute("condition",condition);
request.getRequestDispatcher("/list.jsp").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
6.1 list.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>用户信息管理系统title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/jquery-2.1.0.min.js">script>
<script src="js/bootstrap.min.js">script>
<style type="text/css">
td, th {
text-align: center;
}
style>
head>
<body>
<div class="container">
<h3 style="text-align: center"><a href="${pageContext.request.contextPath}/servletPaging">用户信息列表a>h3>
<div style="float: left">
<form class="form-inline" action="${pageContext.request.contextPath}/servletPaging">
<div class="form-group">
<label for="exampleInputName2">姓名label>
<input type="text" class="form-control" value="${condition.name[0]}" name="name" id="exampleInputName2">
div>
<div class="form-group">
<label for="exampleInputName2">籍贯label>
<input type="text" class="form-control" name="address" value="${condition.address[0]}" id="exampleInputAddress2">
div>
<div class="form-group">
<label for="exampleInputEmail2">邮箱label>
<input type="text" class="form-control" name="email" value="${condition.email[0]}" id="exampleInputEmail2">
div>
<button type="submit" class="btn btn-default">查询button>
<button type="submit" class="btn btn-default">删除button>
form>
div>
<div class="" style="float: right">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/add.jsp">添加联系人a>
<a class="btn btn-primary" href="javascript:deleteChecked()">删除选中a>
<%--没有表单submit控件 那么就让form表单绑定 onsubmit事件--
form标签.onsubmit()
--%>
div>
<table border="1" class="table table-bordered table-hover">
<tr class="success">
<th><input type="checkbox" name="all" onclick="selectAll()">th>
<th>编号th>
<th>姓名th>
<th>性别th>
<th>年龄th>
<th>籍贯th>
<th>QQth>
<th>邮箱th>
<th>操作th>
tr>
<c:forEach items="${pageBean.list}" var="user" varStatus="s">
<tr>
<c:if test="${user.id == '1' }">
<td>td>
c:if>
<c:if test="${user.id != '1' }">
<td><input type="checkbox" name="deleteUser" value="${user.id}" >td>
c:if>
<td>${s.count}td>
<td>${user.name}td>
<td>${user.gender}td>
<td>${user.age}td>
<td>${user.address}td>
<td>${user.qq}td>
<td>${user.email}td>
<td><c:if test="${user.id == '1' }">
<a class="btn btn-default btn-sm disabled"
href="${pageContext.request.contextPath}/servletFindUser?id=${user.id}">修改a>
<a
id="deleteUser" class="btn btn-default btn-sm disabled"
href="javascript:deleteUser(${user.id})">删除a>td>
c:if>
<c:if test="${user.id != '1'}">
<a class="btn btn-default btn-sm"
href="${pageContext.request.contextPath}/servletFindUser?id=${user.id}">修改a>
<a
id="deleteUser" class="btn btn-default btn-sm"
href="javascript:deleteUser('${user.id}')">删除a>td>
c:if>
tr>
c:forEach>
table>
<nav>
<ul class="pagination">
<c:if test="${pageBean.pageNow == 1 }">
<li class="disabled">
<a aria-label="Previous">
<span aria-hidden="true">«span>
a>
li>
c:if>
<c:if test="${pageBean.pageNow != 1 }">
<li class="">
<a href="${pageContext.request.contextPath}/servletPaging?name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}&pageNow=${pageBean.pageNow-1}&rows=${pageBean.rows}" aria-label="Previous">
<span aria-hidden="true">«span>
a>
li>
c:if>
<c:forEach begin="1" end="${pageBean.pageCount}" var="i" step="1" varStatus="s">
<%--循环遍历出来的 起始时候就显示出来多少个分页标签 s.count--%>
<c:if test="${pageBean.pageNow == i}">
<li class="active"><a href="${pageContext.request.contextPath}/servletPaging?name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}&pageNow=${i}&rows=${pageBean.rows}">${i}a>li>
c:if>
<c:if test="${pageBean.pageNow != i}">
<li class=""><a href="${pageContext.request.contextPath}/servletPaging?name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}&pageNow=${i}&rows=${pageBean.rows}">${i}a>li>
c:if>
c:forEach>
<%-- <c:forEach items="pageCount" var="user" varStatus="s">
<li><a href="${pageContext.request.contextPath}/servletPaging?pageNow=1&rows=5">a>li>
c:forEach>--%>
<%--<li><a href="${pageContext.request.contextPath}/servletPaging?n=1">1a>li>--%>
<c:if test="${pageBean.pageNow == pageBean.pageCount}">
<li class="disabled">
<a aria-label="Previous">
<span aria-hidden="true">»span>
a>
li>
c:if>
<c:if test="${pageBean.pageNow != pageBean.pageCount}">
<li class="">
<a href="${pageContext.request.contextPath}/servletPaging?name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}&pageNow=${pageBean.pageNow+1}&rows=${pageBean.rows}" aria-label="Previous">
<span aria-hidden="true">»span>
a>
li>
c:if>
<li style="font-size: 20px">共${pageBean.dataCount}条记录,共${pageBean.pageCount}页li>
ul>
nav>
div>
<script>
function deleteUser(id,ev) {
console.log(ev)
// var deleteUser = document.getElementById("deleteUser");
if (confirm("确定要删除嘛?")) {
// if("1" == id ){
// deleteUser.className = "btn btn-default btn-sm disabled";
// }
// if("24" == id ){
// ev.href = "javascript:void(0)";
// }
location.href = "${pageContext.request.contextPath}/servletDelete?id=" + id;
}
}
function selectAll() {
var elementsByName = document.getElementsByName("deleteUser");
var all = document.getElementsByName("all")[0];
for (var i = 0; i < elementsByName.length; i++) {
elementsByName[i].checked = all.checked;
}
}
function deleteChecked() {
var elementsByName = document.getElementsByName("deleteUser");
var s = "";
for (var i = 0; i < elementsByName.length; i++) {
if (elementsByName[i].checked == true) {
// if(i = elementsByName.length-1){
// s = s + elementsByName[i].name + "=" + elementsByName[i].value;
// }
s = s + elementsByName[i].name + "=" + elementsByName[i].value + "&";
}
}
console.log(s)
s = s.substring(0, s.length - 1);
console.log(s)
if (confirm("确定删除这些条目嘛?")) {
location.href = "${pageContext.request.contextPath}/servletDeleteChecked?" + s;
}
}
script>
body>
html>
6.2 复杂添加查询拥有分页功能和分页查询写在一起。参见ServletPaging.java
7.1 index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="zh-CN">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>首页title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/jquery-2.1.0.min.js">script>
<script src="js/bootstrap.min.js">script>
<script type="text/javascript">
script>
head>
<body>
<div align="center">
<div>${sessionScope.user.name}欢迎你div>
<a
href="${pageContext.request.contextPath}/servletPaging" style="text-decoration:none;font-size:33px">查询所有用户信息
a>
div>
body>
html>
第一次发文。
只是简练的附上了代码和项目结构,因为对于不同的人拥有不同的问题,对于内容细节没有进行过多解释。望大家见谅。随后会把解释慢慢补上。
一入此坑深似海,无法自拔,与君共勉。
爱你们哦(づ ̄3 ̄)づ╭❤~。