支持的常见的几种参数类型
HttpServletRequest:提供的默认支持绑定的类型
HttpServletResponse
Model
java对象,包括基本类型、pojo
常见的返回类型
ModelAndView 基本不使用
void
String 使用多一些
Map 使用多一些
测试这几种参数类型
写一个controller,测试:
package com.cbb.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@RequestMapping("two")
@Controller
public class TwoController {
/**
* 方法描述:默认支持绑定的数据类型:HttpServletRequest和HttpServletResponse
* @param request
* @param response
* @return
*/
@RequestMapping("hello01")
public ModelAndView hello01(HttpServletRequest request,HttpServletResponse response) {
ModelAndView mv = new ModelAndView();
String name = request.getParameter("name");//获取请求参数信息
mv.addObject("msg",name);
mv.setViewName("user");
return mv;
}
}
返回类型为void,实现转发
/**
* 方法描述:返回类型为 void :进行转发实验
* @param request
* @param response
* @throws IOException
* @throws ServletException
*/
@RequestMapping("hello02")
public void hello02(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/first/one.do").forward(request, response);
//转发前面加“/”意思是到根目录
}
返回类型为void,实现重定向
/**
* 方法描述:返回类型为void 进行重定向
* @param response
* @throws ServletException
* @throws IOException
*/
@RequestMapping("hello03")
public void hello03(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
response.sendRedirect(request.getContextPath()+"/first/one.do");
//如果只有“first/one.do”,他就会在当前的路径下,也就是localhost:8080/springmvc/two之后再加上first/one.do
//如果是“/first/one.do”,他就会只有localhost:8080,然后在后面添加/first/one.do,把应用路径干掉了。
//所以只能是上面的这种格式
}
返回值类型为String 实现转发,重定向,通过返回一个字符串。
所以更简单的实现了转发和重定向
/**
* 方法描述:返回值类型为String 支持转发 foward:
* 支持重定向 redirect
* @return
*/
@RequestMapping("hello04")
public String hello04() {
return "forward:/first/one.do";
}
@RequestMapping("hello05")
public String hello05() {
return "redirect:/first/two.do";//站内的
}
ps:转发和重定向之后的请求类型
重定向第二次请求的类型为get类型的
转发的请求类型和发出的请求类型一致
返回正常字符串
/**
* 方法描述:返回类型为字符串(一个普通字符串)
* 会被作为逻辑视图名被视图解析器进行解析
* @return
*/
@RequestMapping("hello06")
public String hello06() {
return "user";
}
也就是说他会跳到一个user.jsp页面上
String的作用 1、作为视图名进行解析 2、转发 3、重定向
map作为返回值类型可以与json放在后面讲,
java对象作为重点也放在后面的数据注入里面讲,
我们接下来将Model作为参数类型的方式
/**
* 方法描述:默认支持绑定的参数类型 :Model。可以将数据填充到request域对象中
* @param model
* @return
*/
@RequestMapping("hello07")
public String hello07(Model model) {
model.addAttribute("msg","通过model设置的数据");
return "user";
}
因为string作为返回值类型可以直接跳转到那个页面所以根据这个特性,我们只需要再将model传过去,就可以实现正常的mv。
所以,如下即可实现。也是参数为model类型的例子
本次内容如上
END