一些开发用得到的文章和代码
1.文章类
2.代码类
1.常用的重定向方式
常见SpringBoot(RestFul)+SpringMVC模式下,功能说明:点击删除通过id并自动跳转到列表页
@GetMapping("/deleteById/{id}") public String deleteById(@PathVariable("id") Integer id){ cartService.removeById(id); return "redirect:/cart/findAllCart"; }
这里是SpringMVC框架的处理
方式一:使用ModelAndView
return new ModelAndView("redirect:/toList");
这样可以重定向到toList这个方法
方式二:返回String
return "redirect:/ toList ";
记得在spring mvc2中,当保存POJO到数据库后,要返回成功页面,如果这个时候要带点信息,
Java代码: //第三个参数(UserModel user)默认为绑定对象 @RequestMapping(value = "/user/save", method = RequestMethod.POST) public ModelAndView saveUser(HttpServletRequest request, HttpServletResponse response,UserModel user) throws Exception { ModelAndView mv = new ModelAndView("/user/save/result");//默认为forward模式 // ModelAndView mv = new ModelAndView("redirect:/user/save/result");//redirect模式 mv.addObject("message","保存用户成功!"); return mv; }
或者这样,带参数可使用RedirectAttributes参数进行传递:
@RequestMapping(value="/redirect",method=RequestMethod.GET) public String testRedirect(RedirectAttributes attr){ attr.addAttribute("a", "a"); attr.addFlashAttribute("b", "b"); return "redirect:/index.action"; }
1.使用RedirectAttributes的addAttribute方法传递参数会跟随在URL后面,如上代码即为http:/index.action?a=a
2.使用addFlashAttribute不会跟随在URL后面,会把该参数值暂时保存于session,待重定向url获取该参数后从session中移除,这里的redirect必须是方法映射路径,jsp无效。你会发现redirect后的jsp页面中b只会出现一次,刷新后b再也不会出现了,这验证了上面说的,b被访问后就会从session中移除。对于重复提交可以使用此来完成.
@RequestMapping(value="/saveUserDetails.action", method=RequestMethod.POST) public String greetingsAction(@Validated User user,RedirectAttributesredirectAttributes){ someUserdetailsService.save(user); redirectAttributes.addFlashAttribute("firstName", user.getFirstName()); redirectAttributes.addFlashAttribute("lastName", user.getLastName()) return "redirect:success.html"; } success.html: <div> <h1>Hello ${firstName} ${lastName}. Your details stored in our database.</h1> </div><br>
Servlet则这样:
@WebServlet("/RedirectSevlet") public class RedirectSevlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("dopost"); doGet(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("doGet"); //重定向到RedirectSevlet2 request.getContextPath()获取当前项目路径 response.sendRedirect(request.getContextPath()+"/RedirectSevlet2"); } }
public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String method = req.getParameter("method"); if (method.equals("add")){ //即 http://localhost:8080/hello_user?method=add req.getSession().setAttribute("msg","执行了add方法"); } if (method.equals("delete")){ //即 http://localhost:8080/hello_user?method=delete req.getSession().setAttribute("msg","执行了delete方法"); } //业务逻辑 //视图跳转或者去通过重定向 req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); } }
2.区分Restful混淆的方法就是用get post delete 等代替requestMapping 或者就是通过不同顺序不同名字
如:
@GetMapping("/deleteById/{id}")
和
@DeleteMapping("/deleteById/{id}")
和
@GetMapping("{id}/deleteById")
3.常用的前后联调,通过session拿到数据供服务层使用
@GetMapping("/findAllCart") public ModelAndView findAllCart(HttpSession session){ ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("settlement1"); User user = (User)session.getAttribute("user"); modelAndView.addObject("cartList",cartService.findAllCartVOByUserId(user.getId())); return modelAndView; }
或者这样通过注解的方式从cookies中拿到数据
@ResponseBody public SeckillResult<SeckillExecution> execute(@PathVariable("seckillId") Long seckillId, @PathVariable("md5") String md5, @CookieValue(value = "userPhone",required = false) Long userPhone )
4.RestFul风格的参数接收@PathVariable,和比较一下经典url的@RequestParam接收?name=xxx的风格
@Controller @RequestMapping("/User") public class UserController { @GetMapping("/t1") public String test1(@RequestParam("username") String name, Model model) { //1 如果前端传递的名字也是name 如:?name=xxx。那么就不用改变,如果是?usernamename=xxx就需要加@RequestParam相当于别名 //一般都加上RequestParam,因为一样不一样都可以加 如:@RequestParam("name")即可. System.out.println("接收到前端的参数为:"+name); //2 返回的结果传递给前端,model model.addAttribute("msg",name); // 3 视图跳转 return "test"; }
如果参数较多,则可以直接这样@RequestParam拿到所有的后缀参数,这样的缺点就是不太稳定,不太敢确保有没有某一参数,所以最好通过判断再拿到参数
@GetMapping({"/search", "/search.html"}) public String searchPage(@RequestParam Map<String, Object> params, HttpServletRequest request) { if (StringUtils.isEmpty(params.get("page"))) { params.put("page", 1); } params.put("limit", Constants.GOODS_SEARCH_PAGE_LIMIT); //封装分类数据 if (params.containsKey("goodsCategoryId") && !StringUtils.isEmpty(params.get("goodsCategoryId") + "")) { Long categoryId = Long.valueOf(params.get("goodsCategoryId") + ""); SearchPageCategoryVO searchPageCategoryVO = newBeeMallCategoryService.getCategoriesForSearch(categoryId); if (searchPageCategoryVO != null) { request.setAttribute("goodsCategoryId", categoryId); request.setAttribute("searchPageCategoryVO", searchPageCategoryVO); } } //封装参数供前端回显 if (params.containsKey("orderBy") && !StringUtils.isEmpty(params.get("orderBy") + "")) { request.setAttribute("orderBy", params.get("orderBy") + ""); }