基于javaweb+mysql的ssm+maven校园外卖点餐系统(java+ssm+jsp+maven+mysql)
运行环境
Java≥8、MySQL≥5.7、Tomcat≥8
开发工具
eclipse/idea/myeclipse/sts等均可配置运行
适用
课程设计,大作业,毕业设计,项目练习,学习演示等
功能说明
基于javaweb+mysql的SSM+Maven校园外卖点餐系统(java+ssm+jsp+maven+mysql)
一、项目简述 环境配置:
Jdk1.8 + Tomcat8.5 + mysql + Eclispe(IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持)
项目技术:
JSP +Spring + SpringMVC + MyBatis + css + JavaScript + JQuery + Ajax + layui+ maven等等。
Category categoryByid = productService.getCategoryByCid(id);
model.addAttribute("crrentCategory",categoryByid);
//通过id返回所属商家
User userById = userService.getUserByPid(id);
model.addAttribute("crrentUser",userById);
model.addAttribute("categoryList",categoryList);
model.addAttribute("userList",userList);
return "productmodule/product-edit";
}
@RequestMapping("/updateProduct")
public String update(Product product, HttpSession session, UploadUtil upload) throws IOException {
productService.update(product);
if(upload!=null){
String imageName = product.getId()+".jpg";
File file = new File(session.getServletContext().getRealPath("/images/product"),imageName);
file.getParentFile().mkdirs();
upload.getImage().transferTo(file);
ProductVO vo = new ProductVO();
vo.setId(product.getId());
vo.setImageUrl("images/product/"+imageName);
productService.setImageURL(vo);
}
return "redirect:list";
}
}
package com.demo.common.Interceptor;
/**
* 前台登陆状态拦截器 如果访问的请求没有在noNeedAuthPage数组就跳转登陆
*/
public class LoginInterceptor extends HandlerInterceptorAdapter {
Customer cst = (Customer)session.getAttribute("cst");
float total = 0;
int number = 0;
for (String strid : oiid) {
int id = Integer.parseInt(strid);
OrderItem oi= orderItemService.get(id);
if (cst.getStatus()==1){
total +=oi.getProduct().getPrice()*0.8*oi.getNumber();
}else{
total +=oi.getProduct().getPrice()*oi.getNumber();
}
number += oi.getNumber();
ois.add(oi);
}
/*
累计这些ois的价格总数,赋值在total上
把订单项集合放在session的属性 "ois" 上,方便下订单时候直接获取
把总价格放在 model的属性 "total" 上
服务端跳转到buy.jsp
*/
session.setAttribute("ois", ois);
model.addAttribute("total", total);
model.addAttribute("number", number);
return "forepage/foreBuy";
}
/**
* 添加购物车
* @param pid 商品id
* @param number 购买数量
* @param model
* @param session
* @return boolean
*/
@RequestMapping("/foreAddCart")
@ResponseBody
public String addCart(int pid, int number, Model model, float totalPrice, HttpSession session) {
Customer customer =(Customer) session.getAttribute("cst");
if(customer==null){
return "false";
}
Product p = productService.get(pid);
boolean found = false;
//获得订单项表中该用户的所有订单id为空的订单项
List<OrderItem> ois = orderItemService.listByCustomer(customer.getId());
for (OrderItem oi : ois) {
//基于用户对象customer,查询没有生成订单的订单项集合
* @param content
* @return
*/
@RequestMapping("/cstPinglun")
@ResponseBody
public String cstPinglun(HttpSession session, int pid, String content){
Customer cst = (Customer) session.getAttribute("cst");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format = sdf.format(new Date());
//string转date
ParsePosition pos = new ParsePosition(0);
Date strtodate = sdf.parse(format, pos);
Review review = new Review();
review.setCstid(cst.getId());
review.setCustomer(cst);
review.setPid(pid);
review.setProduct(productService.get(pid));
review.setContent(content);
review.setCreatetime(strtodate);
reviewService.save(review);
return "success";
}
/**
* 已审核的资讯
* @param model
* @return
*/
@RequestMapping("/foreZixuns")
public String zixun(Model model){
List<ZiXun> list = ziXunService.list();
model.addAttribute("list",list);
return "forepage/foreZixun";
}
@RequestMapping("/foreZixunadd")
@ResponseBody
@RequestMapping("/productAddUI")
public String addUI(Model model){
List<Category> categoryList = categoryService.list();
List<User> userList = userService.list();
model.addAttribute("categoryList",categoryList);
model.addAttribute("userList",userList);
return "productmodule/product-add";
}
@RequestMapping("/addProduct")
public String add(Product product, HttpSession session, UploadUtil upload) throws IOException {
productService.save(product);
if (upload != null) {
String imageName = product.getId()+".jpg";
File file = new File(session.getServletContext().getRealPath("/images/product"),imageName);
System.out.println(session.getServletContext().getRealPath("/images/product"));
file.getParentFile().mkdirs();
upload.getImage().transferTo(file);
System.out.println("["+product.getId()+","+"images/product/"+imageName+"]");
ProductVO vo = new ProductVO();
vo.setId(product.getId());
vo.setImageUrl("images/product/"+imageName);
productService.setImageURL(vo);
System.out.println(productService.get(product.getId()));
}
return "redirect:list";
}
@RequestMapping("/deleteProduct")
public String del(@RequestParam(value = "id")int id, HttpSession session){
productService.del(id);
String imageName = id+".jpg";
File file = new File(session.getServletContext().getRealPath("/images/product"),imageName);
file.delete();
return "redirect:list";
@Controller
@RequestMapping("/fore")
public class ForeController {
@Autowired
private ForeService foreService;
@Autowired
private ProductService productService;
@Autowired
private ReviewService reviewService;
@Autowired
private CategoryService categoryService;
@Autowired
private CustomerService customerService;
@Autowired
private OrderItemService orderItemService;
@Autowired
private OrderService orderService;
@Autowired
private ZiXunService ziXunService;
public String PNAME=null;
/**
* 前台首页
* @param model
* @return
*/
@RequestMapping("/foreIndex")
public String index(Model model, HttpSession session){
//传入3个分类
List<Category> categories = foreService.listToThree();
List<Category> categories1 = categoryService.list();
//给每个分类设置商品
for (Category c:categories){
List<Product> products = productService.getProductsByCid(c.getId());
//如果分类下的商品超过4个,则只显示4个给前端
if(products.size()>5){
List<Product> products1 = new ArrayList<Product>();
for(int i=0;i<=4;i++){
products1.add(products.get(i));
}
c.setProducts(products1);
}else{
c.setProducts(products);
}
/**
* 评论模块controller
*/
@Controller
@RequestMapping("/review")
public class ReviewController {
@Autowired
private ReviewService reviewService;
@Autowired
private ProductService productService;
@RequestMapping("/list")
public String list(Model model, Page page){
PageHelper.offsetPage(page.getStart(),page.getCount());//分页查询
List<Review> list= reviewService.list();
int total = (int) new PageInfo<>(list).getTotal();//总条数
page.setTotal(total);
model.addAttribute("totals",list.size());
model.addAttribute("list",list);
return "pinglunpage/pinglun";
}
@RequestMapping("/del")
public String del(int id){
reviewService.del(id);
for(int i=0;i<8;i++){
ps1.add(ps.get(i));
}
model.addAttribute("products",ps1);
model.addAttribute("category",category);
return "forepage/proCategorySeach";
}
model.addAttribute("products",ps);
model.addAttribute("proSize",ps.size());
model.addAttribute("category",category);
return "forepage/proCategorySeach";
}
@RequestMapping("/faq")
public String faq(){
return "forepage/faq";
}
/**
* 商品评价
* @param pid
* @param model
* @return
*/
@RequestMapping("/forePingjia")
public String forePingjia(int pid, Model model){
return "forePage/pingjia";
}
/**
* 商品评论
* @param session
* @param pid
* @param content
* @return
*/
@RequestMapping("/cstPinglun")
@ResponseBody
public String cstPinglun(HttpSession session, int pid, String content){
Customer cst = (Customer) session.getAttribute("cst");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format = sdf.format(new Date());
//string转date
ParsePosition pos = new ParsePosition(0);
Date strtodate = sdf.parse(format, pos);
Review review = new Review();
review.setCstid(cst.getId());
review.setCustomer(cst);
review.setPid(pid);
@RequestMapping("/del")
public String del(int id){
reviewService.del(id);
return "redirect:list";
}
}
package com.demo.common.exception;
/**
* 全局异常类
*/
@ControllerAdvice
public class DefaultExceptionHandler {
@ExceptionHandler({UnauthorizedException.class}) //异常判断类
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public ModelAndView processUnauthenticatedException(NativeWebRequest request, UnauthorizedException e) {
ModelAndView mv = new ModelAndView();
mv.addObject("ex", e);
mv.setViewName("unauthorized");
return mv;
}
}
package com.demo.controller;
/**
* 专门用于显示页面的控制器
*/
@Controller
@RequestMapping("")
public class PageController {
/**
* 后台主页页面
* @return
*/
}
/**
* 在业务处理器处理请求执行完成后,生成视图之前执行的动作
* 可在modelAndView中加入数据,比如当前时间
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// super.postHandle(request, response, handler, modelAndView);
}
/**
* 在DispatcherServlet完全处理完请求后被调用,可用于清理资源等
*
* 当有拦截器抛出异常时,会从当前拦截器往回执行所有的拦截器的afterCompletion()
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// super.afterCompletion(request, response, handler, ex);
}
}
package com.demo.controller;
model.addAttribute("list",list);
return "forepage/foreZixun";
}
@RequestMapping("/foreZixunadd")
@ResponseBody
public String zixunadd(String content, HttpSession session){
Customer c = (Customer) session.getAttribute("cst");
ZiXun z = new ZiXun();
z.setCstid(c.getId());
z.setContent(content);
z.setFabudate(new Date());
z.setStatus(0);
ziXunService.save(z);
return "success";
}
}
package com.demo.controller;
@Autowired
RoleService roleService;
@Autowired
RolePermissionService rolePermissionService;
@Autowired
PermissionService permissionService;
@RequestMapping("/addRoleUI")
public String addRole(){
return "syspage/admin-role-add";
}
@RequestMapping("/listRole")
public String list(Model model, Page page){
PageHelper.offsetPage(page.getStart(),page.getCount());//分页查询
List<Role> rs= roleService.list();
int total = (int) new PageInfo<>(rs).getTotal();//总条数
page.setTotal(total);
model.addAttribute("rs", rs);
model.addAttribute("roleSize",total);
Map<Role,List<Permission>> role_permissions = new HashMap<>();
for (Role role : rs) {
List<Permission> ps = permissionService.list(role);
role_permissions.put(role, ps);
}
model.addAttribute("role_permissions", role_permissions);
return "syspage/admin-role";
}
@RequestMapping("/editRole")
public String list(Model model, long id){
Role role =roleService.get(id);
model.addAttribute("role", role);
//所有权限
return "productmodule/category-edit";
}
@RequestMapping("/updateCategory")
public String update(Category category, Model model){
categoryService.update(category);
return "redirect:list";
}
}
package com.demo.controller;
/**
* 用户模块controller
*/
@Controller
@RequestMapping("/customer")
public class CustomerController {
@Autowired
private CustomerService customerService;
@RequestMapping("/list")
public String list(Model model, Page page){
PageHelper.offsetPage(page.getStart(),page.getCount());//分页查询
List<Customer> list= customerService.list();
int total = (int) new PageInfo<Customer>(list).getTotal();//总条数
page.setTotal(total);
model.addAttribute("list",list);
model.addAttribute("totals",total);
return "cstpage/cst-list";
}
@RequestMapping("/addRoleUI")
public String addRole(){
return "syspage/admin-role-add";
}
@RequestMapping("/listRole")
public String list(Model model, Page page){
PageHelper.offsetPage(page.getStart(),page.getCount());//分页查询
List<Role> rs= roleService.list();
int total = (int) new PageInfo<>(rs).getTotal();//总条数
page.setTotal(total);
model.addAttribute("rs", rs);
model.addAttribute("roleSize",total);
Map<Role,List<Permission>> role_permissions = new HashMap<>();
for (Role role : rs) {
List<Permission> ps = permissionService.list(role);
role_permissions.put(role, ps);
}
model.addAttribute("role_permissions", role_permissions);
return "syspage/admin-role";
}
@RequestMapping("/editRole")
public String list(Model model, long id){
Role role =roleService.get(id);
model.addAttribute("role", role);
//所有权限
List<Permission> ps = permissionService.list();
model.addAttribute("ps", ps);
//当前管理员拥有的权限
List<Permission> currentPermissions = permissionService.list(role);
model.addAttribute("currentPermissions", currentPermissions);
return "syspage/admin-role-edit";
}
@RequestMapping("/updateRole")
public String update(Role role,long[] permissionIds){
rolePermissionService.setPermissions(role, permissionIds);
roleService.update(role);
return "redirect:listRole";
}
@RequestMapping("/addRole")
public String list(Model model, Role role){
@Controller
@RequestMapping("/zixun")
public class ZiXunController {
@Autowired
private ZiXunService ziXunService;
@RequestMapping("/list")
public String list(Page page, Model model){
PageHelper.offsetPage(page.getStart(),page.getCount());//分页查询
List<ZiXun> list = ziXunService.list1();
int total = (int) new PageInfo<ZiXun>(list).getTotal();//总条数
page.setTotal(total);
model.addAttribute("list",list);
model.addAttribute("totals",total);
return "cstpage/zixun-list";
}
/**
* 审核
* @param zid
* @return
*/
@RequestMapping("/zixunshenhe")
@ResponseBody
public String zixunshenhe(int zid){
ziXunService.shenhe(zid);
return "success";
}
@RequestMapping("/del")
public String del(int id){
ziXunService.del(id);
return "redirect:list";
}
* 接着再从最后一个拦截器往回执行所有的afterCompletion()
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
/**
* 不需要登录也可以访问的
* 注册,登录,产品,首页,分类,查询等等
* 需要登录才能够访问的
* 购买行为,加入购物车行为,查看购物车,查看我的订单等等
* 不需要登录也可以访问的已经确定了,但是需要登录才能够访问,截止目前为止还不能确定,所以这个过滤器就判断如果不是注册,登录,产品这些,就进行登录校验
* 1. 准备字符串数组 noNeedAuthPage,存放哪些不需要登录也能访问的路径
* 2. 获取uri
* 3. 去掉前缀/fore
* 4. 如果访问的地址是/fore开头
* 4.1 取出fore后面的字符串,比如是forecart,那么就取出cart
* 4.2 判断cart是否是在noNeedAuthPage
* 4.2 如果不在,那么就需要进行是否登录验证
* 4.3 从session中取出"cst"对象
* 4.4 如果对象不存在,就客户端跳转到login.jsp
* 4.5 否则就正常执行
*/
HttpSession session = request.getSession();
String contextPath=session.getServletContext().getContextPath()+"/fore";
//准备字符串数组 noNeedAuthPage,存放哪些不需要登录也能访问的路径
String[] noNeedAuthPage = new String[]{
"Index", //首页
"DetailUI", //商品详情页
"RegisterUI", //注册页
"Register", //注册
"LoginUI", //登陆页
"Login", //登陆
"IsLogin", //判断是否登陆
"MtLogin", //模态登陆验证
"CstLoginOut", //退出
"DelOrderItem",//删除购物车项
"CreateOrder", //提交订单
"Payed", //支付成功
"NameLike", //模糊搜索商品
"FindCategory", //查看分类下的商品
"Zixunadd", //添加资讯
"LoginMsg", //登陆返回信息
};
//获取uri
String uri = request.getRequestURI(); //访问首页 /fore/foreIndex
//去掉前缀/fore
uri = uri.substring(5,uri.length()); //去掉前缀后 /foreIndex
/**
* 专门用于显示页面的控制器
*/
@Controller
@RequestMapping("")
public class PageController {
/**
* 后台主页页面
* @return
*/
@RequestMapping("/index")
public String index(){
return "index";
}
/**
* 后台登陆页面
* @return
*/
@RequestMapping(value="login",method= RequestMethod.GET)
public String login(){
return "login";
}
/**
* 无权限页面
* @return
*/
@RequestMapping("/unauthorized")
public String noPerms(){
return "unauthorized";
}
}
package com.baidu.ueditor.upload;
public class Uploader {
private HttpServletRequest request = null;
private Map<String, Object> conf = null;
public Uploader(HttpServletRequest request, Map<String, Object> conf) {
this.request = request;
this.conf = conf;
}
"DelOrderItem",//删除购物车项
"CreateOrder", //提交订单
"Payed", //支付成功
"NameLike", //模糊搜索商品
"FindCategory", //查看分类下的商品
"Zixunadd", //添加资讯
"LoginMsg", //登陆返回信息
};
//获取uri
String uri = request.getRequestURI(); //访问首页 /fore/foreIndex
//去掉前缀/fore
uri = uri.substring(5,uri.length()); //去掉前缀后 /foreIndex
//如果访问的地址是/fore开头
if(uri.startsWith("/fore")){
//判断是否是在noNeedAuthPage
String method = StringUtils.substringAfterLast(uri,"/fore" ); // 取出/fore后的字符串:Index
//如果不在,那么就需要进行是否登录验证
if(!Arrays.asList(noNeedAuthPage).contains(method)){
Customer customer =(Customer) session.getAttribute("cst");
if(null==customer){
response.sendRedirect("foreLoginUI");
return false;
}
}
}
return true;
}
/**
* 在业务处理器处理请求执行完成后,生成视图之前执行的动作
* 可在modelAndView中加入数据,比如当前时间
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// super.postHandle(request, response, handler, modelAndView);
}
/**
* 在DispatcherServlet完全处理完请求后被调用,可用于清理资源等
*
* 当有拦截器抛出异常时,会从当前拦截器往回执行所有的拦截器的afterCompletion()
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// super.afterCompletion(request, response, handler, ex);
}
}
/**
* 评论模块controller
*/
@Controller
@RequestMapping("/review")
public class ReviewController {
@Autowired
private ReviewService reviewService;
@Autowired
private ProductService productService;
@RequestMapping("/list")
public String list(Model model, Page page){
PageHelper.offsetPage(page.getStart(),page.getCount());//分页查询
List<Review> list= reviewService.list();
int total = (int) new PageInfo<>(list).getTotal();//总条数
page.setTotal(total);
model.addAttribute("totals",list.size());
model.addAttribute("list",list);
return "pinglunpage/pinglun";
}
@RequestMapping("/del")
public String del(int id){
reviewService.del(id);
return "redirect:list";
}
}
package com.demo.common.exception;
/**
* 全局异常类
*/
@ControllerAdvice
public class DefaultExceptionHandler {
@ExceptionHandler({UnauthorizedException.class}) //异常判断类
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public ModelAndView processUnauthenticatedException(NativeWebRequest request, UnauthorizedException e) {
ModelAndView mv = new ModelAndView();
mv.addObject("ex", e);
mv.setViewName("unauthorized");
return mv;
}
}
package com.demo.controller;
/**
* 专门用于显示页面的控制器
*/
@Controller
@RequestMapping("")
public class PageController {
/**
* 后台主页页面
* @return
*/
@RequestMapping("/index")
public String index(){
return "index";
}
/**
* 后台登陆页面
}
@RequestMapping("/listRole")
public String list(Model model, Page page){
PageHelper.offsetPage(page.getStart(),page.getCount());//分页查询
List<Role> rs= roleService.list();
int total = (int) new PageInfo<>(rs).getTotal();//总条数
page.setTotal(total);
model.addAttribute("rs", rs);
model.addAttribute("roleSize",total);
Map<Role,List<Permission>> role_permissions = new HashMap<>();
for (Role role : rs) {
List<Permission> ps = permissionService.list(role);
role_permissions.put(role, ps);
}
model.addAttribute("role_permissions", role_permissions);
return "syspage/admin-role";
}
@RequestMapping("/editRole")
public String list(Model model, long id){
Role role =roleService.get(id);
model.addAttribute("role", role);
//所有权限
List<Permission> ps = permissionService.list();
model.addAttribute("ps", ps);
//当前管理员拥有的权限
List<Permission> currentPermissions = permissionService.list(role);
model.addAttribute("currentPermissions", currentPermissions);
return "syspage/admin-role-edit";
}
@RequestMapping("/updateRole")
public String update(Role role,long[] permissionIds){
rolePermissionService.setPermissions(role, permissionIds);
roleService.update(role);
return "redirect:listRole";
* 删除订单项
* @param oiid 订单项id
* @param session
* @return
*/
@RequestMapping("/foreDelOrderItem")
@ResponseBody
public String foreDelOrderItem(int oiid, HttpSession session){
Customer customer = (Customer) session.getAttribute("cst");
if(customer==null){
return "noSuccess";
}
orderItemService.del(oiid);
return "success";
}
/*
点击提交订单
1. 从session中获取cst对象
2. 通过参数Order接受收货人
3. 根据当前时间加上一个4位随机数生成订单号
4. 根据上述参数,创建订单对象
5. 把订单状态设置为未支付
6. 从session中获取订单项集合 ( 在结算功能的ForeController.buy() 13行,订单项集合被放到了session中 )
7. 把订单加入到数据库,并且遍历订单项集合,设置每个订单项的order,更新到数据库
8. 统计本次订单的总金额
9. 客户端跳转到确认支付页forePayed,并带上订单id和总金额
*/
@RequestMapping("/foreCreateOrder")
public String createOrder(Model model, String address, HttpSession session){
/*
提交订单后,设置code,客户id,支付状态,地址
*/
Order order = new Order();
Customer customer =(Customer) session.getAttribute("cst");
String orderCode = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + RandomUtils.nextInt(10000);
order.setCode(orderCode);
order.setAddress(address);
order.setCstid(customer.getId());
order.setStatus(0);//未支付
List<OrderItem> ois= (List<OrderItem>) session.getAttribute("ois");
//给每个订单项设置订单id 并且算出订单总价
float total =orderService.add(order,ois);
return "redirect:forePayed?oid="+order.getId() +"&total="+total;
}
/**
* 支付成功跳转
if(us!=null){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//上次时间
Date time = us.getLasttime();
lastLoginTime = sdf.format(time);
//新时间
String format = sdf.format(new Date());
//string转date 不处理时间格式会不理想
ParsePosition pos = new ParsePosition(0);
Date strtodate = sdf.parse(format, pos);
us.setLasttime(strtodate);
userService.update(us);
}
if (us.getStatus()==1){
Session session=subject.getSession();
session.setAttribute("subject", subject);
session.setAttribute("lastLoginTime",lastLoginTime);
return "redirect:index";
}else {
model.addAttribute("error", "账号已被停用!");
return "/login";
}
} catch (AuthenticationException e) {
model.addAttribute("error", "验证失败!");
return "/login";
}
}
}
package com.demo.controller;
/**
* 权限模块controller
*/
@Controller
@RequestMapping("/config")
public class PermissionController {
@Autowired
PermissionService permissionService;
OrderItemService orderItemService;
/**
* 在业务处理器处理请求之前被调用
* 如果返回false
* 从当前的拦截器往回执行所有拦截器的afterCompletion(),再退出拦截器链
* 如果返回true
* 执行下一个拦截器,直到所有的拦截器都执行完毕
* 再执行被拦截的Controller
* 然后进入拦截器链,
* 从最后一个拦截器往回执行所有的postHandle()
* 接着再从最后一个拦截器往回执行所有的afterCompletion()
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
/**
* 不需要登录也可以访问的
* 注册,登录,产品,首页,分类,查询等等
* 需要登录才能够访问的
* 购买行为,加入购物车行为,查看购物车,查看我的订单等等
* 不需要登录也可以访问的已经确定了,但是需要登录才能够访问,截止目前为止还不能确定,所以这个过滤器就判断如果不是注册,登录,产品这些,就进行登录校验
* 1. 准备字符串数组 noNeedAuthPage,存放哪些不需要登录也能访问的路径
* 2. 获取uri
* 3. 去掉前缀/fore
* 4. 如果访问的地址是/fore开头
* 4.1 取出fore后面的字符串,比如是forecart,那么就取出cart
* 4.2 判断cart是否是在noNeedAuthPage
* 4.2 如果不在,那么就需要进行是否登录验证
* 4.3 从session中取出"cst"对象
* 4.4 如果对象不存在,就客户端跳转到login.jsp
* 4.5 否则就正常执行
*/
HttpSession session = request.getSession();
String contextPath=session.getServletContext().getContextPath()+"/fore";
//准备字符串数组 noNeedAuthPage,存放哪些不需要登录也能访问的路径
String[] noNeedAuthPage = new String[]{
"Index", //首页
"DetailUI", //商品详情页
"RegisterUI", //注册页
"Register", //注册
"LoginUI", //登陆页
"Login", //登陆
"IsLogin", //判断是否登陆
String salt = new SecureRandomNumberGenerator().nextBytes().toString();
int times = 2;
String algorithmName = "md5";
String encodedPassword = new SimpleHash(algorithmName,password,salt,times).toString();
user.setSalt(salt);
user.setPassword(encodedPassword);
user.setPassword(password);
}
else
user.setPassword(null);
userService.update(user);
return "redirect:listUser";
}
@RequestMapping("addUser")
public String add(User user,long[] roleIds){
String salt = new SecureRandomNumberGenerator().nextBytes().toString();//生成随机数
int times = 2;
String algorithmName = "md5";
String encodedPassword = new SimpleHash(algorithmName,user.getPassword(),salt,times).toString();
User u = new User();
u.setName(user.getName());
u.setPassword(encodedPassword);
u.setPassword(user.getPassword());
u.setSalt(salt);
u.setStatus(1);
u.setAddress(user.getAddress());
u.setPhone(user.getPhone());
userService.add(u);
userRoleService.setRoles(u,roleIds);
return "redirect:listUser";
}
public class ForeController {
@Autowired
private ForeService foreService;
@Autowired
private ProductService productService;
@Autowired
private ReviewService reviewService;
@Autowired
private CategoryService categoryService;
@Autowired
private CustomerService customerService;
@Autowired
private OrderItemService orderItemService;
@Autowired
private OrderService orderService;
@Autowired
private ZiXunService ziXunService;
public String PNAME=null;
/**
* 前台首页
* @param model
* @return
*/
@RequestMapping("/foreIndex")
public String index(Model model, HttpSession session){
//传入3个分类
List<Category> categories = foreService.listToThree();
List<Category> categories1 = categoryService.list();
//给每个分类设置商品
for (Category c:categories){
List<Product> products = productService.getProductsByCid(c.getId());
//如果分类下的商品超过4个,则只显示4个给前端
if(products.size()>5){
List<Product> products1 = new ArrayList<Product>();
for(int i=0;i<=4;i++){
products1.add(products.get(i));
}
c.setProducts(products1);
}else{
c.setProducts(products);
if(ps.size()>8){
List<Product> ps1 = new ArrayList<Product>();
for(int i=0;i<8;i++){
ps1.add(ps.get(i));
}
model.addAttribute("products",ps1);
model.addAttribute("category",category);
return "forepage/proCategorySeach";
}
model.addAttribute("products",ps);
model.addAttribute("proSize",ps.size());
model.addAttribute("category",category);
return "forepage/proCategorySeach";
}
@RequestMapping("/faq")
public String faq(){
return "forepage/faq";
}
/**
* 商品评价
* @param pid
* @param model
* @return
*/
@RequestMapping("/forePingjia")
public String forePingjia(int pid, Model model){
return "forePage/pingjia";
}
/**
* 商品评论
* @param session
* @param pid
* @param content
* @return
*/
@RequestMapping("/cstPinglun")
@ResponseBody
public String cstPinglun(HttpSession session, int pid, String content){
Customer cst = (Customer) session.getAttribute("cst");