@RequestMapping修饰类
@RequestMapping("/springmvc")//此路径是相对于web应用根目录的路径 @Controller public class SpringMVCTest { private static final String SUCCESS = "success"; /** * @RequestMapping 除了修饰方法还可以修饰类 * 类定义处:提供初步的请求映射信息,相对于WEB应用的根目录 * 方法处:提供进一步的细分映射信息 * @return */ //此时请求应写为http://localhost:8080/SpringMVC/springmvc/testRequestMapping @RequestMapping("/testRequestMapping")//此路径是相对于类上面注解的路径 public String testRequestMapping() { System.out.println("testRequestMapping"); return SUCCESS;
为@RequestMapping指定请求方式
/** * 使用method来指定请求方式 * @return */ //此时通过http://localhost:8080/SpringMVC/springmvc/testMethod请求无效,必须为POST请求才响应 @RequestMapping(value="/testMethod", method=RequestMethod.POST) public String testMethod() { System.out.println("testMethod"); return SUCCESS; }
为@RequestMapping指定请求参数和请求头
//http://localhost:8080/SpringMVC/springmvc/testParamsAndHeaders?username=admin&age=10 这种方式HTTP Status 404 //http://localhost:8080/SpringMVC/springmvc/testParamsAndHeaders?username=admin&age=11 这种方式可以访问 @RequestMapping(value="testParamsAndHeaders", params={"username", "age!=10"}, headers={"Accept-Language=zh-CN,zh;q=0.8"}) public String testParamsAndHeaders() { return SUCCESS; }
@RequestMapping匹配Ant路径
//http://localhost:8080/SpringMVC/springmvc/testAntPath/aa/abc //@RequestMapping("/testAntPath/*/abc")//*表示任意字符 //http://localhost:8080/SpringMVC/springmvc/testAntPath/a/abc //@RequestMapping("/testAntPath/?/abc")//?表示任意一个字符 //http://localhost:8080/SpringMVC/springmvc/testAntPath/a/45/abc @RequestMapping("/testAntPath/**/abc")//**表示匹配多层路径 public String testAntPath() { System.out.println("testAntPath"); return SUCCESS; }
@RequestMapping的@PathVariable注解
/** * @PathVariable映射URL中的占位符到目标方法的参数中 * @param id * @return */ //http://localhost:8080/SpringMVC/springmvc/testPathVariable/45 @RequestMapping("/testPathVariable/{id}") public String testPathVariable(@PathVariable("id") Integer id){ System.out.println("testPathVariable:" + id); return SUCCESS; }
使用HiddenHttpMethodFilter实现REST风格URL
首先在web.xml中加入filter的配置
HiddenHttpMethodFilter org.springframework.web.filter.HiddenHttpMethodFilter HiddenHttpMethodFilter /*
页面请求如下
Test Rest Get
处理请求的方法如下
/** * Rest风格的URL * 新增:/order POST * 修改:/order/1 PUT * 获取:/order/1 GET * 删除:/order/1 DELETE * */ @RequestMapping(value="/testRest/{id}", method=RequestMethod.PUT) public String testRestPut(@PathVariable Integer id) { System.out.println("testRest Put:" + id); return SUCCESS; } @RequestMapping(value="/testRest/{id}", method=RequestMethod.DELETE) public String testRestDelete(@PathVariable Integer id) { System.out.println("testRest DELETE:" + id); return SUCCESS; } @RequestMapping(value="/testRest", method=RequestMethod.POST) public String testRestPost() { System.out.println("testRest POST"); return SUCCESS; } @RequestMapping(value="/testRest/{id}", method=RequestMethod.GET) public String testRestGet(@PathVariable Integer id) { System.out.println("testRest Get:" + id); return SUCCESS; }
使用@RequestParam来映射请求参数
@RequestMapping(value="/testRequestParam") public String testRequestParam(@RequestParam(value="username") String username, @RequestParam(value="age", required=false, defaultValue="0")int age) { System.out.println("username:" + username + ",age:" + age); return SUCCESS; }
请求URL如下
http://localhost:8080/SpringMVC/springmvc/testRequestParam?username=admin&age=12
由于配置了required=false,以下的请求也有效
http://localhost:8080/SpringMVC/springmvc/testRequestParam?username=admin
使用@RequestHeader获取请求头信息
@RequestMapping(value="/testRequestHeader") public String testRequestHeader(@RequestHeader(value="Accept-Language") String al) { System.out.println("Accept-Language:" + al); return SUCCESS; }
请求URL:http://localhost:8080/SpringMVC/springmvc/testRequestHeader
打印信息:Accept-Language:zh-CN,zh;q=0.8
使用@CookieValue注解
@RequestMapping(value="/testCookieValue") public String testCookieValue(@CookieValue("JSESSIONID") String sessionId) { System.out.println("JSESSIONID:" + sessionId); return SUCCESS; }
请求URL:http://localhost:8080/SpringMVC/springmvc/testCookieValue
打印信息:JSESSIONID:23F73DE9E0A13ED7F171A16BDF151E98
使用POJO对象绑定请求参数值,支持级联属性
页面表单如下
实体类如下
public class User { private String username; private String password; private String email; private int age; private Address address; //省略getter、setter、toString方法 }
public class Address { private String province; private String city; //省略getter、setter、toString方法 }
spring处理方法如下
/** * 使用POJO作为参数 * 支持级联属性 * @param user * @return */ @RequestMapping("/testPojo") public String testPojo(User user) { System.out.println("testPojo" + user); return SUCCESS; }
使用原生Servlet API
@RequestMapping("/testSrevletAPI") public void testSrevletAPI(HttpServletRequest request, HttpServletResponse response, Writer out) throws IOException { //支持的类型还有:HttpSession、java.security.Principal、Locale、InputStream、OutputStream、Reader、Writer System.out.println("HttpServletRequest:" + request + ",HttpServletResponse:" + response); out.write("testSrevletAPI"); // return SUCCESS; }
ModelAndView
@RequestMapping("/testModelAndView") public ModelAndView testModelAndView() { String viewName = SUCCESS;//视图名称 ModelAndView modelAndView = new ModelAndView(viewName); modelAndView.addObject("time", new Date()); return modelAndView; }
success.jsp中使用标签即可显示time的值
time:${requestScope.time}
--------------------------------
另一种方法如下
/** * 目标方法可以是Map(实际上也可以是Model类型或ModelMap类型)类型参数 * @param map * @return */ @RequestMapping("/testMap") public String testMap(Mapmap) { System.out.println(map.getClass().getName());//org.springframework.validation.support.BindingAwareModelMap map.put("names", Arrays.asList("Tom", "Jerry", "Mike")); return SUCCESS; }
success.jsp中使用标签显示names的值
names:${requestScope.names}
@SessionAttributes注解
@SessionAttributes(value={"user"}, types={String.class}) @RequestMapping("/springmvc")//此路径是相对于web应用根目录的路径 @Controller public class SpringMVCTest { private static final String SUCCESS = "success"; @RequestMapping("/testSessionAttributes") public String testSessionAttributes(Mapmap) { User user = new User("admin", "123", "[email protected]", 24); map.put("user", user); map.put("school", "ctgu"); return SUCCESS; } //..... }
这样写之后,将user和String类型的变量不仅放到了request里,而且还放到了session里
seccess.jsp中取值如下
request user:${requestScope.user}
session user:${sessionScope.user}
request school:${requestScope.school}
session school:${sessionScope.school}
@ModelAttribute用法
Spring处理如下
@ModelAttribute//此方法会在每个目标方法执行之前被SpringMVC调用 public void getUser( @RequestParam(value = "id", required = false) Integer id, Mapmap) { if (id != null) { // 模拟从数据库中获取对象 User user = new User(1, "admin", "123456", "[email protected]", 24); System.out.println("从数据库中获取对象:" + user); map.put("user", user);//对应@ModelAttribute("user") } } @RequestMapping("/testModelAttribute") public String testModelAttribute(@ModelAttribute("user") User user) { System.out.println("修改:" + user); return SUCCESS; }
控制台打印如下:
从数据库中获取对象:User [id=1, username=admin, password=123456, [email protected], age=24]
修改:User [id=1, username=Tom, password=123456, [email protected], age=25]