【SpringMvc】请求处理的各种注解
文章目录1、@RequestParam(获取请求参数)value属性:required属性:defaultValue属性:2、@RequestHeader(获取请求头)3、@CookieValue(获取cookie信息)4、传入POJO,SpringMvc自动封装1、jsp中创建form表单2、创建对应的POJO3、SpringMvc接收数据注意事项:5、传入原生API1、@RequestPara
·
文章目录
1、@RequestParam(获取请求参数)
属性:value、required、defaultValue
value属性:
public String test1(@RequestParam(value = "user") String username) {}
这种方式相当于:
username=request.getParameter("user");
required属性:
required():true/false,指定该参数在访问页面的时候是否必须存在,默认true
defaultValue属性:
指定该参数默认值
2、@RequestHeader(获取请求头)
属性:value、required、defaultValue
使用方式:在参数前使用
public String test2(@RequestHeader(value = "User-Agent") String username) {}
相当于下面代码
userAgent = request.getHeader("User-Agent");
required、defaultValue的意义和@RequestParam
的参数相同
3、@CookieValue(获取cookie信息)
属性:value、required、defaultValue
使用方式:
public String test3(@CookieValue("JSESSIONID") String username) {}
4、传入POJO,SpringMvc自动封装
1、jsp中创建form表单
<%@ 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="fangfff">
书名:<input type="text" name="name">
作者:<input type="text" name="author">
价格:<input type="text" name="price">
出版社:<input type="text" name="press">
<input type="submit" value="提交图书">
</form>
</body>
</html>
2、创建对应的POJO
package com.fang.bean;
public class Book {
private String name;
private String author;
private String price;
private String press;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getPress() {
return press;
}
public void setPress(String press) {
this.press = press;
}
@Override
public String toString() {
return "Book [name=" + name + ", author=" + author + ", price=" + price + ", press=" + press + "]";
}
}
3、SpringMvc接收数据
@RequestMapping(value = "/fangfff")
public String test4(Book book) {
System.out.println(book);
return "success";
}
注意事项:
POJO的属性名与表单中input的name属性一一对应,不然就是默认为null
5、传入原生API
1、设置session、request作用域参数
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@Controller
public class HelloController {
@RequestMapping(value = "/ff")
public String test5(HttpSession session,HttpServletRequest req) {
session.setAttribute("ffsession", "这是session域的");
req.setAttribute("reqname", "这是request域的");
return "success";
}
}
2、前端jsp获取参数
<%@ 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>
成功
<!-- 获取ff响应发来的参数 -->
${requestScope.reqname }
${sessionScope.ffsession }
</body>
</html>
更多推荐
已为社区贡献1条内容
所有评论(0)