二、springMVC之RequestMapping和绑定参数注解
一、概述:
配置方式:
同HelloWord的配置方式;
目录结构:
@RequestMapping:
@RequestMapping除了可以使用请求URL映射请求外,还可以使用请求方法、请求参数及请求头映射请求;
@RequestMapping的value、method、params及heads分别表示请求URL、请求方法、请求参数及请求头的映射条件,他们之间的与的关系,联合使用多个条件可让请求映射更加精确化。
修饰类
关于@RequestMapping除了修饰方法,还可用来修饰类 类定义处:提供初步的请求映射信息。
方法定义处:提供进一步的分映射信息。
类定义处标记的@RequestMapping 限定了处理器类可以处理所有URI为/springmvc的请求,它相对于WEB容器部署的根路径;
处理器类可以定义多个处理方法,处理来自/springmvc下的请求;
RequestMappingTest:
1 package handler; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 6 @RequestMapping("/springmvc") 7 @Controller 8 public class RequestMappingTest { 9 private static final String SUCCESS = "success"; 10 11 @RequestMapping("/testRequestMaping") 12 public String hello() { 13 System.out.println("testRequestMaping"); 14 return SUCCESS; 15 } 16 }
index.jsp:
a标签的herf 属性 为RequestMapping的 类的修改 和方法的修饰value的拼接;
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="true"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <a href="springmvc/testRequestMaping">hello</a> 11 </body> 12 </html>
success.jsp
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <h4>success</h4> 11 </body> 12 </html>
运行结果:
index页面点击 hello 跳转到 success.jsp页面 且控制台打印:testRequestMaping;
使用method属性来指定请求方式
RequestMapping(value="testMethod",method=RequestMethod.POST):
- value:指定URL
- method:指定请求方式
RequestMappingTest:
1 package handler; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 import org.springframework.web.bind.annotation.RequestMethod; 6 7 @RequestMapping("/springmvc") 8 @Controller 9 public class RequestMappingTest { 10 private static final String SUCCESS = "success"; 11 12 /** 13 * 14 * 常用:使用method属性来指定请求方式 15 * 16 * @return 17 */ 18 @RequestMapping(value = "/testMethod", method = RequestMethod.POST) 19 public String testMethod() { 20 System.out.println("testMethod"); 21 return SUCCESS; 22 } 23 }
index.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="true"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <form action="/springmvc/testMethod" method="POST"> 11 <input type="submit" value="post提交"> 12 </form> 13 </body> 14 </html>
success:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <h4>success</h4> 11 </body> 12 </html>
运行结果:
index页面点击post提交 跳转到 success.jsp页面 且控制台打印:testMethod;
使用params来更加精确的映射请求
params={"username", "age!=10","!dept"}参数说明:
- 请求参数中必须包含 username,username有没有值都没有关系;
- 请求参数必须包含age且age不等于10 age有没有都没关系,
- 请求参数不能包含dept;
RequestMappingTest:
1 package handler; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 6 @RequestMapping("/springmvc") 7 @Controller 8 public class RequestMappingTest { 9 private static final String SUCCESS = "success"; 10 11 /** 12 * 13 * 了解;可以使用params和headers来更加精确的映射请求 params和headers支持简单的表达式 14 * 15 * @return 16 */ 17 @RequestMapping(value = "/testParamsAndHeaders", params = { "username", "age!=10","!dept" }) 18 public String testParamsAndHeaders() { 19 System.out.println("testParamsAndHeaders"); 20 return SUCCESS; 21 } 22 }
index.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="true"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <a href="/springmvc/testParamsAndHeaders?username=李秀明&age=10">testParamsAndHeaders_username_age10</a> 11 <br> 12 <a href="/springmvc/testParamsAndHeaders?username=李秀明&age=11">testParamsAndHeaders_username_age11</a> 13 <br> 14 <a href="/springmvc/testParamsAndHeaders?username=李秀明&age=11&gender=1">testParamsAndHeaders_username_age11_gender</a> 15 <br> 16 <a href="/springmvc/testParamsAndHeaders?age=11&gender=1">testParamsAndHeaders_age11_gender</a> 17 <br> 18 </body> 19 </html>
success:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <h4>success</h4> 11 </body> 12 </html>
运行结果:
index.jsp的页面如下,
如果点击testParamsAndHeaders_username_age10,则显示错误信息;原因是age=10,而param中规定参数!=10;
如果点击testParamsAndHeaders_username_age11,则成功跳转到success 且 控制台打印testParamsAndHeaders;
如果点击testParamsAndHeaders_username_age11_gender,则成功跳转到success且 控制台打印testParamsAndHeaders;
如果点击testParamsAndHeaders_age11_gender,则显示错误信息;原因是没有username,而param中规定参数中有username,所以参数中必须带有username;
使用headers来更加精确的映射请求
RequestMappingTest:
1 package handler; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 6 @RequestMapping("/springmvc") 7 @Controller 8 public class RequestMappingTest { 9 private static final String SUCCESS = "success"; 10 11 @RequestMapping(value = "/testHeaders", headers = { "Accept-Language=zh-CN,zh;q=0.9" }) 12 public String testHeaders() { 13 System.out.println("testHeaders"); 14 return SUCCESS; 15 } 16 17 @RequestMapping(value = "/testHeaders/enus", headers = { "Accept-Language=en-US,zh;q=0.9" }) 18 public String testHeadersEnus() { 19 System.out.println("testHeaders"); 20 return SUCCESS; 21 } 22 }
index.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isErrorPage="true"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> <title>Insert title here</title> </head> <body> <a href="/springmvc/testHeaders">testHeaders</a> <br> <a href="/springmvc/testHeaders/enus">testHeaders_enus</a> <br> </body> </html>
success:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <h4>success</h4> 11 </body> 12 </html>
运行结果:
index.jsp 运行结果如下,当点击testHeaders ,跳转到 success.jsp页面 且控制台打印testHeaders,
点击testHeaders_enus 报错,原因是 headers = { "Accept-Language=en-US,zh;q=0.9" },与浏览器的Accept-Language不一致导致请求失败;
@RequestMapping URL支持Ant风格的请求(通配符)
- ?:匹配文件名中的一个字符:
- *:匹配文件名中的任意字符
- **:匹配多层路径;
RequestMappingTest:
1 package handler; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 6 @RequestMapping("/springmvc") 7 @Controller 8 public class RequestMappingTest { 9 private static final String SUCCESS = "success"; 10 11 @RequestMapping("/testAntPath/*/abc/dd/**/end?") 12 public String testAnt() { 13 System.out.println("testAnt"); 14 return SUCCESS; 15 } 16 }
index.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="true"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <a href="/springmvc/testAntPath/test/abc/dd/test/test/end11">testAnt</a> 11 </body> 12 </html>
success.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <h4>success</h4> 11 </body> 12 </html>
运行结果:
index.jsp 的运行效果如下图;点击testAnt,会出现错误,原因是/springmvc/testAntPath/test/abc/dd/test/test/end11 end11多了一个1,因为@RequestMapping("/testAntPath/*/abc/dd/**/end?") 且?匹配一个字符,这里end11 多了一个字符;所以不成功;把end11改为end1 ,再点击testAnt,会跳转到success 页面,且控制台打印:testAnt;
@PathVariable映射URL绑定的占位符到目标方法的参数中:
@RequestMapping url中的占位符,必须和@PathVariable中的值一致,@PathVariable中的值可以和参数值相同也可以不相同;
即 @RequestMapping("/testPathVariable/{id}/{name}");中的{id} 必须与@PathVariable("id") String id ,中的@PathVariable("id") 值相同;与String id 可以相同或者不相同。
RequestMappingTest:
1 package handler; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.PathVariable; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 7 @RequestMapping("/springmvc") 8 @Controller 9 public class RequestMappingTest { 10 private static final String SUCCESS = "success"; 11 12 @RequestMapping("/testPathVariable/{id}/{name}") 13 public String testPathVariable(@PathVariable("id") String id, @PathVariable("name") String names) { 14 System.out.println("testPathVariable id:" + id + ",name:" + names); 15 return SUCCESS; 16 } 17 }
index.jsp:
a标签中的占位符必须数量必须和@RequestMapping("/testPathVariable/{id}/{name}")中的数量一致,否则报错;
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="true"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <a href="/springmvc/testPathVariable/aaa/bb">testPathVariable</a> 11 </body> 12 </html>
success.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <h4>success</h4> 11 </body> 12 </html>
运行结果:
index.jsp显示如下;点击testPathVariable,跳转到success页面,同时控制台打印 testPathVariable id:aaa,name:bb
REST( Representational State Transfer )
说明:
State Transfer 为 "状态传输" 或 "状态转移 ",Representational 中文有人翻译为"表征"、"具象",合起来就是 "表征状态传输" 或 "具象状态传输" 或 "表述性状态转移"。可以理解为:(资源)表征状态传输;
- 资源:就是网络上的一个实体,换言之就是一个具体的信息。(如图片,文本。。。)可以用URI 指向它。URI为每一个资源识别符。
- 表征:可以理解为资源的传输形式(文本可以用 txt;可以用HTML;可以用JSON)。
- 状态转换:HTTP协议 无状态;如果客户需要操作服务器,必须通过某种手段,让服务器发生状态转换。http协议里面,4个表示操作的动词,GET、POST、PUT、DELETE。对应着 获取、新增、修改、删除。
示例:
- '/order/1 http get' 得到ID=1的order
- '/order http POST' 新增的order
- '/order/1 http PUT' 更新ID=1的order
- '/order/1 http DELETE' 删除ID=1的order
实例验证
为了实现put 和 delete的效果,web.xml中需要配置HiddenHttpMethodFilter ,可以把post请求转为delete or put请求 。
1 <!-- 配置HiddenHttpMethodFilter :可以把post请求转为delete or put请求 --> 2 3 <filter> 4 <filter-name>HiddenHttpMethodFilter</filter-name> 5 <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> 6 </filter> 7 <filter-mapping> 8 <filter-name>HiddenHttpMethodFilter</filter-name> 9 <url-pattern>/*</url-pattern> 10 </filter-mapping>
web.xml配置:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns="http://xmlns.jcp.org/xml/ns/javaee" 4 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" 5 version="4.0"> 6 <display-name>HelloWorld</display-name> 7 <!-- 配置DispatcherServlet(快捷键 alt +/) --> 8 <servlet> 9 <servlet-name>springDispatcherServlet</servlet-name> 10 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 11 <!-- 配置DispatcherServletd 一个初始化参数:配置springmvc配置文件的位置和名称 --> 12 <!-- 实际上也可以不通过 contextConfigLocation 来配置Springmvc的配置文件,而是用默认的 即默认的配置文件为 13 /WEB-INF/<servlet-name>-servlet.xml 本项目默认位置配置文件即为: /WEB-INF/springDispatcherServlet-servlet.xml --> 14 <init-param> 15 <param-name>contextConfigLocation</param-name> 16 <param-value>classpath:spring.xml</param-value> 17 </init-param> 18 <!-- 表示springDispatcherServlet在加载的时候被创建 --> 19 <load-on-startup>1</load-on-startup> 20 </servlet> 21 22 <!-- Map all requests to the DispatcherServlet for handling --> 23 <servlet-mapping> 24 <servlet-name>springDispatcherServlet</servlet-name> 25 <url-pattern>/</url-pattern> 26 </servlet-mapping> 27 28 <!-- 配置HiddenHttpMethodFilter :可以把post请求转为delete or put请求 --> 29 30 <filter> 31 <filter-name>HiddenHttpMethodFilter</filter-name> 32 <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> 33 </filter> 34 <filter-mapping> 35 <filter-name>HiddenHttpMethodFilter</filter-name> 36 <url-pattern>/*</url-pattern> 37 </filter-mapping> 38 39 </web-app>
RequestMappingTest:
1 package handler; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.PathVariable; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 import org.springframework.web.bind.annotation.RequestMethod; 7 8 @RequestMapping("/springmvc") 9 @Controller 10 public class RequestMappingTest { 11 private static final String SUCCESS = "success"; 12 13 @RequestMapping(value = "/testRest/{id}", method = RequestMethod.PUT) 14 public String testRestput(@PathVariable("id") Integer id) { 15 System.out.println("testRest-put:" + id); 16 return SUCCESS; 17 } 18 19 @RequestMapping(value = "/testRest/{id}", method = RequestMethod.DELETE) 20 public String testRestDelete(@PathVariable("id") Integer id) { 21 System.out.println("testRest-delete:" + id); 22 return SUCCESS; 23 } 24 25 @RequestMapping(value = "/testRest", method = RequestMethod.POST) 26 public String testRestPost() { 27 System.out.println("testRest post"); 28 return SUCCESS; 29 } 30 31 @RequestMapping(value = "/testRest/{id}", method = RequestMethod.GET) 32 public String testRestGet(@PathVariable("id") Integer id) { 33 System.out.println("testRest-get:" + id); 34 return SUCCESS; 35 } 36 }
index.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="true"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <a href="/springmvc/testRest/1">test rest get</a> 11 <br> 12 <form action="/springmvc/testRest" method="POST"> 13 <input type="submit" value="test rest post"> 14 </form> 15 <form action="/springmvc/testRest/1" method="POST"> 16 <input type="hidden" name="_method" value="DELETE"> <input 17 type="submit" value="test rest delete"> 18 </form> 19 <form action="/springmvc/testRest/1" method="POST"> 20 <input type="hidden" name="_method" value="PUT"> <input 21 type="submit" value="test rest put"> 22 </form> 23 </body> 24 </html>
success.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="true"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <h4>success</h4> 11 </body> 12 </html>
运行结果:
index.jsp运行效果如下图;
点击test rest get 跳转到success页面,同时控制台打印testRest-get:1;
点击test rest post跳转到success页面,同时控制台打印testRest post;
点击test rest delete跳转到success页面,同时控制台打印testRest-delete:1
点击test rest put跳转到success页面,同时控制台打印testRest-put:1;
绑定参数注解
使用@RequestParam绑定请求参数值:
在方法入参处使用@RequestParam 可以把请求参数传递给请求方法;
- value:表示请求参数的参数名
- required:是否必须,默认为true,请求参数中必须包含对应的参数,若不存在,将抛出异常;
- defaultvalue :参数默认值
http://localhost:8080/springmvc/tesRestParam?username=%E6%9D%8E%E7%A7%80%E6%98%8E&age=12中的username必须和@RequestParam(value = "username") String username中的@RequestParam(value="username")的一样;和String username 可以一样也可以不一样;
RequestMappingTest:
1 package handler; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 import org.springframework.web.bind.annotation.RequestParam; 6 7 @RequestMapping("/springmvc") 8 @Controller 9 public class RequestMappingTest { 10 private static final String SUCCESS = "success"; 11 12 /** 13 * @RequestParam来映射请求参数 value:请求参数名 required :是否必须 defaultvalue :参数默认值 14 * @return 15 */ 16 @RequestMapping("/tesRestParam") 17 public String tesRestParam(@RequestParam(value = "username") String username, 18 @RequestParam(value = "age", required = false, defaultValue = "0") int age) { 19 System.out.println("tesRestParam:username" + username + ".aget:" + age); 20 return SUCCESS; 21 } 22 }
index.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="false"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <a href="/springmvc/tesRestParam?username=李秀明&age=12">tesRestParam_username&age</a> 11 <br> 12 <a href="/springmvc/tesRestParam?username=李秀明">tesRestParam_username</a> 13 </body> 14 </html>
success.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="true"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <h4>success</h4> 11 </body> 12 </html>
运行结果:
index.jsp 运行如下图,点击tesRestParam_username&age 跳转到success,且控制台打印:tesRestParam:username李秀明.aget:12;点击tesRestParam_username 跳转到successtesRestParam:username李秀明.aget:0
@RequestHeader绑定请求报头属性值
请求头包含了若干个属性,服务器可据此货值客户端的信息。通过@RequestHeader可将请求头中的属性值绑定到处理方法的入参中
RequestMappingTest:
1 package handler; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestHeader; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 7 @RequestMapping("/springmvc") 8 @Controller 9 public class RequestMappingTest { 10 private static final String SUCCESS = "success"; 11 12 /** 13 * 用来映射请求头信息;用法同@RequestParam 14 * 15 * @return 16 */ 17 @RequestMapping("/tesRestHeader") 18 public String tesRestHeader(@RequestHeader(value = "Accept-Language") String al) { 19 System.out.println("tesRestHeader" + al); 20 return SUCCESS; 21 } 22 }
index.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="false"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <a href="/springmvc/tesRestHeader">tesRestHeader</a> 11 <br> 12 </body> 13 </html>
success.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="true"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <h4>success</h4> 11 </body> 12 </html>
运行结果: 点击testRestHeader 跳转到success页面,且控制台打印:tesRestHeaderzh-CN,zh;q=0.9
@CookieValue绑定请求报头属性值
通过@CookieValue可让处理方法入参绑定某个Cookie值;用法同@RequestParam
RequestMappingTest:
1 package handler; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.CookieValue; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 7 @RequestMapping("/springmvc") 8 @Controller 9 public class RequestMappingTest { 10 private static final String SUCCESS = "success"; 11 12 /** 13 * @CookieValue映射一个cookie值;用法同@RequestParam 14 * 15 * @return 16 */ 17 @RequestMapping("/testCookieValue") 18 public String testCookieValue(@CookieValue(value = "JSESSIONID") String JSESSIONID) { 19 System.out.println("testCookieValue" + JSESSIONID); 20 return SUCCESS; 21 } 22 }
index.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="false"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <a href="/springmvc/testCookieValue">testCookieValue</a> 11 </body> 12 </html>
success.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="true"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <h4>success</h4> 11 </body> 12 </html>
运行结果:
index.jsp运行结果如下图;点击testCookieValue跳转到success页面,且控制台打印testCookieValue6458E41FB8EEF62E6A52F7612D1936D7
使用POJO对象绑定请求参数值;
springMVC 会按照请求参数名和POJO属性名进行自动匹配,自动为该对象填充属性。支持级联属性。如dept.deptId、dept.address.tel。。。
添加两个实体类User.java 和 address.java
User.java
1 package entity; 2 3 public class User { 4 private String userName; 5 private int age; 6 private Address address; 7 8 public String getUserName() { 9 return userName; 10 } 11 12 public void setUserName(String userName) { 13 this.userName = userName; 14 } 15 16 public int getAge() { 17 return age; 18 } 19 20 public void setAge(int age) { 21 this.age = age; 22 } 23 24 public Address getAddress() { 25 return address; 26 } 27 28 public void setAddress(Address address) { 29 this.address = address; 30 } 31 32 @Override 33 public String toString() { 34 return "User [userName=" + userName + ", age=" + age + ", address=" + address + "]"; 35 } 36 37 }
address.java
1 package entity; 2 3 public class Address { 4 private String province; 5 private String city; 6 7 public String getProvince() { 8 return province; 9 } 10 11 public void setProvince(String province) { 12 this.province = province; 13 } 14 15 public String getCity() { 16 return city; 17 } 18 19 public void setCity(String city) { 20 this.city = city; 21 } 22 23 @Override 24 public String toString() { 25 return "Address [province=" + province + ", city=" + city + "]"; 26 } 27 28 }
web.xml添加编码配置,防止form表单提交 控制台打印乱码(这里的方式是设定post 请求体的编码格式;如果是git请求参数乱码,则需要设置服务器的编码格式):
该段代码配置在web.xml其他过滤器前面,否则无效;
参考解决方式:https://www.cnblogs.com/lixiuming521125/p/14697014.html#_label4
1 <filter> 2 <filter-name>CharacterEncodingFilter</filter-name> 3 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 4 <init-param> 5 <param-name>encoding</param-name> 6 <param-value>utf-8</param-value> 7 </init-param> 8 </filter> 9 <filter-mapping> 10 <filter-name>CharacterEncodingFilter</filter-name> 11 <url-pattern>/*</url-pattern> 12 </filter-mapping>
完整内容:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns="http://xmlns.jcp.org/xml/ns/javaee" 4 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" 5 version="4.0"> 6 <display-name>HelloWorld</display-name> 7 <filter> 8 <filter-name>CharacterEncodingFilter</filter-name> 9 <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> 10 <init-param> 11 <param-name>encoding</param-name> 12 <param-value>utf-8</param-value> 13 </init-param> 14 </filter> 15 <filter-mapping> 16 <filter-name>CharacterEncodingFilter</filter-name> 17 <url-pattern>/*</url-pattern> 18 </filter-mapping> 19 <!-- 配置DispatcherServlet(快捷键 alt +/) --> 20 <servlet> 21 <servlet-name>springDispatcherServlet</servlet-name> 22 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 23 <!-- 配置DispatcherServletd 一个初始化参数:配置springmvc配置文件的位置和名称 --> 24 <!-- 实际上也可以不通过 contextConfigLocation 来配置Springmvc的配置文件,而是用默认的 即默认的配置文件为 25 /WEB-INF/<servlet-name>-servlet.xml 本项目默认位置配置文件即为: /WEB-INF/springDispatcherServlet-servlet.xml --> 26 <init-param> 27 <param-name>contextConfigLocation</param-name> 28 <param-value>classpath:spring.xml</param-value> 29 </init-param> 30 <!-- 表示springDispatcherServlet在加载的时候被创建 --> 31 <load-on-startup>1</load-on-startup> 32 </servlet> 33 34 <!-- Map all requests to the DispatcherServlet for handling --> 35 <servlet-mapping> 36 <servlet-name>springDispatcherServlet</servlet-name> 37 <url-pattern>/</url-pattern> 38 </servlet-mapping> 39 40 <!-- 配置HiddenHttpMethodFilter :可以把post请求转为delete or put请求 --> 41 42 <filter> 43 <filter-name>HiddenHttpMethodFilter</filter-name> 44 <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> 45 </filter> 46 <filter-mapping> 47 <filter-name>HiddenHttpMethodFilter</filter-name> 48 <url-pattern>/*</url-pattern> 49 </filter-mapping> 50 51 </web-app>
RequestMappingTest:
1 package handler; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 6 import entity.User; 7 8 @RequestMapping("/springmvc") 9 @Controller 10 public class RequestMappingTest { 11 private static final String SUCCESS = "success"; 12 13 @RequestMapping("/testpojo") 14 public String testpojo(User user) { 15 System.out.println("testpojo" + user); 16 return SUCCESS; 17 } 18 }
index.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="false"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <form action="/springmvc/testpojo" method="POST"> 11 用户名:<input type="text" name="userName" /> <br> 12 年龄:<input type="text" name="age" /> <br> 13 城市:<input type="text"name="address.city" /> <br> 14 省份:<input type="text" name="address.province" /> <br> 15 <input type="submit" value='提交'> 16 </form> 17 </body> 18 </html>
success.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="true"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <h4>success</h4> 11 </body> 12 </html>
运行结果:
index.jsp 的运行结果如下图,填写下面信息,点击提交,跳转到 success页面,且控制台打印:
testpojoUser [userName=李秀明, age=18, address=Address [province=浙江, city=嘉兴]]
servlet 原生的API作为目标方法的参数
具体支持以下类型
- HttpServletRequest,
- HttpServletResponse,
- Writer,
- java.security.Principal,
- Locale
- InputStream,
- OutputStream,
- Reader,
- Writer
RequestMappingTest:
1 package handler; 2 3 import java.io.IOException; 4 import java.io.Writer; 5 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 9 import org.springframework.stereotype.Controller; 10 import org.springframework.web.bind.annotation.RequestMapping; 11 12 @RequestMapping("/springmvc") 13 @Controller 14 public class RequestMappingTest { 15 16 @RequestMapping("/testServletAPI") 17 public void testServletAPI(HttpServletRequest request, HttpServletResponse response, Writer out) 18 throws IOException { 19 out.write("hello spring"); 20 } 21 }
index.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="false"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta http-equiv="Content-type" content="text/html;charset=UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <a href="/springmvc/testServletAPI">testServletAPI</a> 11 </body> 12 </html>
success.jsp:
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8" isErrorPage="true"%> 3 <!DOCTYPE html> 4 <html> 5 <head> 6 <meta charset="UTF-8"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <h4>success</h4> 11 </body> 12 </html>
运行结果:
index.jsp运行效果如下;点击testServletAPI 会显示hello spring ;