需求:
1 前端界面
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<a href="/user?method=list">查询所有的用户</a><br/>
<a href="/user?method=findByPage&curPage=1">分页查询用户</a><br/>
</body>
</html>
list.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<!-- 网页使用的语言 -->
<html lang="zh-CN">
<head>
<!-- 指定字符集 -->
<meta charset="utf-8">
<!-- 使用Edge最新的浏览器的渲染方式 -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- viewport视口:网页可以根据设置的宽度自动进行适配,在浏览器的内部虚拟一个容器,容器的宽度与设备的宽度相同。
width: 默认宽度与设备的宽度相同
initial-scale: 初始的缩放比,为1:1 -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<title>Bootstrap模板</title>
<!-- 1. 导入CSS的全局样式 -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- 2. jQuery导入,建议使用1.9以上的版本 -->
<script src="js/jquery-2.1.0.min.js"></script>
<!-- 3. 导入bootstrap的js文件 -->
<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">显示所有用户</h3>
<table border="1" class="table table-bordered table-hover">
<tr class="success">
<th>编号</th>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
<th>籍贯</th>
<th>QQ</th>
<th>邮箱</th>
<th>操作</th>
</tr>
<c:forEach items="${users}" var="user">
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.sex}</td>
<td>${user.age}</td>
<td>${user.address}</td>
<td>${user.qq}</td>
<td>${user.email}</td>
<td><a class="btn btn-default btn-sm" href="/user?method=update&id=${user.id}">修改</a>
<a class="btn btn-default btn-sm" onclick="f(${user.id})">删除</a></td>
</tr>
</c:forEach>
<tr>
<td colspan="8" align="center"><a class="btn btn-primary"
href="/add.jsp">添加用户</a></td>
</tr>
</table>
</div>
</body>
<
<script>
function f(id) {
var flag = confirm("确定删除此用户吗");
if (flag) {
location.href="/user?method=delete&id="+id;
}
}
</script>
</html>
add.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!-- HTML5文档-->
<!DOCTYPE html>
<!-- 网页使用的语言 -->
<html lang="zh-CN">
<head>
<!-- 指定字符集 -->
<meta charset="utf-8">
<!-- 使用Edge最新的浏览器的渲染方式 -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- viewport视口:网页可以根据设置的宽度自动进行适配,在浏览器的内部虚拟一个容器,容器的宽度与设备的宽度相同。
width: 默认宽度与设备的宽度相同
initial-scale: 初始的缩放比,为1:1 -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<title>添加用户</title>
<!-- 1. 导入CSS的全局样式 -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- 2. jQuery导入,建议使用1.9以上的版本 -->
<script src="js/jquery-2.1.0.min.js"></script>
<!-- 3. 导入bootstrap的js文件 -->
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<center><h3>添加用户页面</h3></center>
<form action="/user?method=add" 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="sex" value="男" checked="checked"/>男
<input type="radio" name="sex" 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="jiguan">
<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" placeholder="请输入QQ号码"/>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" name="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="f()"/>
<input class="btn btn-default" type="button" value="返回" onclick="f2()"/>
</div>
</form>
</div>
</body>
</html>
<script>
function f() {
location.href="/add.jsp";
}
function f2() {
history.back();
}
</script>
update.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE html>
<!-- 网页使用的语言 -->
<html lang="zh-CN">
<head>
<base href="<%=basePath%>"/>
<!-- 指定字符集 -->
<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="/user?method=update2&id=${user.id}" method="post">
<div class="form-group">
<label for="name">姓名:</label>
<input type="text" class="form-control" id="name" name="name" placeholder="请输入姓名" value="${user.name}"/>
</div>
<div class="form-group">
<label>性别:</label>
<c:if test="${user.sex=='男'}">
<input type="radio" name="sex" value="男" checked/>男
<input type="radio" name="sex" value="女"/>女
</c:if>
<c:if test="${user.sex=='女'}">
<input type="radio" name="sex" value="男"/>男
<input type="radio" name="sex" value="女" checked/>女
</c:if>
</div>
<div class="form-group">
<label for="age">年龄:</label>
<input type="text" class="form-control" id="age" name="age" placeholder="请输入年龄" value="${user.age}"/>
</div>
<div class="form-group">
<label for="address">籍贯:</label>
<c:if test="${user.address=='广东'}">
<select name="address" class="form-control">
<option value="广东" selected>广东</option>
<option value="广西">广西</option>
<option value="湖南">湖南</option>
</select>
</c:if>
<c:if test="${user.address=='广西'}">
<select name="address" class="form-control">
<option value="广东">广东</option>
<option value="广西" selected>广西</option>
<option value="湖南">湖南</option>
</select>
</c:if>
<c:if test="${user.address=='湖南'}">
<select name="address" class="form-control">
<option value="广东">广东</option>
<option value="广西">广西</option>
<option value="湖南" selected>湖南</option>
</select>
</c:if>
</div>
<div class="form-group">
<label for="qq">QQ:</label>
<input type="text" class="form-control" name="qq" placeholder="请输入QQ号码" value="${user.qq}"/>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" name="email" placeholder="请输入邮箱地址" 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="reset" value="重置" onclick="f(this)"/>
<input class="btn btn-default" type="button" value="返回" onclick="f2()"/>
</div>
</form>
</div>
</body>
</html>
<script>
function f(obj) {
obj.action="/update.jsp?time="+new Date().getMilliseconds();
}
function f2() {
history.back()
}
</script>
这里也引用了各种别人写好的包
2 栅包

