1、Spring-mvc.xml中配置视图解析
<!-- 配置视图解析 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 视图名前缀 -->
<property name="prefix" value="/jsp/"></property>
<!-- 视图名后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>
2、返回视图以及返回信息的几种实现方式
@RequestMapping("/quick1")
public String Test1(HttpServletRequest request) {
request.setAttribute("username", "HttpServletRequest");
return "ok";
}
@RequestMapping("/quick2")
public String Test2(Model model) {
model.addAttribute("username", "Model");
return "ok";
}
@RequestMapping("/quick3")
public ModelAndView Test3(ModelAndView modelAndView) {
modelAndView.addObject("username", "ModelAndView");
modelAndView.setViewName("ok");
return modelAndView;
}
@RequestMapping("/quick4")
public ModelAndView Test4() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("username", "ModelAndView");
modelAndView.setViewName("ok");
return modelAndView;
}
3、Spring-Mvc.xml中配置处理器映射
<!-- 对象转json 配置处理器映射-->
<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">-->
<!-- <property name="messageConverters">-->
<!-- <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>-->
<!-- </property>-->
<!-- </bean>-->
<mvc:annotation-driven/>
4、返回内容实现方式:
@RequestMapping("/quick5")
@ResponseBody
public void Test5(HttpServletResponse response) throws IOException {
response.getWriter().println("HttpServletResponse");
}
@RequestMapping("/quick6")
@ResponseBody
public String Test6() {
return "Hello Word Spring MVC";
}
@RequestMapping("/quick7")
@ResponseBody
public String Test7() throws JsonProcessingException {
UserInfo userInfo = new UserInfo();
userInfo.setId(1);
userInfo.setUserName("zhangsan");
userInfo.setPassword("123456");
ObjectMapper objectMapper = new ObjectMapper();
String s = objectMapper.writeValueAsString(userInfo);
return s;
}
@RequestMapping("/quick8")
@ResponseBody
public UserInfo Test8() {
UserInfo userInfo = new UserInfo();
userInfo.setId(1);
userInfo.setUserName("zhangsan");
userInfo.setPassword("123456");
return userInfo;
}