1、在@RequestMapping中定义访问页面的URL模版,使用{}传入页面参数,使用@PathVariable 获取传入参数,
2)@RequestMapping("/start/{name}") 这个name 随便 啥都可以
public String start(@PathVariable("name") string name){ 反正和上面的对应
return 方法体里面就可以直接获得参数}
@RequestMapping(value="/adminList/{area}/{startDay}/{endDay}
{}中都表示参数
/* 接收参数getParameter()的时候:
* 如果地址栏/springmvc/hello.htm上面没有传递参数,那么当id为int型的时候会报错,当id为Integer的时候值为null
* 当地址栏为/springmvc/hello.htm?id=10的时候,action中有三种接收方式
* 1、String hello(@RequestParam(value = "userid") int id),这样会把地址栏参数名为userid的值赋给参数id,如果用地址栏上的参数名为id,则接收不到
* 2、String hello(@RequestParam int id),这种情况下默认会把id作为参数名来进行接收赋值
* 3、String hello(int id),这种情况下也会默认把id作为参数名来进行接收赋值
* 注:如果参数前面加上@RequestParam注解,如果地址栏上面没有加上该注解的参数,例如:id,那么会报404错误,找不到该路径
2、根据不同的Web请求方法,映射到不同的处理方法:
使用登陆页面作示例,定义两个方法分辨对使用GET请求和使用POST请求访问login.htm时的响应。可以使用处理GET请求的方法显示视图,使用POST请求的方法处理业务逻辑;
@Controller
public class LoginController {
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login() {
return "login";
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login2(HttpServletRequest request) {
String username = request.getParameter("username").trim();
System.out.println(username);
return "login2";
}
防止重复提交数据,可以使用重定向视图:
return "redirect:/login2"
3、可以传入方法的参数类型:
@RequestMapping(value = "login", method = RequestMethod.POST)
public String testParam(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
String username = request.getParameter("username");
System.out.println(username);
return null;
}
可以传入HttpServletRequest、HttpServletResponse、HttpSession,值得注意的是,如果第一次访问页面,HttpSession没被创建,可能会出错;
4、使用@RequestParam 注解获取GET请求或POST请求提交的参数;
获取Cookie的值:使用@CookieValue :
获取PrintWriter:
可以直接在Controller的方法中传入PrintWriter对象,就可以在方法中使用:
@RequestMapping(value = "login", method = RequestMethod.POST)
public String testParam(PrintWriter out, @RequestParam("username") String username) {
out.println(username);
return null;
5、可以把对象,put 入获取的Map对象中,传到对应的视图:
@RequestMapping(value = "login", method = RequestMethod.POST)
public String testParam(User user, Map model) {
model.put("user",user);
return "view";
}
在返回的view.jsp中,就可以根据key来获取user的值(通过EL表达式,${user }即可);
Controller中方法的返回值:
void:多数用于使用PrintWriter输出响应数据;
String 类型:返回该String对应的View Name;
任意类型对象:
返回ModelAndView:
自定义视图(JstlView,ExcelView):
拦截器(Inteceptors):
springmvc
最新推荐文章于 2024-11-19 22:56:42 发布