JavaWeb_(MVC)管理员后台商品查询demo
MVC分层实现管理员后台商品查询
MVC层即model view controller
Model(模型):模型代表着核心的业务逻辑和数据(不要理解成Model只是实体类)
View(视图):视图应该关注与如何展示数据,而不应该包含任何业务逻辑(业务逻辑应写在Model中)
Controller(控制器):控制器控制着程序的逻辑,并充当着视图和模型之间的协调角色。控制器从视图层接收用户输入的信息,然后使用模型来执行特定的操作,并把最终的结果回传给视图
model层:存放业务逻辑处理,不直接和数据库打交道但存放关于数据库处理的操作
Dao层:对数据库进行数据持久化操作,操作直接针对数据库
index.jsp进行首页的展示,用户可以在首页进行普通用户的注册和登录,当使用管理员账号登录时候可以进入商品后台对其进行进一步管理(LoginServlet.java中实现)
项目结构
DBUtil.java模拟数据库,已存在的管理员用户和商品信息列表如下,注册时只能对普通用户进行注册,Gary和Gary2的isAdmin为True
public static Map<String , User> userMap = new HashMap<String , User>(); public static List<Goods> goodsList = new ArrayList<Goods>(); static { addUser(new User("Gary","123",10,"男",true)); addUser(new User("Gary2","456",20,"男",true)); goodsList.add(new Goods("香蕉","这个是香蕉",100,110)); goodsList.add(new Goods("苹果","这个是苹果",200,120)); goodsList.add(new Goods("西瓜","这个是西瓜",300,130)); goodsList.add(new Goods("桃子","这个是桃子",400,140)); }
逻辑层:处理代码请求
package com.Gary.controller; import java.io.IOException; import java.util.List; 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 com.Gary.model.Goods; import com.Gary.service.GoodsService; @WebServlet("/admin/goods_list") public class GoodsListServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<Goods> list = new GoodsService().selectAllGoods(); request.setAttribute("list", list); request.getRequestDispatcher("/admin/goods_list.jsp").forward(request, response); } }
package com.Gary.controller; import java.io.IOException; 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 com.Gary.model.User; import com.Gary.service.UserService; @WebServlet("/login_do") public class LoginServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); UserService service = new UserService(); User user =service.login(username, password); System.out.println(user); if(user!=null) { request.getSession().setAttribute("user", user); //System.out.println(user); //TODO if(user.isAdmin()) { //管理员 //response.sendRedirect(request.getContextPath()+"/admin/goods_list.jsp"); request.getRequestDispatcher("admin/goods_list").forward(request, response); //不需要传递数据时可以使用重定向 //response.sendRedirect(request.getContextPath()+"/admin/good_list"); }else { //普通用户 //System.out.println("完成"); request.getRequestDispatcher("/").forward(request, response); } }else { request.setAttribute("msg", "<font color='red'>用户名或密码错误,请重新登录!</font>"); request.getRequestDispatcher("/login.jsp").forward(request, response); } } }
package com.Gary.controller; import java.io.IOException; 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 com.Gary.service.UserService; /** * Servlet implementation class RegisterService */ @WebServlet("/register_do") public class RegisterService extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置中文编码 request.setCharacterEncoding("utf-8"); String username = request.getParameter("username"); String password = request.getParameter("password"); int age = Integer.parseInt(request.getParameter("age")); String sex = request.getParameter("sex"); UserService userService = new UserService(); boolean isSuccess = userService.register(username,password,age,sex); if(isSuccess) { request.setAttribute("msg", "<font color='green'>注册成功,请登录!</font>"); request.getRequestDispatcher("/login.jsp").forward(request, response); }else { request.setAttribute("msg", "<font color='red'>用户名重复,请重新填写</font>"); request.getRequestDispatcher("/register.jsp").forward(request, response); } } }
DAO层:将数据存到数据库中
package com.Gary.dao; import java.util.List; import com.Gary.model.Goods; import com.Gary.util.DBUtil; public class GoodsDao { public List<Goods> getAllGoods(){ return DBUtil.goodsList; } }
package com.Gary.dao; import com.Gary.model.User; import com.Gary.util.DBUtil; public class UserDao { public boolean isExist(String username) { return DBUtil.userMap.containsKey(username); } public boolean addUser(String username,String password,int age,String sex) { if(isExist(username)) return false; User u = new User(username,password,age,sex,false); DBUtil.userMap.put(u.getUsername(),u); return true; } public User getUserByUP(String username,String password) { if(isExist(username)==false) return null; User u = DBUtil.userMap.get(username); if(u.getPassword().equals(password))return u; else return null; } }
model层:存放我们的实体类,与数据库中的属性值基本保持一致
package com.Gary.model; public class Goods { private String name; private String des; private int price; private int inventory; public Goods(String name, String des, int price, int inventory) { super(); this.name = name; this.des = des; this.price = price; this.inventory = inventory; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDes() { return des; } public void setDes(String des) { this.des = des; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public int getInventory() { return inventory; } public void setInventory(int inventory) { this.inventory = inventory; } }
package com.Gary.model; public class User { private String username; private String password; private int age; private String sex; private boolean isAdmin=false; //判断是否是管理员账号 public User(String username, String password, int age, String sex, boolean isAdmin) { super(); this.username = username; this.password = password; this.age = age; this.sex = sex; this.isAdmin = isAdmin; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public boolean isAdmin() { return isAdmin; } public void setAdmin(boolean isAdmin) { this.isAdmin = isAdmin; } }
service层:存放业务逻辑处理
package com.Gary.service; import java.util.List; import com.Gary.dao.GoodsDao; import com.Gary.model.Goods; public class GoodsService { public List<Goods> selectAllGoods(){ return new GoodsDao().getAllGoods(); } }
package com.Gary.service; import com.Gary.dao.UserDao; import com.Gary.model.User; public class UserService { //处理注册请求 public boolean register(String username,String password,int age ,String sex) { UserDao userDao = new UserDao(); boolean isExist =userDao.isExist(username); if(isExist) return false; else userDao.addUser(username, password, age, sex); return true; } public User login(String username,String password) { return new UserDao().getUserByUP(username, password); } }
util层:辅助作用 【我用来做数据库的模拟】
package com.Gary.util; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.Gary.model.Goods; import com.Gary.model.User; //模拟数据库 public class DBUtil { public static Map<String , User> userMap = new HashMap<String , User>(); public static List<Goods> goodsList = new ArrayList<Goods>(); static { addUser(new User("Gary","123",10,"男",true)); addUser(new User("Gary2","456",20,"男",true)); goodsList.add(new Goods("香蕉","这个是香蕉",100,110)); goodsList.add(new Goods("苹果","这个是苹果",200,120)); goodsList.add(new Goods("西瓜","这个是西瓜",300,130)); goodsList.add(new Goods("桃子","这个是桃子",400,140)); } private static void addUser(User user) { userMap.put(user.getUsername(), user); } }
商品列表页面
<%@page import="com.Gary.model.Goods"%> <%@page import="java.util.List"%> <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Insert title here</title> <style type="text/css"> *{ font-size = 20px; } </style> </head> <body> <h1>商品管理</h1> </hr> <a>添加</a> <table border = "1"> <tr> <td>商品名</td><td>描述</td><td>价格</td><td>库存</td><td>操作</td> </tr> <% List<Goods> list = (List<Goods>)request.getAttribute("list"); for(Goods goods : list){ %> <tr> <td><%=goods.getName() %></td><td><%=goods.getDes() %></td><td><%=goods.getPrice() %></td><td><%=goods.getInventory() %></td><td>删除 修改</td> </tr> <% } %> <!-- <tr> --> <!-- <td>香蕉</td><td>这个是香蕉</td><td>78</td><td>500</td><td>删除 修改</td> --> <!-- </tr> --> </body> </html>
首页面
<%@ page import="com.Gary.model.User" %> <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Insert title here</title> </head> <% Object user = session.getAttribute("user"); if(user==null){ %> <a href="<%=request.getContextPath() %>/login.jsp">登录</a> <a href="<%=request.getContextPath() %>/register.jsp">注册</a> <% }else{ out.println("当前登录用户:"+((User)user).getUsername()); } %> <body> </br> 各种商品的展示 </body> </html>
用户登录页面
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Insert title here</title> </head> <body> <% if(request.getAttribute("msg")!=null) out.println(request.getAttribute("msg")+"<br/>"); %> 登录 <hr/> <form action="<%=request.getContextPath() %>/login_do" method="post"> 用户名:<input type="text" name="username" /><br/> 密码:<input type="password" name="password" /><br/> <input type="submit" value="登录" /> </form> </body> </html>
用户注册页面
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Insert title here</title> </head> <body> <% if(request.getAttribute("msg")!=null) out.println(request.getAttribute("msg")+"<br/>"); %> 注册 <hr/> <form action="<%=request.getContextPath() %>/register_do" method="post"> 用户名:<input type="text" name="username" /><br/> 密码:<input type="password" name="password" /><br/> 年龄:<input type="text" name="age" /><br/> 性别: 男<input type="radio" name="sex" value="男" checked="checked"/>女<input type="radio" name="sex" value="女" /><br/> <input type="submit" value="注册" /> </form> </body> </html>
实现过程
index.jsp判断有无用户登录,有用户登录时展示用户信息,若无用户登录则显示用户注册登录
<% Object user = session.getAttribute("user"); if(user==null){ %> <a href="<%=request.getContextPath() %>/login.jsp">登录</a> <a href="<%=request.getContextPath() %>/register.jsp">注册</a> <% }else{ out.println("当前登录用户:"+((User)user).getUsername()); } %>
用户注册后将表单提交给register_do
<form action="<%=request.getContextPath() %>/register_do" method="post"> 用户名:<input type="text" name="username" /><br/> 密码:<input type="password" name="password" /><br/> 年龄:<input type="text" name="age" /><br/> 性别: 男<input type="radio" name="sex" value="男" checked="checked"/>女<input type="radio" name="sex" value="女" /><br/> <input type="submit" value="注册" /> </form>
创建用户数据模型User,java和Goods.java
private String username; private String password; private int age; private String sex; private boolean isAdmin=false; //判断是否是管理员账号
private String name; private String des; //商品描述信息 private int price; private int inventory; //商品库存
DBUtil.java模拟数据库,将用户与商品存放到List<>集合中
public static Map<String , User> userMap = new HashMap<String , User>(); public static List<Goods> goodsList = new ArrayList<Goods>(); static { addUser(new User("Gary","123",10,"男",true)); addUser(new User("Gary2","456",20,"男",true)); goodsList.add(new Goods("香蕉","这个是香蕉",100,110)); goodsList.add(new Goods("苹果","这个是苹果",200,120)); goodsList.add(new Goods("西瓜","这个是西瓜",300,130)); goodsList.add(new Goods("桃子","这个是桃子",400,140)); } private static void addUser(User user) { userMap.put(user.getUsername(), user); }
UserDao.java和GoodDao.java处理数据库逻辑
//用户是否退出登录 public boolean isExist(String username) { return DBUtil.userMap.containsKey(username); } //添加用户 public boolean addUser(String username,String password,int age,String sex) { if(isExist(username)) return false; User u = new User(username,password,age,sex,false); DBUtil.userMap.put(u.getUsername(),u); return true; } //判断用户是否登录成功 public User getUserByUP(String username,String password) { if(isExist(username)==false) return null; User u = DBUtil.userMap.get(username); if(u.getPassword().equals(password))return u; else return null; }
public class GoodsDao { //列出所有的商品 public List<Goods> getAllGoods(){ return DBUtil.goodsList; } }
RegisterService.java处理用户注册信息,处理用户的注册和登录
@WebServlet("/register_do") public class RegisterService extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置中文编码 request.setCharacterEncoding("utf-8"); String username = request.getParameter("username"); String password = request.getParameter("password"); int age = Integer.parseInt(request.getParameter("age")); String sex = request.getParameter("sex"); UserService userService = new UserService(); boolean isSuccess = userService.register(username,password,age,sex); if(isSuccess) { request.setAttribute("msg", "<font color='green'>注册成功,请登录!</font>"); request.getRequestDispatcher("/login.jsp").forward(request, response); }else { request.setAttribute("msg", "<font color='red'>用户名重复,请重新填写</font>"); request.getRequestDispatcher("/register.jsp").forward(request, response); } } }
LoginServlet.java处理用户登录后分用户和管理员操作,用户跳转到首页,管理员则转发到goods_list对商品后台信息进行处理
GoodsListServlet.java处理转发的goods_list请求
@WebServlet("/admin/goods_list") public class GoodsListServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<Goods> list = new GoodsService().selectAllGoods(); request.setAttribute("list", list); request.getRequestDispatcher("/admin/goods_list.jsp").forward(request, response); } }
goods_list.jsp展示数据库中商品信息列表
<% List<Goods> list = (List<Goods>)request.getAttribute("list"); for(Goods goods : list){ %> <tr> <td><%=goods.getName() %></td><td><%=goods.getDes() %></td><td><%=goods.getPrice() %></td><td><%=goods.getInventory() %></td><td>删除 修改</td> </tr> <% } %> <!-- <tr> --> <!-- <td>香蕉</td><td>这个是香蕉</td><td>78</td><td>500</td><td>删除 修改</td> --> <!-- </tr> -->