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. Ruby Rails正式学习:Ruby on Rails 做个演示项目吧,逐渐完善

    项目开始 一. 新建Rails项目 1. 修改一下Gemfile文件(简单修改一下) source 'https://rubygems.org' git_source(:github) { |repo ...

  2. js日期相关方法

    /** * ===================================== * 日期相关方法 * ===================================== */ ;(fu ...

  3. copy小练习

    # 1. # 有如下 # v1 = {'郭宝元', '李杰', '太白', '梦鸽'} # v2 = {'李杰', '景女神} # 请得到 v1 和 v2 的交集并输出 # 请得到 v1 和 v2 的 ...

  4. Web前端开发HTML基础

    HTML是英文Hyper Text Mark-up Language(超文本标记语言)的缩写,他是一种制作万维网页面标准语言(标记),相当于定义统一的一套规则,大家都来遵守他,这样就可以让浏览器根据标 ...

  5. Asp.net4.5未在web服务器上注册

    在使用vs2012打开项目时,显示Asp.net4.5未在web服务器上注册?是由于没有下载一个补丁的原因,只需下载安装补丁 VS11-KB3002339.exe 下载地址:https://downl ...

  6. 这38个小技巧告诉你如何快速学习MySQL数据库

    1.如何快速掌握MySQL? ⑴培养兴趣兴趣是最好的老师,不论学习什么知识,兴趣都可以极大地提高学习效率.当然学习MySQL 5.6也不例外.⑵夯实基础计算机领域的技术非常强调基础,刚开始学习可能还认 ...

  7. jquery中的obj.attr()和obj.data

    实例一 obj.attr('data-max-width','aa'): obj.data('max-width') 问题 data只会获取第一次select赋值的值 区别 .data每次是从jque ...

  8. Ubuntu - 14.04下,GO语言的安装!

    一,下载GO语言的安装文件,我直接下载GO语言的安装包(64位),并不是源码: 下载地址: 64位:https://storage.googleapis.com/golang/go1.6.linux- ...

  9. Object.keys()返回对象自身可枚举属性组成的数组

    Object.keys()方法是对一个对象的key遍历,会把key组成一个数组返回 示例: // 参数为数组时,返回的是数组的索引 let arr1 = [1, 2, '3'] console.log ...

  10. 在Chrome中使用IE浏览器!

    学校的毕业论文系统,无法完整显示网页,特别是下部的"提交"按钮看不见. IE11无效. 发现"360极速浏览器 7.5.3.186"能正常显示,百度网盘下载太慢 ...