“程序员必备小知识”
返回字符串的形式
直接返回字符串,将字符串视图解析器的前后缀拼接跳转
@RequestMapping("quick")
public String quickMethod(){
return "index";
}
//以下为spring-mvc.xml配置
<!--配置内部资源视图解析器-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- /jsp/success.jsp -->
<property name="prefix" value="/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
转发的资源地址:/jsp/index.jsp
返回视图(ModelAndView)对象
函数内创建ModelAndView对象,添加模型数据和视图名称
@RequestMapping(value="/quick2")
public ModelAndView save2(){
/*
Model:模型 作用封装数据
View:视图 作用展示数据
*/
ModelAndView modelAndView = new ModelAndView();
//设置模型数据
modelAndView.addObject("username","ll");
//设置视图名称
modelAndView.setViewName("success");
return modelAndView;
}
通过SpringMVC框架注入ModelAndView对象
@RequestMapping(value="/quick3")
public ModelAndView save3(ModelAndView modelAndView){
modelAndView.addObject("username","ll");
modelAndView.setViewName("success");
return modelAndView;
}
向request中存储数据
最简单的方法就是通过SpringMVC框架的request对象色图Attribute()方法设置
@RequestMapping(value="/quick5")
public String save5(HttpServletRequest request){
request.setAttribute("username","ll");
return "success";
}
回写数据
直接返回字符串
通过SpringMVC框架注入的response对象,使用response.getWriter().print(“hello world”) 回写数据,此时不需要视图跳转,业务方法返回值为void。
@RequestMapping(value="/quick6")
public void save6(HttpServletResponse response) throws IOException {
response.getWriter().print("hello world");
}
将需要回写的字符串直接返回,但此时需要通过@ResponseBody注解告知SpringMVC框架,方法返回的字符串不是跳转是直接在http响应体中返回
@RequestMapping(value="/quick7")
@ResponseBody //告知SpringMVC框架 不进行视图跳转 直接进行数据响应
public String save7() throws IOException {
return "hello itheima";
}
在异步项目中,客户端与服务器端往往要进行json格式字符串交互,此时我们可以手动拼接json字符串返回。
@RequestMapping(value="/quick8")
@ResponseBody
public String save8() throws IOException {
return "{\"username\":\"zhangsan\",\"age\":18}";
}
上述方式手动拼接json格式字符串的方式很麻烦,开发中往往要将复杂的java对象转换成json格式的字符串,我们可以使用web阶段学习过的json转换工具jackson进行转换,导入jackson坐标。
@RequestMapping(value="/quick9")
@ResponseBody
public String save9() throws IOException {
User user = new User();
user.setUsername("lisi");
user.setAge(30);
//使用json的转换工具将对象转换成json格式字符串在返回
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(user);
return json;
}
返回对象或集合
通过SpringMVC帮助我们对对象或集合进行json字符串的转换并回写,为处理器适配器配置消息转换参数,指定使用jackson进行对象或集合的转换,因此需要在spring-mvc.xml中进行如下配置:
在方法上添加@ResponseBody就可以返回json格式的字符串,但是这样配置比较麻烦,配置的代码比较多,因此,我们可以使用mvc的注解驱动代替上述配置。
在 SpringMVC 的各个组件中,处理器映射器、处理器适配器、视图解析器称为 SpringMVC 的三大组件。 使用mvc:annotation-driven自动加载 RequestMappingHandlerMapping(处理映射器)和 RequestMappingHandlerAdapter( 处 理 适 配 器 ),可用在Spring-xml.xml配置文件中使用 mvc:annotation-driven替代注解处理器和适配器的配置。 同时使用mvc:annotation-driven默认底层就会集成jackson进行对象或集合的json格式字符串的转换。