zoukankan      html  css  js  c++  java
  • SpringMVC中 controller方法返回值

    1)ModelAndView      

    @RequestMapping(value="/itemEdit")
    public ModelAndView itemEdit(){
       //创建模型视图对象
       ModelAndView modelAndView = new ModelAndView();
            
       modelAndView.addObject("username", "张三");//指定页面返回的数据
       modelAndView.setViewName("test");//设置返回的视图名称
            
       return modelAndView;   
    }

    2)String(推荐使用)

    1) 返回普通字符串,就是页面去掉扩展名的名称, 返回给页面数据通过Model来完成

    @RequestMapping(value="/test1")
    public String test1(Model model){
    //添加数据 model.addAttribute("username", "李四"); model.addAttribute("address", "福州晋安区");
    return "test"; }

    2) forward: 请求转发,存入到model中的数据, 转发的方法响应的页面可以直接取出${username}--${address}

    @RequestMapping(value="/test2")
     public String test2(Model model){
         //添加数据,请求转发携带的数据
         model.addAttribute("username", "李四");
         model.addAttribute("address", "福州晋安区");
            
         //请求转发到另一个方法
         return "forward:index";//相对路径
         //return "forward:/test/index"; //绝对路径,"/"代表从项目名开始
    }
    
    @RequestMapping(value="/index")
    public String index(){
        return "test";
    }

    页面

    <body>
          <!--页面显示: 李四--福州晋安区-->
           ${username}--${address} 
    </body>

    3) redirect: 重定向

    @RequestMapping("/testRedirect")
    public String testRedirect(Model model){
            
        //添加数据
        model.addAttribute("username", "jack");
        model.addAttribute("address", "美国纽约");
            
        //重定向
        return "redirect:index";
    }
    
    //http://localhost:8080/crm0618/test/index?username=jack&address=美国纽约 @RequestMapping(value="/index") public String index(HttpServletRequest request) throws UnsupportedEncodingException{
    String username
    = request.getParameter("username"); String address = new String(request.getParameter("address").getBytes("iso8859-1"), "utf-8"); return "test"; }

    3)返回void(使用它破坏了springMvc的结构,所以不建议使用)

    可以使用request.setAttribut 来给页面返回数据
    可以使用request.getRquestDispatcher().forward()来指定返回的页面
    如果controller返回值为void则不走springMvc的组件,所以要写页面的完整路径名称

    @RequestMapping("/testRequest")
    public void testRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //将数据存入到request域中
        request.setAttribute("username", "make");
        request.setAttribute("address", "芝加哥");
            
        request.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(request, response);;
    }



  • 相关阅读:
    leetcode 131. Palindrome Partitioning
    leetcode 526. Beautiful Arrangement
    poj 1852 Ants
    leetcode 1219. Path with Maximum Gold
    leetcode 66. Plus One
    leetcode 43. Multiply Strings
    pytorch中torch.narrow()函数
    pytorch中的torch.repeat()函数与numpy.tile()
    leetcode 1051. Height Checker
    leetcode 561. Array Partition I
  • 原文地址:https://www.cnblogs.com/guo-rong/p/9199511.html
Copyright © 2011-2022 走看看