SpringMVC02
请求相关操作
1@RequestMapping
@RequestMapping * 作用:用来限制请求的 * 位置:可以标记在方法上,也可以标记在类上 * 属性: * value:用来限制请求url的,字符串数组类型 * 支持通配符: * ?:表示任意一个字符 * *:任意多个任意字符 * **:任意多层字符 * method:用来限制请求方式的,RequestMethod数组类型 * 默认支持四种请求方式,如果我们指定了某种请求方式,那么前端再给后端发送请求的时候,就必须按着指定的请求方式发送 * GET: 查询数据库资源 * POST: 向数据库中添加数据 * PUT: 修改数据库中的资源 * DELETE:删除数据库中的资源 *
* 如何发送put或者delete请求? * 1.在web.xml文件中配置一个HiddenHttpMethodFilter * 2.必须发送post请求 * 3.必须携带一个键值对,键为:_method,值为:put或者delete * 补充:rest请求风格:建议使用请求方式表示对某种资源进行何种方式的处理,规范
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <form action="hello" method="post"> <input type="hidden" name="_method" value="delete"> <input type="submit" value="提交"> </form> </body>
</html>
@RequestMapping(value= {"/hello"},method= {RequestMethod.DELETE})
public String go() {
return "success";
}
* params:用来限制请求参数的,字符串数组类型 * params={"username"}:请求参数中必须携带一个键为username的参数 * params={"!username"}:请求参数中不能携带键为username的参数 * params={"username=123"}:请求参数中必须携带一个键为username,值为123的参数 * params={"username!=123"}:请求参数中必须携带一个键为username,值不能为123的参数 * params={"username=123","password"}:请求参数中必须携带一个键为username,值为123的参数,并且还得携带一个键为password的参数 * * headers:用来限制请求头的* ,字符串数组类型,使用类似于params属性 * headers={"Connection"}:请求头中必须携带一个键为username的参数 * headers={"!Connection"} * headers={"Connection=123"}: * headers={"Connection!=123"}: * @RequestMapping注解的四个属性是与(&)的关系,必须同时满足
举例:


