• JAVA 框架 springmvc controller的返回值


    一、返回值:ModleView对象。

    使用modelAndView.setViewName设置返回的页面。使用modelAndView.addObject设置返回的数据。

    1     @RequestMapping("/edit")
    2     public ModelAndView editTable(HttpServletRequest request){
    3         ModelAndView modelAndView=new ModelAndView();
    4         String id=request.getParameter("id");
    5         goods goodser= this.goodsService.findByIdSer(Integer.parseInt(id));
    6         modelAndView.setViewName("edit");
    7         modelAndView.addObject("goods",goodser);
    8         return modelAndView;
    9     }

     二、返回值:字符串

    字符串为页面名称除去扩展名

    1     @RequestMapping("/edit")
    2     public String editTable(HttpServletRequest request,Model model){
    3         String id=request.getParameter("id");
    4         goods goodser= this.goodsService.findByIdSer(Integer.parseInt(id));
    5         model.addAttribute("goods",goodser);
    6         return "edit";
    7     }

    三、返回值:void

    通过参数httpservletrequest来确定设置返回值,通过request 设置值和转发。

    1     @RequestMapping("/edit")
    2     public void editTable(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    3         String id=request.getParameter("id");
    4         goods goodser= this.goodsService.findByIdSer(Integer.parseInt(id));
    5         request.setAttribute("gooods",goodser);
    6         request.getRequestDispatcher("WEB-INF/jsp/success.jsp").forward(request,response);
    7     }

     四:转发

    通过return  forward:*.action 方式进行转发,通过Model设置数据。绝对路径是带有/

    1     @RequestMapping("/update")
    2     public String upddateById(goods goods,Model model){
    3         this.goodsService.updateById(goods);
    4         model.addAttribute("id",goods.getId());
    5     return  "forward:edit.action";
    6     }

    绝对路径写法:根据需求来适用绝对路径和相对路径。

    1    @RequestMapping("/update")
    2     public String upddateById(goods goods,Model model){
    3         this.goodsService.updateById(goods);
    4         model.addAttribute("id",goods.getId());
    5     return  "redirect:/goods/edit.action";
    6     }

    注意这里需要带上扩展名.action

    url没发生变化。

    五、重定向:

    通过return "redirect:*.action"  通过Model设置数据。绝对路径是带有/。

    1     @RequestMapping("/update")
    2     public String upddateById(goods goods,Model model){
    3         this.goodsService.updateById(goods);
    4         model.addAttribute("id",goods.getId());
    5     return  "redirect:edit.action";
    6     }

     url发生变化。

    Modle 底层也是通过request.setAttribute来设置属性,但是对request上做了更好的封装,无论是转发还是重定向都可以设置值。

  • 相关阅读:
    设置一个字符串中的个别字符的特殊格式
    在代码中设置字体加粗的方法
    删除字符串中某字符
    xib下这种方式创建cell
    UILabel 字体下方加下划线
    iPhone4 8.3 系统下字体下方去除下划线
    elasticsearch 深入 —— normalizer
    elasticsearch 基础 —— Common Terms Query常用术语查询
    elasticsearch 基础 —— Jion父子关系
    elasticsearch 深入 —— Top Hits Aggregation
  • 原文地址:https://www.cnblogs.com/evilliu/p/8980423.html
Copyright © 2020-2023  润新知