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);
} }

GoodsListServlet.java

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);
}
} }

LoginServlet.java

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);
}
} }

RegisterService.java

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;
}
}

GoodsDao.java

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;
} }

UserDao.java

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;
} }

Goods.java

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;
} }

User.java

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();
}
}

GoodsService.java

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);
}
}

UserService.java

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);
} }

DBUtil.java

商品列表页面

<%@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>

goods_list.jsp

首页面

<%@ 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>

index.jsp

用户登录页面

<%@ 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>

login.jsp

用户注册页面

<%@ 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>

register.jsp

实现过程

  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> -->

JavaWeb_(MVC)管理员后台商品查询demo的更多相关文章

  1. 【spring mvc】后台API查询接口,get请求,后台Date字段接收前台String类型的时间,报错default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'createDate';

    后台API查询接口,get请求,后台Date字段接收前台String类型的时间筛选条件 后台接口接收 使用的实体 而createDate字段在后台实体中是Date类型 报错信息: org.spring ...

  2. 返璞归真 asp.net mvc (1) - 添加、查询、更新和删除的 Demo

    原文:返璞归真 asp.net mvc (1) - 添加.查询.更新和删除的 Demo [索引页] [源码下载] 返璞归真 asp.net mvc (1) - 添加.查询.更新和删除的 Demo 作者 ...

  3. React MVC框架 <某某后台商品管理开源项目> 完成项目总结

    **百货后台商品信息开源项目 1.利用React  app脚手架 2.封装打包 buid 3.更偏向于后台程序员开发思维 4.利用的 react -redux    react-router-dom  ...

  4. ASP.NET MVC+JQueryEasyUI1.4+ADO.NET Demo

    1.JQueryEasyUI使用 JQuery EasyUI中文官网:http://www.jeasyui.net/ JQuery EasyUI中文官网下载地址:http://www.jeasyui. ...

  5. MVC 从后台页面 取前台页面传递过来的值的几种取法

      MVC 从后台页面 取前台页面传递过来的值的几种取法   <1>前台页面 Index视图 注意:用户名表单的name值为txtName 密码表单的name值为txtPassword & ...

  6. asp.net mvc多条件+分页查询解决方案

    开发环境vs2010 css:bootstrap js:jquery bootstrap paginator 原先只是想做个mvc的分页,但是一般的数据展现都需要检索条件,而且是多个条件,所以就变成了 ...

  7. 50个令人惊奇的jQuery插件(对话框和表单篇)及免费的响应式bootstrap管理员后台界面主题 - Charisma

    http://www.woiweb.net/50-amazing-jquery-plugins.html 多文件文件下载 免费的响应式bootstrap管理员后台界面主题 – Charisma htt ...

  8. ECSHOP后台商品列表显示商品缩略图

    ECSHOP后台商品列表显示商品缩略图 ECSHOP教程/ ecshop教程网(www.ecshop119.com) 2013-11-06   ecshop 后台商品列表显示商品缩略图,大楷步凑如下: ...

  9. IOS CoreData 多表查询demo解析

    在IOS CoreData中,多表查询上相对来说,没有SQL直观,但CoreData的功能还是可以完成相关操作的. 下面使用CoreData进行关系数据库的表与表之间的关系演示.生成CoreData和 ...

随机推荐

  1. # ACM奇淫技巧

    目录 ACM奇淫技巧 差分操作 坐标旋转 ACM 卡常优化 vsc代码块(头文件模板) 读入输出优化 逗号表达式 内联函数inline 寄存器变量register 条件判断加减代替取模 自增运算符优化 ...

  2. 自动生成ID

    public class IdUtil { /** * * @return 返回时间id,类似于20191217195622 */ public static String timeId(){ Dat ...

  3. Fiddler--模拟弱网

    1.首先要勾选Rules--Performance--Simulate Modem Speeds 2.点击Customer Rules 3.然后找到 修改这个值就好. 备注:修改完保存后,要重新勾选第 ...

  4. python之成像库pillow

    目录 python之成像库pillow 官方文档 图像模块(Image.Image) Image模块的功能 Image.new(mode,size,color): Image.open(file,mo ...

  5. C++ 友元(friend关键字)、类中的重载、操作符重载(operator关键字)

    C++ 中友元的用法: 1.在类中使用friend关键字声明 2.类的友元可以是其它类或者具体函数 3.友元不是类的一部分 4.友元不受类中访问级别的限制 5.友元可以直接访问具体类中的所有成员. 友 ...

  6. WebSocket的兼容性

    https://github.com/sockjs/sockjs-client https://socket.io/ https://github.com/gimite/web-socket-js h ...

  7. 会计凭证替代 OBBH

    单词:Validation: 会计凭证校验 ,Substitution:会计凭证替代 step1: GCX2 gblr: ZRFI_GGBR000 gbls: ZRFI_GGBS000 - step2 ...

  8. openCV3 Python编译指南

    这里主要对openCV官网的<Installation in Linux>文档进行了翻译和解释 原文见:https://docs.opencv.org/3.4.1/doc/tutorial ...

  9. java在遍历列表的时候删除列表中某个元素

    在遍历list的时候需要删除其中的某些元素,不要用foreach遍历,需要用Iterator. List<String> list = new ArrayList<String> ...

  10. 关于IDEA,多服务运行 Services -> Run Dashboard 部分服务添加变灰色,限制使用5个启动类,重启之后需要重新添加,服务在 Run Dashboard 中的显示排序问题,不显示 Services(Run Dashboard)

    我的IDEA版本为最新版本 变灰色的原因就是因为右键删除了那个启动的主配置类,然后就会显示灰色,再次打开这个醒目,就不会在Run Dashboard中显示这个主配置类了 解决方法 如果你要 调整这些服 ...