spring mvc controller class return value

The return type is String 

The controller method returns a string that can specify the name of the logical view, which is resolved to the address of the physical view by the view resolver.
// Specify the name of the logical view, which is resolved to the jsp physical path by the view resolver: /WEB-INF/pages/success.jsp
/ * * 
     * Return String 
     * @param model 
     * @return 
     * / 
    @RequestMapping ( " / testString " )
     public String testString (Model model) { 
        System. Out .println ( " testString ... " ); 

        // Simulation from the database User object 
        = new User (); 
        user.setUsername ( " 美 美" ); 
        user.setPassword ( " 123 " ); 
        user.setAge ( 30 );
         // model object
        model.addAttribute("user",user);
        return "success";
    }

 

2. The return type is void

The original API of the Servlet can be used as the parameter of the method in the controller: so use the request and response of the original servlet as the parameter
 / * * 
     * Return void: If there is no return value and no jump, the default page is the request 
     path.jsp 
     * 
     * @param * / 
    @RequestMapping ( " / testVoid " )
     public  void testVoid (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
        System. Out .println ( " testVoid ... " );
         // Request forwarding
         // request.getRequestDispatcher ("/ WEB-INF / pages / success.jsp"). Forward (request, response); 

        / / Redirect: The content in WEB-INF cannot be directly requested
         // response.sendRedirect (request.getContextPath () + "/ index.jsp");

        // Direct 
        response.setCharacterEncoding ( " UTF-8 " ); 
        response.setContentType ( " text / html; charset = UTF-8 " ); 
        response.getWriter (). Print ( " Hello " );
         return ; 
    }

 

3. The return type is ModelAndView

ModelAndView is an object provided by SpringMVC for us, the object can also be used as the return value of the controller method.
@RequestMapping ( " / testModelAndView " )
     public ModelAndView testModelAndView () {
         // Create ModelAndView object 
        ModelAndView modelAndView = new ModelAndView (); 
        System. Out .println ( " testString ... " );
         // Simulate querying User from the database Object 
        User user = new User (); 
        user.setUsername ( " 美 美" ); 
        user.setPassword ( " 123 " ); 
        user.setAge ( 30 ); 

        //Store the user object in the mv object, and also store the user object in the request domain object 
        modelAndView.addObject ( " user " , user);
         // Which page to jump to, use the view resolver to parse 
        modelAndView.setViewName ( " success " ); 

        return modelAndView; 
    }

 

Guess you like

Origin www.cnblogs.com/zsben991126/p/12690663.html