Controller_vs_RestController

Controller注解 返回值类型:

  1. ModelAndView
    页面和数据整合的类型,使用模版引擎时可使用这种方式
  2. void
    此时,可以进行forward转发,request.getRequestDispatcher(“forwardUrl”).forward(request, response)(页面url不变)
    也可以进行redirect重定向,response.sendRedirect(“redirectUrl”) (页面url会跳转)
    还可以通过response.getWriter.write()直接返回页面数据
  3. String
    Controller注解下,返回字符串默认是逻辑视图名称,功能同返回ModelAndView
    也可以进行redirect重定向,response.sendRedirect(“redirectUrl”) (页面url会跳转),此时返回值无用
    还可以进行forward转发,request.getRequestDispatcher(“forwardUrl”).forward(request, response)(页面url不变),此时返回值无用
  4. 任意数据类型 + ResponseBody注解
    此时将返回值按照返回类型进行json解析,并返回json数据
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
@Controller
@RequestMapping(path = "/hehe")
public class TestController {

@GetMapping(path = "test")
@ResponseBody
public String test(@RequestParam String name) {
return "HELLO " + name;
}

@GetMapping(path = "testvoid")
public void testVoid(HttpServletRequest request,
HttpServletResponse response,
@RequestParam String name) {
response.setCharacterEncoding ( "utf-8" );
response.setContentType ( "application/json; charset=utf-8" );
try {
response.getWriter ().write ( "response write data: " + name );
} catch (IOException e) {
e.printStackTrace ();
}
}

@GetMapping(path = "redirect1")
public String redirect1(@RequestParam String name) {
return "redirect:test?name=" + name;
}

@GetMapping(path = "redirect2")
public void redirect2(HttpServletRequest request,
HttpServletResponse response,
@RequestParam String name) {
try {
response.sendRedirect ( "/hehe/test?name=" + name );
} catch (IOException e) {
e.printStackTrace ();
}
}

@GetMapping(path = "redirect3")
public RedirectView redirect3(@RequestParam String name) {
return new RedirectView ( "/hehe/test?name=" + name );
}

@GetMapping(path = "forward1")
public String forward1(@RequestParam String name) {
return "forward:test";
}

@GetMapping(path = "forward2")
public void forward2(
HttpServletRequest request,
HttpServletResponse response,
@RequestParam String name) {
try {
request.getRequestDispatcher ( "/hehe/test" )
.forward ( request, response);
} catch (ServletException e) {
e.printStackTrace ();
} catch (IOException e) {
e.printStackTrace ();
}
}

}

RestController注解 相当于 Controller注解 + ResponseBody注解,会对返回值进行JSON化处理并直接返回数据

1
2
3
4
5
6
7
@RestController
public class TestRestController {
@RequestMapping("/rest")
public Map test() {
return new HashMap ( );
}
}
-------------本文结束感谢您的阅读-------------
Good for you!