3 工具包utils
package com.zl.utils; import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource; import java.io.InputStream; import java.sql.*; import java.util.Properties; public class JDBCUtils { //修改工具类,得到连接方法,来自连接池 private static DataSource dataSource;//null public static DataSource getDataSource() { return dataSource; } static { try { //读取配置文件信息,类加载器,读取配置文件src文件夹下的文件这个资源作为流 Properties properties = new Properties(); InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"); properties.load(is); dataSource = DruidDataSourceFactory.createDataSource(properties); } catch (Exception e) { e.printStackTrace(); } } public static final Connection getConnection(){ try { Connection connection = dataSource.getConnection(); return connection; } catch (Exception e) { e.printStackTrace(); } return null; } public static final void close(ResultSet resultSet, Statement statement, Connection connection) { if (resultSet!=null){ try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } if (statement!=null){ try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection!=null){ try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
4 用户包bean
package com.zl.bean; import java.io.Serializable; public class User implements Serializable { private int id; private String name; private String sex; private int age; private String address; private String qq; private String email; public User() { } public User(int id, String name, String sex, int age, String address, String qq, String email) { this.id = id; this.name = name; this.sex = sex; this.age = age; this.address = address; this.qq = qq; this.email = email; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getQq() { return qq; } public void setQq(String qq) { this.qq = qq; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "Contact{" + "id=" + id + ", name='" + name + '\'' + ", sex='" + sex + '\'' + ", age=" + age + ", address='" + address + '\'' + ", qq='" + qq + '\'' + ", email='" + email + '\'' + '}'; } }
package com.zl.bean; import java.io.Serializable; import java.util.List; public class PageBean<T> implements Serializable { private List<T> list; //每页所有数据 private int curSize; //每页(当前页)条数 private int curPage; //当前页码 private int sumPage; //最大页码 private int count; //总记录条数 public PageBean() { } public PageBean(List<T> list, int curSize, int curPage, int sumPage, int count) { this.list = list; this.curSize = curSize; this.curPage = curPage; this.sumPage = sumPage; this.count = count; } public List<T> getList() { return list; } public void setList(List<T> list) { this.list = list; } public int getCurSize() { return curSize; } public void setCurSize(int curSize) { this.curSize = curSize; } public int getCurPage() { return curPage; } public void setCurPage(int curPage) { this.curPage = curPage; } public int getSumPage() { return sumPage; } public void setSumPage(int sumPage) { this.sumPage = sumPage; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } @Override public String toString() { return "PageBean{" + "list=" + list + ", curSize=" + curSize + ", curPage=" + curPage + ", sumPage=" + sumPage + ", count=" + count + '}'; } }
5 配置文件
这里用的是druid.properties
方法
用三层架构解决:高内聚,低耦合。面向接口
web层,servlet控制层
package com.zl.web;
import com.zl.bean.PageBean;
import com.zl.bean.User;
import com.zl.service.UserService;
import com.zl.service.impl.UserServiceImpl;
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.Method;
import java.util.List;
import java.util.Map;
@WebServlet("/user")
public class UserServlet extends HttpServlet {
UserService userService = new UserServiceImpl();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String methodname = request.getParameter("method");
Class<? extends UserServlet> c = this.getClass();
try {
Method method = c.getDeclaredMethod(methodname, HttpServletRequest.class, HttpServletResponse.class);
method.setAccessible(true);
method.invoke(this, request, response); //this.method(args)
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
List<User> users = userService.findAll();
request.setAttribute("users", users);
request.getRequestDispatcher("/list.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
System.out.println("查询异常!");
}
}
protected void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String, String[]> map = request.getParameterMap();
User user = new User();
try {
BeanUtils.populate(user, map);
int count = userService.addUser(user);
if (count > 0) {
list(request, response);
} else {
System.out.println("增加失败!");
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("增加异常!");
}
}
protected void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
try {
int count = userService.deleteUser(id);
if (count > 0) {
list(request, response);
} else {
System.out.println("删除失败!");
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("删除异常!");
}
}
protected void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
try {
User user = userService.updateGetUser(id);
if (user != null) {
request.setAttribute("user", user);
request.getRequestDispatcher("/update.jsp").forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected void update2(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Map<String, String[]> map = request.getParameterMap();
User user = new User();
try {
BeanUtils.populate(user, map);
int count = userService.updateUser(user);
if (count > 0) {
list(request, response);
} else {
System.out.println("修改失败!");
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("修改异常!");
}
}
protected void findByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int curPage = Integer.parseInt(request.getParameter("curPage"));
try {
PageBean<User> pageBean = userService.findPageBean(curPage);
request.setAttribute("pageBean", pageBean);
request.getRequestDispatcher("/list_page.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
service层,服务层,业务层
package com.zl.service; import com.zl.bean.PageBean; import com.zl.bean.User; import java.util.List; public interface UserService { List<User> findAll() throws Exception; int addUser(User user) throws Exception; int deleteUser(int id) throws Exception; User updateGetUser(int id) throws Exception; int updateUser(User user) throws Exception; PageBean<User> findPageBean(int curPage) throws Exception; }
package com.zl.service.impl;
import com.zl.bean.PageBean;
import com.zl.bean.User;
import com.zl.dao.UserDao;
import com.zl.dao.impl.UserDaoImpl;
import com.zl.service.UserService;
import java.util.List;
public class UserServiceImpl implements UserService {
UserDao userDao = new UserDaoImpl();
@Override
public List<User> findAll() throws Exception {
List<User> users = userDao.findAll();
return users;
}
@Override
public int addUser(User user) throws Exception {
int count = userDao.addUser(user);
return count;
}
@Override
public int deleteUser(int id) throws Exception {
int count = userDao.deleteUser(id);
return count;
}
@Override
public User updateGetUser(int id) throws Exception {
User user = userDao.updateGetUser(id);
return user;
}
@Override
public int updateUser(User user) throws Exception {
int count = userDao.updateUser(user);
return count;
}
@Override
public PageBean<User> findPageBean(int curPage) throws Exception {
PageBean<User> pageBean = new PageBean<User>();
pageBean.setCurPage(curPage);
int b = 3;
pageBean.setCurSize(b);
int count = userDao.findCount();
pageBean.setCount(count);
int sumPage = (count % b == 0) ? (count / b) : (count / b + 1);
pageBean.setSumPage(sumPage);
List<User> users = userDao.findListLimit((curPage - 1) * b, b);
pageBean.setList(users);
return pageBean;
}
}
dao层,数据访问层,持久层
package com.zl.dao; import com.zl.bean.User; import java.util.List; public interface UserDao { List<User> findAll() throws Exception; int addUser(User user) throws Exception; int deleteUser(int id) throws Exception; User updateGetUser(int id) throws Exception; int updateUser(User user) throws Exception; int findCount() throws Exception; List<User> findListLimit(int a, int b) throws Exception; }
package com.zl.dao.impl;
import com.zl.bean.User;
import com.zl.dao.UserDao;
import com.zl.utils.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
public class UserDaoImpl implements UserDao {
JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
@Override
public List<User> findAll() throws Exception {
List<User> users = jdbcTemplate.query("select * from user", new BeanPropertyRowMapper<>(User.class));
return users;
}
@Override
public int addUser(User user) throws Exception {
Object[] args = {user.getId(), user.getName(), user.getSex(), user.getAge(), user.getAddress(), user.getQq(), user.getEmail()};
int count = jdbcTemplate.update("insert into user values (?,?,?,?,?,?,?)", args);
return count;
}
@Override
public int deleteUser(int id) throws Exception {
int count = jdbcTemplate.update("delete from user where id=?", id);
return count;
}
@Override
public User updateGetUser(int id) throws Exception {
User user = jdbcTemplate.queryForObject("select * from user where id=?", new BeanPropertyRowMapper<>(User.class), id);
return user;
}
@Override
public int updateUser(User user) throws Exception {
Object[] args = {user.getName(), user.getSex(), user.getAge(), user.getAddress(), user.getQq(), user.getEmail(), user.getId()};
int count = jdbcTemplate.update("update user set name=?,sex=?,age=?,address=?,qq=?,email=? where id=?", args);
return count;
}
@Override
public int findCount() throws Exception {
//query?
Long count = jdbcTemplate.queryForObject("select count(*) from user", Long.class);
return count.intValue();
}
@Override
public List<User> findListLimit(int a, int b) throws Exception{
List<User> users = jdbcTemplate.query("select * from user limit ?,?",
new BeanPropertyRowMapper<>(User.class), a, b);
return users;
}
}
过滤器
package com.zl.filter; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; //拦截类型,这里设置重定向和内部转发 @WebFilter(value = "/user",dispatcherTypes = {DispatcherType.REQUEST,DispatcherType.FORWARD}) public class UserFilter implements Filter { //在开启服务器tomcat时执行,在启动servlet之前 public void init(FilterConfig config) throws ServletException { } //每次访问服务器前都执行 public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { //强转两个参数 HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; //设置编码类型 request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); chain.doFilter(request, response); } //关闭服务器时摧毁 public void destroy() { } }
浙公网安备 33010602011771号