文章目录
提示:以下是本篇文章正文内容,下面案例可供参考
一、数据响应方式
1.页面跳转
1.1直接返回字符串
此种方式会将返回的字符串与视图解析器的前后缀拼接后跳转
@RequestMapping("/quick")
public String quickMethod(//HttpServletRequest request){
//向request域存储数据
//request.setAttribute("name","zhangsan");
return "index";
}
//转发:forward:/WEB-INF/views/index.jsp
//重定向:redirect:/index.jsp
1.2通过ModelAndView对象
@RequestMapping("/quick2")
public ModelAndView quickMethod2(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("redirect:index.jsp");
向request域存储数据
//modelAndView.addObject("name","lisi");
return modelAndView;
}
2.回写数据
2.1直接返回字符串
- 通过SpringMVC框架注入的response对象
//不需要视图跳转,业务方法返回值为void
@RequestMapping("/quick4")
public void quickMethod4(HttpServletResponse response) throws IOException {
response.getWriter().print("hello world");
}
- 回写的字符串直接返回
//通过@ResponseBody注解告知SpringMVC框架,方法返回的字符串不是跳转是直接在http响应体中返回
@RequestMapping("/quick5")
@ResponseBody
public String quickMethod5() throws IOException {
return "hello springMVC!!!";
}
2.2返回对象或集合
- 配置注解驱动
//前提:mvc命名空间(略)
<!--mvc的注解驱动-->
<mvc:annotation-driven/>
/*作用
在 SpringMVC 的各个组件中,处理器映射器、处理器适配器、视图解析器称为 SpringMVC 的三大组件。
使用<mvc:annotation-driven>自动加载 RequestMappingHandlerMapping(处理映射器)和
RequestMappingHandlerAdapter( 处 理 适 配 器 ),可用在Spring-xml.xml配置文件中使用
<mvc:annotation-driven>替代注解处理器和适配器的配置。
同时使用<mvc:annotation-driven>默认底层就会集成jackson进行对象或集合的json格式字符串的转换。
*/
/*代替了在方法上添加@ResponseBody和如下配置
<bean class="org.springframework.web.servlet.mvc.method.annotation
.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json
.MappingJackson2HttpMessageConverter">
</bean>
</list>
</property>
</bean>
- 代码示例
@RequestMapping("/quick8")
@ResponseBody
public User quickMethod8() throws IOException {
User user = new User();
user.setUsername("zhangsan");
user.setAge(18);
return user;
}
二、获得请求数据
1.基本类型参数
- Controller中的业务方法的参数名称要与请求参数的name一致,参数值会自动映射匹配
http://localhost:8080/itheima_springmvc1/quick9?username=zhangsan&age=12
@RequestMapping("/quick9")
@ResponseBody
public void quickMethod9(String username,int age) throws IOException {
System.out.println(username);
System.out.println(age);
}
2.POJO类型参数
- Controller中的业务方法的POJO参数的属性名与请求参数的name一致,参数值会自动映射匹配
http://localhost:8080/itheima_springmvc1/quick9?username=zhangsan&age=12
public class User {
private String username;
private int age;
getter/setter…
}
@RequestMapping("/quick10")
@ResponseBody
public void quickMethod10(User user) throws IOException {
System.out.println(user);
}
3.数组类型参数
- Controller中的业务方法数组名称与请求参数的name一致,参数值会自动映射匹配
http://localhost:8080/itheima_springmvc1/quick11?strs=111&strs=222&strs=333
@RequestMapping("/quick11")
@ResponseBody
public void quickMethod11(String[] strs) throws IOException {
System.out