参考地址:https://blog.csdn.net/qq_32718633/article/details/79131974
目录
@RequestMapping
REST风格的参数(@PathVariable)
- 形如REST风格的地址访问,比如: /departments/23,其中用(@PathVariable接收rest风格的参数
@RequestMapping("/departments/{departmentId}")
public String findDepatment(@PathVariable String departmentId){
System.out.println("Find department with ID: " + departmentId);
return "someResult";
}
- 创建一个Handler接收请求,跳转到对应的页面。请求和页面的名称一致。可以统一处理.
@RequestMapping("/{page}")
public String showPage(@PathVariable String page) {
return page;
}
限制请求类型及参数
// 该方法将接收 /user/login 发来的请求,且请求参数必须为username=kolbe&password=123456
@RequestMapping(path = "/login", params={"username=kolbe","password=123456"})
public String login() {
return "success";
}
//仅处理通过 POST 方式发来的请求
@RequestMapping(path = "/login", method=RequestMethod.POST)
// 该方法将同时接收通过GET和POST方式发来的请求
@RequestMapping(path = "/login", method={RequestMethod.POST,RequestMethod.GET})
//设定必须包含username 和age两个参数,且age参数不为10 (可以有多个参数)。
@RequestMapping(value = "testParamsAndHeaders", params = { "username","age!=10" })
public String testParamsAndHeaders() {
System.out.println("testParamsAndHeaders");
return SUCCESS;
}
- value属性:映射的是请求的地址,如果是一个数据,那么这两个地址之间的关系是或(||)的关系
如: http://localhost:8080/springMVCmybatis/modifyGet1.do?name=mike&pwd=123456
http://localhost:8080/springMVCmybatis/modifyGet.do?name=mike&pwd=123456 - method属性:定义了请求的方式,如果此属性定义了多个值,那么可以适应多种请求方式
- consumes属性 :指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;
- produces属性:指定返回的内容类型
- params与heads:这两个属性的作用是类似的,可以对请求进一步过滤,如果输入的参数不包含对应的属性或者属性的值有错误,那么就会报HTTP Status [404] – [Not Found]的错误。
@RequestMapping(value = {"/modifyGet.do","/modifyGet1.do"}, method={RequestMethod.POST, RequestMethod.GET},consumes={"application/json"}, produces={"application/json"}, params={"name=mike","pwd=123456"},headers={"a=1"})
@ResponseBody
public Object addEmpGet(@RequestBody JSONObject reqobj)throws Exception {
JSONObject responseObj = new JSONObject();
responseObj.put("id", reqObj.getIntValue("id"));
return responseObj ;
}
==>{"id":1}
@RequestBody @ResponseBody
ResponseBody基本用法
- @responseBody注解的作用是将controller的方法返回的对象通过适当的转换器转换为指定的格式之后,写入到response对象的body区,通常用来返回JSON数据或者是XML数据,需要注意的呢,在使用此注解之后不会再走试图处理器,而是直接将数据写入到输入流中,他的效果等同于通过response对象输出指定格式的数据。
@RequestMapping("/login")
@ResponseBody
public User login(User user){
return user;
}
User字段:userName pwd
那么在前台接收到的数据为:'{"userName":"xxx","pwd":"xxx"}'
效果等同于如下代码:
@RequestMapping("/login")
public void login(User user, HttpServletResponse response){
response.getWriter.write(JSONObject.fromObject(user).toString());
}
RequestBody基本用法
- 首先@RequestBody需要接的参数是一个string化的json(接收的是一个Json对象的字符串),这里直接使用JSON.stringify(json)这个方法来转化
其次@RequestBody,从名称上来看也就是说要读取的数据在请求体里,所以要发post请求
第三,要设置contentType,contentType:”application/json,明确的告诉服务器发送的内容是json,而默认的contentType是application/x-www-form-urlencoded; charset=UTF-8
$.ajax({
type: "post",
contentType:"application/json",
url: "repairs/saveDispatches",
data: JSON.stringify(dispatchesDTO),
success: function(data){
if(!data.success){
alertError("派工失败");
}else{
alertSuccess("派工成功");
}
})
@RequestMapping("/repairs/saveDispatches")
public void saveDispatches(@RequestBody DispatchesDTO dispatchesDTO,
HttpServletResponse response) throws IOException {
dispatchesService.saveDispatches(dispatchesDTO);
success(response);
}
接收参数(HttpServletRequest @ModelAttribute @RequestParam)
- 直接把表单的参数写在Controller相应的方法的形参中
@RequestMapping("/addUser1")
public String addUser1(String username,String password) {
System.out.println("username is:"+username);
System.out.println("password is:"+password);
return "demo/index";
}
- 通过HttpServletRequest接收,post方式和get方式都可以。
@RequestMapping("/addUser2")
public String addUser2(HttpServletRequest request) {
String username=request.getParameter("username");
String password=request.getParameter("password");
System.out.println("username is:"+username);
System.out.println("password is:"+password);
return "demo/index";
}
- 通过一个bean来接收,post方式和get方式都可以。
@RequestMapping("/addUser3")
public String addUser3(UserModel user) {
System.out.println("username is:"+user.getUsername());
System.out.println("password is:"+user.getPassword());
return "demo/index";
}
- 用注解@RequestParam绑定请求参数到方法入参
当请求参数username不存在时会有异常发生,可以通过设置属性required=false解决,例如: @RequestParam(value=”username”, required=false)
若”Content-Type”=”application/x-www-form-urlencoded”,post get都可以
若”Content-Type”=”application/application/json”,只适用get
@RequestMapping(value="/addUser6",method=RequestMethod.GET)
public String addUser6(@RequestParam("username") String username,@RequestParam("password") String password) {
System.out.println("username is:"+username);
System.out.println("password is:"+password);
return "demo/index";
}
- 获取request中所有参数的方法
//方法一
Enumeration enu=request.getParameterNames();
while(enu.hasMoreElements()){
String paraName=(String)enu.nextElement();
System.out.println(paraName+": "+request.getParameter(paraName));
}
//方法二
Map map=request.getParameterMap();
Set keSet=map.entrySet();
for(Iterator itr=keSet.iterator();itr.hasNext();){
Map.Entry me=(Map.Entry)itr.next();
Object ok=me.getKey();
Object ov=me.getValue();
String[] value=new String[1];
if(ov instanceof String[]){
value=(String[])ov;
}else{
value[0]=ov.toString();
}
for(int k=0;k<value.length;k++){
System.out.println(ok+"="+value[k]);
}
}