SpringMVC之响应
返回字符串
返回字符串相当于返回视图名称,该视图名称经过视图解析器得到视图路径
@RequestMapping("/testString")
public String testString() {
System.out.println("testString()执行");
return "success";
}
返回void
默认行为:以方法名作为视图名称,经过视图解析器得到视图路径
@RequestMapping("/testVoid1")
public void testVoid1() {
System.out.println("testVoid1()执行");
}
通过HttpServletRequest请求转发,转发地址不走视图解析器:
@RequestMapping("/testVoid2")
public void testVoid2(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("testVoid2()执行");
req.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(req, resp);
}
通过HttpServletResponse重定向
@RequestMapping("/testVoid3")
public void testVoid3(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("testVoid3()执行");
// resp.sendRedirect("testVoid2");
resp.sendRedirect("/springmvc03/test1/testVoid2");
}
通过Response对象指定响应结果
@RequestMapping("/testVoid4")
public void testVoid4(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("testVoid4()执行");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
resp.getWriter().write("testVoid4");
}
返回ModelAndView
addObject(String, @Nullable Object):变量赋值,在jsp页面中通过requestScope取值
setViewName(String):设置视图名称
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("username", "张三");
modelAndView.setViewName("testModelAndView");
return modelAndView;
}
请求转发
@RequestMapping("/testForward")
public String testForward() {
System.out.println("testForward()执行");
return "forward:/WEB-INF/pages/success.jsp";
}
重定向
@RequestMapping("/testRedirect")
public String testRedirect() {
System.out.println("testRedirect()执行");
return "redirect:testString";
}
返回json
导入jackson类库:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.12.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.12.2</version>
</dependency>
@RequestMapping("/testJson")
public @ResponseBody User testJson(@RequestBody User user) {
System.out.println("testJson()执行");
System.out.println(user);
user.setUsername("张三丰");
return user;
}
浙公网安备 33010602011771号