SpringMVC 请求转发和重定向

1. SpringMVC 请求转发 和 重定向

springMVC 请求转发 只需要在 返回结果前加上forward:/

重定向同理:只需要加上 redirect:/

@Controller
public class TestController {


    @RequestMapping("requestForward")
    public String testRequestForward(){

        return "forward:/forward.jsp";

    }


    @RequestMapping("responseRedirect")
    public String testResponseRedirect(){

        return "redirect:/redirect.jsp";

    }
}

2.SpringMvc View视图 返回 重定向和请求转发

  @RequestMapping("viewrequestForward")
    public View requestForwardView(){
        View view;
        view = new InternalResourceView("/forward.jsp");
        return view;
    }


    @RequestMapping("viewresponseRedict")
    public View responseRedictView(HttpServletRequest request,HttpServletResponse response){
        View view;
        view = new RedirectView(request.getContextPath() + "/redirect.jsp");
        return view;
    }

3. spring MVC 返回 ModelAndView

 @RequestMapping("modelAndView")
    public ModelAndView modelAndViewForwardView(){
        ModelAndView view = new ModelAndView();
//        view.setView(new InternalResourceView("/froward.jsp"));
        view.setViewName("forward:/forward.jsp");
        return view;
    }

4. 响应json 数据

  1. 添加jackson databinding maven 库
  2. 在方法上 @ResponseBody 表明返回值不经过视图解析器处理,直接返回
 @ResponseBody
    @RequestMapping("testJson")
    public Pet testAjax(){
       Pet pet = new Pet("Tom","cat");
       return pet;
    } 

你可能感兴趣的:(Java,后端,java,mvc,前端)