2。@PathVariable
作用:将路径占位符信息绑定到目标方法的参数上
位置:标记在controller层目标方法的参数上
属性:value属性,要求value值一定要和路径占位符保持一致
@RequestMapping(value="/test01/{id}",method=RequestMethod.GET)
public String testPathVariable(@PathVariable(value="id") Integer sid) {
System.out.println(sid);
return "success";

3.@RequestParam
作用:获取请求参数的
位置:标记在controller层方法的参数上
属性:Value,Required ,defaultValue:
当controller层目标方法的参数名和表单的name值保持一致的时候,@RequestParam注解可以省略。

4 @RequestHeader
作用:获取请求头信息
位置:标注在目标controller方法的参数上
属性:使用类似于@RequestParam注解
@RequestMapping("/testRequestHeader")
public String testRequestHeader(@RequestHeader(value="Cookie",required = false,defaultValue = "dasd") String header) {
System.out.println("testRequestHeader。。。。。。。。。。"+header);
return "success";
}
5.@CookieValue
获取某个cookie的值
之前的遍历Cookie[] cookie才能拿到某个值
@RequestMapping("/hello")
public String testCookie(@CookieValue(value="JSESSIONID",required=true,defaultValue="abcde") String cookie){
System.out.println("cookie信息为"+ cookie);
return "success";
}
区分:

原生API
SringMVC可以直接在参数上写原生API
常用的:
HttpServletRequest HttpServletResponse HttpSession java.security.principal: htps安全相关 Locale: 国际化相关的区域信息对象 InputStream: ServletInputStream inputStream = request.getInputStream(); OutputStream : ServletOutputStream outputStream = response.getOutputStream(); Reader : BufferedReader reader = request.getReader(); Writer : PrintWriter writer = response.getWriter();
处理请求乱码的方式
GET请求乱码
Tomcat7.x及以下:
<Connector URIEncoding="UTF-8" connectionTimeout="20000" port="8080"
Tomcat8.x及以上:tomcat自己解决了。
POST请求乱码:
在web.xml文件中配置一个CharacterEncodingFilter

支持pojo对象
import java.util.Arrays; public class User { private String username; private int sex; private String[] hobby; private Address address; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public int getSex() { return sex; } public void setSex(int sex) { this.sex = sex; } public String[] getHobby() { return hobby; } public void setHobby(String[] hobby) { this.hobby = hobby; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } @Override public String toString() { return "User [username=" + username + ", sex=" + sex + ", hobby=" + Arrays.toString(hobby) + ", address=" + address + "]"; } }
public class Address { private String provice; private String city; private String town; public String getProvice() { return provice; } public void setProvice(String provice) { this.provice = provice; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getTown() { return town; } public void setTown(String town) { this.town = town; } @Override public String toString() { return "Address [provice=" + provice + ", city=" + city + ", town=" + town + "]"; }
<form action="test03" method="post">
<!-- <input type="hidden" name="_method" value="delete"> -->
姓名:<input type="text" name="username"><br>
性别:<input type="radio" name="sex" value="1">男
<input type="radio" name="sex" value="0">女 <br>
爱好:<input type="checkbox" name="hobby" value="篮球">篮球
<input type="checkbox" name="hobby" value="逛街">逛街
<input type="checkbox" name="hobby" value="看电影">看电影
<input type="checkbox" name="hobby" value="玩游戏">玩游戏<br>
住址:省<input type="text" name="address.provice">
市<input type="text" name="address.city">
县<input type="text" name="address.town"><br>
<input type="submit" value="提交">
</form>
@RequestMapping("/test03")
public String testPojo(User user) {
System.out.println(user);
return "success";
}

mvc:view-controller

响应相关操作
同步请求响应
同步请求的返回值类型
同步请求的返回值类型 同步请求的返回值类型: * String:表示逻辑视图名 * ModelAndView: * void:一般不会使用
如何将控制层的数据携带到页面上

1.ModelAndView作为方法的返回值
@RequestMapping("/test04")
public ModelAndView testMAV() {
ModelAndView mv = new ModelAndView();
mv.setViewName("success");
mv.addObject("msg", "ModelAndView");
return mv;
}


2.在controller层的方法参数上使用Map,Model,ModelMap类型的参数,返回值是String类型
@RequestMapping("/test05")
public String testMap(Map<String,Object> map) {
map.put("name", "张三");
map.put("age", 23);
map.put("sex", "男");
return "success";
}
@RequestMapping("/test06")
public String testModel(Model model) {
model.addAttribute("name", "张三");
model.addAttribute("age", 23);
model.addAttribute("sex", "男");
return "success";
}
@RequestMapping("test07")
public String testModelMap(ModelMap modelMap) {
modelMap.addAttribute("name", "张三");
modelMap.addAttribute("age", 23);
modelMap.addAttribute("sex", "男");
return "success";
}
<body>
<h1>来到success页面</h1>
${name }-->${age }-->${sex }
</body>

异步请求响应
如何使用静态资源文件
静态资源文件指的是:html、css、js、img,这些不依赖于tomcat,就能直接查看的资源。




如何返回json数据
在controller层的方法上加@ResponseBody注解
@RequestMapping("/json")
@ResponseBody
public Map<String,Object> testJson(){
Map<String,Object> map = new HashMap<String,Object> ();
map.put("username", "王亮");
map.put("age", 23);
return map;
}
Springmvc.xml文件中配置mvc:annotation-driven

前后端实现异步交互
public class Book { private int bid; private String bname; private String author; private double price; private String type; public Book() { super(); // TODO Auto-generated constructor stub } public Book(int bid, String bname, String author, double price, String type) { super(); this.bid = bid; this.bname = bname; this.author = author; this.price = price; this.type = type; } public int getBid() { return bid; } public void setBid(int bid) { this.bid = bid; } public String getBname() { return bname; } public void setBname(String bname) { this.bname = bname; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public String getType() { return type; } public void setType(String type) { this.type = type; } @Override public String toString() { return "Book [bid=" + bid + ", bname=" + bname + ", author=" + author + ", price=" + price + ", type=" + type + "]"; } }
@RequestMapping("/list")
@ResponseBody
public List testJson2() {
List<Book> list = new ArrayList<Book>();
list.add(new Book(1, "三国演义", "吴承恩", 50.7, "名著"));
list.add(new Book(2, "斗破苍穹", "土豆", 20.0, "玄幻"));
list.add(new Book(3, "三生三世", "玉米", 34.4, "古装"));
list.add(new Book(4, "悲伤逆流成河", "柿子", 31.7, "悲剧"));
return list;
}
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="${pageContext.request.contextPath }/static/js/jquery-1.7.2.js"></script> </head> <body> <button id="btn">点击查看</button> <span id="sp"></span> <script type="text/javascript"> $("#btn").click(function(){ $.ajax({ type:"GET", url:"${pageContext.request.contextPath}/list", success:function(obj){ $("#sp").html("<table id='table-list' border='2px' align='center' width='70%'>" +"<tr>" +"<th>编号</th>" +"<th>书名</th>" +"<th>作者</th>" +"<th>价格</th>" +"<th>类型</th>" +"<th>操作</th>" +"</tr>" +"</table>"); $(obj).each(function(index,item){ var tr = "<tr align='center'><td>"+item.bid+"</td><td>"+item.bname+"</td><td>"+item.author+"</td><td>"+item.price+"</td><td>"+item.type+"</td><td><a href=''>修改</a> <a href=''>删除</a></td></tr>" $("#table-list").append(tr); }) } }) }) </script> </body> </html>


浙公网安备 33010602011771号