Spring MVC(学习笔记四)控制器的注解(三) -之处理方法的返回值配置

Handler Methods(处理方法)
2,返回值的配置操作
类名:HandlerMethodReturnController(访问路径:/hmrc)
@ResponseBody  String
 加上该注解表示现在返回的值就是"123"字符串,不在是一个试图;当然也可以返回一个json对象
@GetMapping(value = "grb")
@ResponseBody
public String getRequestBody(){
    return "123";
}
HttpEntity<B>,ResponseEntity<B>
 B为实体类,实例中我用来User类实体,字段有(id,name,pwd)
@GetMapping(value = "rrb")
    public ResponseEntity<User> returnResponseBody(String reponseType){

    User user=new User();
    user.setName("you");
    user.setPwd("123");

    //准备响应头部信息(content-type:xml)
    HttpHeaders httpHeaders=new HttpHeaders();
    httpHeaders.add(HttpHeaders.CONTENT_TYPE,reponseType);

    ResponseEntity<User> userResponseEntity=new ResponseEntity<User>(user,httpHeaders, HttpStatus.OK);
    return userResponseEntity;
}
HttpHeaders
View
这个时候如果在渲染页面的过程中模型的话,就会给处理器方法定义一个模型参数,然后在方法体里面往模型中添加值。
Map,Model
@RequestMapping(method=RequestMethod.GET)
public Map<String, String> index(){
    Map<String, String> map = new HashMap<String, String>();
    map.put("1", "1");
    //map.put相当于request.setAttribute方法
    return map;
}
@ModelAttribute
ModelAndView object
 用来返回数据模型和视图
@GetMapping(value = "gmav")
public ModelAndView getModelAndView(){
    ModelAndView modelAndView=new ModelAndView();
    modelAndView.addObject("testModelAndView","testModelAndView");
    modelAndView.setViewName("index");
    return modelAndView;
}
void
1,如果没有使用servletapi进行跳转,那么默认会将请求名作为试图名进行跳转。
@RequestMapping("/login")
    public void login(User user){
}
2,在参数中使用了servletapi,并且在方法中使用servletapi进行了跳转。那么按照servletapi跳转的位置进行跳转。
@RequestMapping("/login")
public void login(HttpServletRequest req,HttpServletResponse resp){
    try {
        req.getRequestDispatcher("success.jsp").forward(req, resp);
    } catch (ServletException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}


猜你喜欢

转载自blog.csdn.net/qq_40594137/article/details/79244667