3、springMVC
3.4、SpringMVC的数据响应
3.4.1、页面跳转
(1)返回字符串形式
直接返回字符串:此种方式会将返回的字符串与视图解析器的前后缀拼接后进行跳转。
@RequestMapping("/quick4")
public String quickMethod4(Model model){
model.addAttribute("username","spongebob");
return "forward:/index.jsp";

返回带有前缀的字符串:
转发:forward:/WEB-INF/views/index.jsp
重定向:redirect:/index.jsp
(2)返回ModelAndView对象
@RequestMapping("/quick2")
public ModelAndView quickMethod2(){
/**
* model: 模型 作用封装数据
* view:视图 作用展示数据
*/
ModelAndView modelAndView = new ModelAndView();
//设置视图名称
modelAndView.setViewName("redirect:/index.jsp");
return modelAndView;
}
在进行转发时,往往要向request域中存储数据,在jsp页面中显示,那么Controller中怎样向request域中存储数据呢?
- (1)、通过SpringMVC框架注入的request对象
setAttribute()方法设置
@RequestMapping("/quick5")
public String quickMethod5(HttpServletRequest request){
request.setAttribute("username","awada");
return "success";
}
- (2)、通过
ModelAndView的addObject()方法设置
@RequestMapping("/quick3")
public ModelAndView quickMethod3(){
ModelAndView modelAndView = new ModelAndView();
//设置模型数据
modelAndView.addObject("username","spongebob");
/设置视图名称
modelAndView.setViewName("forward:/index.jsp");
return modelAndView;
}
3.4.2、回写数据
(1)直接返回字符串
Web基础阶段,客户端访问服务器端,如果想直接回写字符串作为响应体返回的话,只需要使用response.getWriter().print("hello world") 即可,那么在Controller中想直接回写字符串该怎样呢?
① 通过SpringMVC框架注入的response对象,使用response.getWriter().print("hello world")回写数据,此时不需要视图跳转,业务方法返回值为void。
@RequestMapping("/quick6")
public void quickMethod6(HttpServletResponse response) throws IOException {
response.getWriter().print("hello world");
}
②将需要回写的字符串直接返回,但此时需要通过@ResponseBody注解告知SpringMVC框架,方法返回的字符串不是跳转是直接在http响应体中返回。
@RequestMapping("/quick7")
@ResponseBody
public String quickMethod7() throws IOException {
return "hello springMVC!!!";
}
json字符串转换
在异步项目中,客户端与服务器端往往要进行json格式字符串交互,此时我们可以手动拼接json字符串返回。
@RequestMapping("/quick8")
@ResponseBody
public String quickMethod8() throws IOException {
return "{\"name\":\"zhangsan\",\"age\":18}";
}
上述方式手动拼接json格式字符串的方式很麻烦,开发中往往要将复杂的java对象转换成json格式的字符串,我们可以使用web阶段学习过的json转换工具jackson进行转换,导入jackson依赖。
<!--jackson-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
通过jackson转换json格式字符串,回写字符串。
@RequestMapping("/quick9")
@ResponseBody
public String quickMethod9() throws IOException {
User user = new User();
user.setUsername("zhangsan");
user.setAge(18);
ObjectMapper objectMapper = new ObjectMapper();
String s = objectMapper.writeValueAsString(user);
return s;
}

本文详细介绍了SpringMVC中数据响应和获取的方法,包括页面跳转、回写数据、请求数据的多种获取方式,如基本类型、POJO、数组和集合等。同时讲解了如何处理请求数据乱码问题、RestFul风格参数、自定义类型转换器以及文件上传等核心功能。
最低0.47元/天 解锁文章
654

被折叠的 条评论
为什么被折叠?



