效果原型图
1. 添加
2. 删除
3. 查询
4. 修改
5. 条件查询
数据层的搭建
public class UserDaoImpl implements UserDao {
private JdbcTemplate jt = new JdbcTemplate(JdbcUtils.getDataSource());
@Override
public List<User> findAll() {
String sql = "select * from user";
List<User> users = jt.query(sql, new BeanPropertyRowMapper<>(User.class));
return users;
}
@Override
public User findById(int id) {
String sql = "select * from user where id = ?";
User user = jt.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), id);
return user;
}
@Override
public boolean add(User user) {
String sql = "insert into user values(null,?,?,?,?,?,?)";
int index = jt.update(sql, user.getName(), user.getGender(), user.getAge(), user.getAddress(), user.getQq(), user.getEmail());
if(index!=0){
return true;
}else{
return false;
}
}
@Override
public boolean deleteById(int id) {
String sql = "delete from user where id = ?";
int index = jt.update(sql, id);
if(index!=0){
return true;
}
return false;
}
@Override
public boolean updateUser(User user) {
String sql = "update user set name = ? ,gender = ?,age = ?,address = ?,qq = ?,email=? where id = ?";
int index = jt.update(sql, user.getName(), user.getGender(), user.getAge(), user.getAddress(), user.getQq(), user.getEmail(),user.getId());
if(index!=0){
return true;
}
return false;
}
@Override
public Integer totalCount(Map<String,String[]> conditions) {
String sql = "select count(*) from user where 1 = 1 ";
Set<String> sets = conditions.keySet();
ArrayList<Object> list = new ArrayList<>();
StringBuilder sb = new StringBuilder(sql);
for (String key : sets) {
if("current".equals(key) || "rows".equals(key)){
continue;
}
String value = conditions.get(key)[0];
if(!"".equals(value) && value!=null){
sb.append(" and "+key+" like ? ");
list.add("%"+value+"%");
}
}
System.out.println(sb.toString());
System.out.println(list);
Integer count = jt.queryForObject(sb.toString(), Integer.class ,list.toArray());
return count;
}
@Override
public List<User> findAll(Integer start, Integer end,Map<String,String[]> conditions) {
String sql = "select * from user where 1 = 1 ";
Set<String> sets = conditions.keySet();
ArrayList<Object> list = new ArrayList<>();
StringBuilder sb = new StringBuilder(sql);
for (String key : sets) {
if("current".equals(key) || "rows".equals(key)){
continue;
}
String value = conditions.get(key)[0];
if(!"".equals(value) && value!=null){
sb.append(" and "+key+" like ? ");
list.add("%"+value+"%");
}
}
sb.append("limit ? ,?");
list.add(start);
list.add(end);
System.out.println(sb.toString());
System.out.println(list);
List<User> lists = jt.query(sb.toString(), new BeanPropertyRowMapper<>(User.class), list.toArray());
return lists;
}
@Override
public UserName login(String userName,String password) {
try {
String sql = "select * from username where name = ? and password = ?";
UserName user = jt.queryForObject(sql, new BeanPropertyRowMapper<>(UserName.class), userName,password);
return user;
} catch (DataAccessException e) {
e.printStackTrace();
return null;
}
}
}
需要注意一下,一般我们在搭建数据层的时候,一般需要定义一个接口,然后实现接口中的方法,这样可以避免我们开发过程中遇到的一些问题,规范我们的开发
public class UserServiceImpl implements UserService {
private UserDao userDao = new UserDaoImpl();
@Override
public List<User> findAll() {
return userDao.findAll();
}
@Override
public User findById(int id) {
return userDao.findById(id);
}
@Override
public boolean add(User user) {
return userDao.add(user);
}
@Override
public boolean deleteById(int id) {
return userDao.deleteById(id);
}
@Override
public void deleteByIds(String[] ids) {
for (String id : ids) {
userDao.deleteById(Integer.valueOf(id));
}
// return false;
}
@Override
public boolean updateUser(User user) {
return userDao.updateUser(user);
}
@Override
public Page<User> findAll(Integer current, Integer rows, Map<String,String[]> conditions) {
Page<User> page = new Page<>();
// 总数量
Integer totalCount = userDao.totalCount(conditions);
page.setTotalCount(totalCount);
// 总页码
Integer totalRows = totalCount%rows==0?totalCount/rows:totalCount/rows+1;
page.setTotalRows(totalRows);
if(current<=1){
current=1;
}
if(current>=totalRows){
current=totalRows;
}
// 当前页码的数据
Integer start = (current-1)*rows;
List<User> list = userDao.findAll(start, rows,conditions);
page.setList(list);
// 当前页码
page.setCurrent(current);
// 每页的数量
page.setRows(rows);
return page;
}
@Override
public UserName login(String userName,String password) {
return userDao.login(userName,password);
}
}
此时让业务层实现数据的层的方法,然后将数据传输给表现层中,由表现层将数据传输给前端页面
1. 添加
@WebServlet("/addServlet")
public class UserAddServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 编码方式
req.setCharacterEncoding("utf-8");
UserService service = new UserServiceImpl();
// 获取数据
Map<String, String[]> map = req.getParameterMap();
User user = new User();
try {
BeanUtils.populate(user, map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
// System.out.println(user);
boolean flag = service.add(user);
req.setAttribute("msg", flag);
req.getRequestDispatcher("/listServlet").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
2. 删除
2.1 根据Id删除
@WebServlet("/deleteServlet")
public class UserDeleteServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String id = req.getParameter("id");
UserService service = new UserServiceImpl();
service.deleteById(Integer.valueOf(id));
req.getRequestDispatcher("/listServlet").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
2.2 根据 ids(id数组)删除
@WebServlet("/deleteByIdsServlet")
public class UserDeleteByIdsServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String[] ids = req.getParameterValues("uid");
UserService service = new UserServiceImpl();
service.deleteByIds(ids);
req.getRequestDispatcher("/listServlet").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
3. 查询
@WebServlet("/listServlet")
public class UserListServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 设置编码方式
req.setCharacterEncoding("utf-8");
UserService service = new UserServiceImpl();
String current = req.getParameter("current");
String rows = req.getParameter("rows");
if("".equals(current)||current==null){
current="1";
}
if("".equals(rows)|| rows==null){
rows="5";
}
Map<String,String[]> conditions = new HashMap<>();
Page<User> pg = service.findAll(Integer.valueOf(current), Integer.valueOf(rows), conditions);
req.setAttribute("pg",pg);
// System.out.println(list);
req.getRequestDispatcher("/list.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
}
4. 修改
@WebServlet("/updateServlet")
public class UserUpdateServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
Map<String, String[]> map = req.getParameterMap();
User u = new User();
try {
BeanUtils.populate(u,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
UserService service = new UserServiceImpl();
boolean flag = service.updateUser(u);
// System.out.println(u+";;"+flag);
req.getRequestDispatcher("/listServlet").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
注意:这个地方的修改是需要先根据id值来查询出来数据,然后将数据传递过来,才开始进行删除
@WebServlet("/findById")
public class UserFindById extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String id = req.getParameter("id");
System.out.println("id:"+id);
UserService service = new UserServiceImpl();
User user = service.findById(Integer.valueOf(id));
req.setAttribute("user",user);
req.getRequestDispatcher("/update.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
5. 条件查询
@WebServlet("/findAllByCondition")
public class UserFindAllByCondition extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
UserService service = new UserServiceImpl();
String current = req.getParameter("current");
String rows = req.getParameter("rows");
if("".equals(current)||current==null){
current="1";
}
if("".equals(rows)|| rows==null){
rows="5";
}
User u = new User();
Map<String, String[]> conditions = req.getParameterMap();
System.out.println(conditions.toString());
req.setAttribute("conditions",conditions);
Page<User> pg = service.findAll(Integer.valueOf(current), Integer.valueOf(rows),conditions);
req.setAttribute("pg",pg);
System.out.println(pg);
req.getRequestDispatcher("/list.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
当然,如果实现登录页面,也需要定义一个HttpServlet 的实现类
6. 登录
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
// 获取验证码
String verifycode = req.getParameter("verifycode");
HttpSession session = req.getSession();
String check_code = (String) session.getAttribute("CHECK_CODE");
session.removeAttribute("CHECK_CODE");
if(!check_code.equalsIgnoreCase(verifycode)){
req.setAttribute("msg","验证码有误,请重新输入");
req.getRequestDispatcher("/login.jsp").forward(req,resp);
return;
}
String username = req.getParameter("name");
String password = req.getParameter("password");
UserService service = new UserServiceImpl();
UserName userName = service.login(username, password);
if(userName!=null){
req.setAttribute("msg","登录成功");
HttpSession s = req.getSession();
s.setAttribute("userName",userName);
// req.getRequestDispatcher("/index.jsp").forward(req,resp);
resp.sendRedirect(req.getContextPath()+"/index.jsp");
}else{
req.setAttribute("msg","账户和密码有误");
req.getRequestDispatcher("/login.jsp").forward(req,resp);
return;
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req,resp);
}
}
有了登录当然也需要一个能够生成随机验证码的HttpServlet的类
验证码的生成
@WebServlet("/checkCode")
public class CheckCode extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//服务器通知浏览器不要缓存
resp.setHeader("pragma","no-cache");
resp.setHeader("cache-control","no-cache");
resp.setHeader("expires","0");
Integer width = 80;
Integer height = 30;
// 创建一个图像缓存区
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
// 获取一个画笔
Graphics graphics = image.getGraphics();
// 画出一个底面
graphics.setColor(getColor());
// 填充页面
graphics.fillRect(0,0,width,height);
// 设计颜色
graphics.setColor(getColor());
// 设置字体
graphics.setFont(new Font("黑体",Font.BOLD,24));
// 添加到图像缓存区中
String code = getCode(4);
HttpSession session = req.getSession();
session.setAttribute("CHECK_CODE",code);
graphics.drawString(code,15,20);
graphics.setColor(getColor());
// 设计干扰现
RandomLine(graphics,width,height);
ImageIO.write(image,"png",resp.getOutputStream());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
// 随机干扰线
public static void RandomLine(Graphics graphics,int width,int height){
Random r = new Random();
int x1 = r.nextInt(width);
int y1 = r.nextInt(height);
int x2 = r.nextInt(width);
int y2 = r.nextInt(height);
graphics.drawLine(x1,y1,x2,y2);
}
// 随机一个颜色
public static Color getColor(){
Random r = new Random();
int rr = r.nextInt(256);
int g = r.nextInt(256);
int b = r.nextInt(256);
return new Color(rr,g,b);
}
// 随机验证码
public static String getCode(int n){
ArrayList<Character> list = new ArrayList<>();
for (int i = 0; i < 26; i++) {
list.add((char)('a'+i));
list.add((char)('A'+i));
}
for (int i = 0; i < 10; i++) {
list.add((char)('0'+i));
}
// System.out.println(list.toString());
StringBuilder sb = new StringBuilder();
Random r = new Random();
for (int i = 0; i < n; i++) {
int index = r.nextInt(list.size());
Character ch = list.get(index);
sb.append(ch);
}
return sb.toString();
}
}
如果不经过拦截,那么你的资源不是就可以被随便访问了吗,所以,我需要我们在定义一个过滤器用来拦截那些需要登录才能获取的资源
拦截器
@WebFilter("/*")
public class UserFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) servletRequest;
String uri = req.getRequestURI();
if(uri.contains("/login.jsp") || uri.contains("/loginServlet") || uri.contains("/css/") || uri.contains("/js/") || uri.contains("/fonts/") || uri.contains("/checkCode") ){
filterChain.doFilter(servletRequest, servletResponse);
}else{
UserName userName = (UserName) req.getSession().getAttribute("userName");
if(userName!=null){
filterChain.doFilter(servletRequest, servletResponse);
}else{
req.setAttribute("msg","你尚未登录,请先去登录");
req.getRequestDispatcher("/login.jsp").forward(req, servletResponse);
}
}
}
@Override
public void destroy() {
}
}
过滤敏感字符
@WebFilter("/*")
public class WorldFilter implements Filter {
private ArrayList<String> list = new ArrayList<>();
@Override
public void init(FilterConfig filterConfig) throws ServletException {
InputStream is = WorldFilter.class.getClassLoader().getResourceAsStream("敏感词汇.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
try {
String line = null;
while ((line = br.readLine()) != null) {
list.add(line);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(list);
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//增强方法
ServletRequest Proxy_req = (ServletRequest) Proxy.newProxyInstance(servletRequest.getClass().getClassLoader(), servletRequest.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (method.getName().equals("getParameter")) {
String value = (String) method.invoke(servletRequest, args);
if (value != null) {
for (String str : list) {
if (value.contains(str)) {
value = value.replaceAll(str, "***");
}
}
}
return value;
} else if ("getParameterMap".equals(method.getName())) {
// 需要重新创建一个Map,否则会出现java.lang.IllegalStateException: 不允许修改锁定的参数映射
Map<String, String[]> map = new HashMap<>( (Map<String, String[]>) method.invoke(servletRequest, args));
String[] newStr = new String[1];
Set<String> sets = map.keySet();
if (sets != null) {
for (String key : sets) {
String value = map.get(key)[0];
for (String str : list) {
if (value.contains(str)) {
value = value.replaceAll(str, "***");
newStr[0] = value;
map.put(key,newStr);
}
}
}
}
return map;
} else if ("getParameterValues".equals(method.getName())) {
String[] values = (String[]) method.invoke(servletRequest, args);
if (values != null) {
for(int i =0 ;i<values.length;i++) {
String value = values[i];
for (String str : list) {
if (value.contains(str)) {
value = value.replaceAll(str, "***");
values[i] = value;
}
}
}
}
return values;
}
return method.invoke(servletRequest, args);
}
});
// 放行
filterChain.doFilter(Proxy_req,servletResponse);
}
@Override
public void destroy() {
}
}
除了这些,当然不能少了我们的JavaBean类
// User类
public class User {
private Integer id;
private String name;
private String gender;
private Integer age;
private String address;
private String qq;
private String email;
public User(){}
public User(Integer id, String name, String gender, Integer age, String address, String qq, String email) {
this.id = id;
this.name = name;
this.gender = gender;
this.age = age;
this.address = address;
this.qq = qq;
this.email = email;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Integer getAge() {
return age;
}
public void setAge(Integer 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 "User{" +
"id=" + id +
", name='" + name + '\'' +
", gender='" + gender + '\'' +
", age=" + age +
", address='" + address + '\'' +
", qq='" + qq + '\'' +
", email='" + email + '\'' +
'}';
}
}
// UserName 类
public class UserName {
private Integer id;
private String name;
private String password;
public UserName() {
}
public UserName(Integer id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "UserName{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
}
// page 类
public class Page <T>{
private Integer totalCount;// 总数量
private Integer current;// 当前页面
private Integer totalRows;// 总页码
private List<T> list;// 当前页码的数据
private Integer rows;// 每页的数量
public Integer getTotalCount() {
return totalCount;
}
public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
}
public Integer getCurrent() {
return current;
}
public void setCurrent(Integer current) {
this.current = current;
}
public Integer getTotalRows() {
return totalRows;
}
public void setTotalRows(Integer totalRows) {
this.totalRows = totalRows;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
public Integer getRows() {
return rows;
}
public void setRows(Integer rows) {
this.rows = rows;
}
@Override
public String toString() {
return "Page{" +
"totalCount=" + totalCount +
", current=" + current +
", totalRows=" + totalRows +
", list=" + list +
", rows=" + rows +
'}';
}
}