springmvc Controller接收前端参数的几种方式总结
1. 普通方式-请求参数名和Controller方法的参数一致
@Controller
@RequestMapping("/param")
public class TestParamController {
private static final Logger logger = LoggerFactory.getLogger(TestParamController.class);
/**
* 请求参数名和Controller方法的参数一致
* produces 设置返回参数的编码格式可以设置返回数据的类型以及编码,可以是json或者xml
* {
* @RequestMapping(value="/xxx",produces = {"application/json;charset=UTF-8"})
* 或
* @RequestMapping(value="/xxx",produces = {"application/xml;charset=UTF-8"})
* 或
* @RequestMapping(value="/xxx",produces = "{text/html;charset=utf-8}")
* }
* @param name 用户名
* @param pwd 密码
* @return
*
*/
@RequestMapping(value = "/add", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String addUser(String name, String pwd){
logger.debug("name:" + name + ",pwd:" + pwd);
return "name:" + name + ",pwd:" + pwd;
}
}
通过访问:http://xxx:8080/sty/param/add?name=张三&pwd=123456
2. 对象方式-请求参数名和Controller方法中的对象的参数一致
@Controller
@RequestMapping("/param")
public class TestParamController {
private static final Logger logger = LoggerFactory.getLogger(TestParamController.class);
/**
* 请求参数名和Controller方法的参数一致
* produces 设置返回参数的编码格式可以设置返回数据的类型以及编码,可以是json或者xml
* }
* @param user 用户信息
* @return
*
*/
@RequestMapping(value = "/addByObject", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String addUserByObject(User user){
logger.debug("name:" + user.getName() + ",pwd:" + user.getPwd());
return "name:" + user.getName() + ",pwd:" + user.getPwd();
}
}
通过访问:http://localhost:8080/sty/param/addByObject?name=张三&pwd=123456
3. 自定义方法参数名-当请求参数名与方法参数名不一致时
注意可以在参数中增加@RequestParam注解。如果在方法中的参数增加了该注解,说明请求的url必须带该带有该参数,否则不能执行该方法。如果在方法中的参数没有增加该注解,说明请求的url无需带有该参数,也能继续执行该方法。
@RequestParam(defaultValue="0")可设置默认值(仅当传入参数为空时)。
@RequestParam(value="id")可接受传入参数为id的值,覆盖该注解注释的字段。
@RequestParam(value="id", required = false)可以接受不是必填项的参数,没有也可以。
@RequestParam(name="name",defaultValue = "李四") String u_name 如果传入字段”name”为空,默认u_name的值为”李四”。若传入”name”不为空,默认u_name值为传入值。
以下只该出方法:
/**
* 自定义方法参数名-当请求参数名与方法参数名不一致时
* @param u_name 用户名
* @param u_pwd 密码
* @return
*/
@RequestMapping(value = "/addByDifName", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String addUserByDifName(@RequestParam("name") String u_name, @RequestParam("pwd")String u_pwd){
logger.debug("name:" + u_name + ",pwd:" + u_pwd);
return "name:" + u_name + ",pwd:" + u_pwd;
}
通过访问:http://localhost:8080/sty/param/addUserByDifName?name=张三&pwd=123456
4. HttpServletRequest方式
/**
* 通过HttpServletRequest接收
* @param request
* @return
*/
@RequestMapping(value = "/addByHttpServletRequest", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String addUserByHttpServletRequest(HttpServletRequest request){
String name = request.getParameter("name");
String pwd = request.getParameter("pwd")
logger.debug("name:" + name + ",pwd:" + pwd);
return "name:" + name + ",pwd:" + pwd;
}
通过访问:http://localhost:8080/sty/param/addByHttpServletRequest?name=张三&pwd=123456
5. @PathVariable获取路径中的参数接收
注:url含有中文名称时,因为编码问题,无法进行映射,需要修改tomcat下的conf文件夹下的server.xml中的URIEncoding=”UTF-8”,对URL编码设置就可以解决中文问题。
对于经常遇到路径在有符号”.”问题,因为springmvc默认是把点后面的信息作为文件后缀,需要修改默认值:
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors" ref="localeChangeInterceptor"/>
<property name="useDefaultSuffixPattern" value="false" />
</bean>
另外,这时候如果只设置这个,请求可以传递到对于的controller,但传过去的数据会有问题,只会传最后一个点前面的数据,除非你在最后加上“/”,比如/news/测试.点/ 这样就会把“测试.点”当作整体,不然只会得到“测试”。这时候我们可以这样设置@RequestMapping("/news/{title:.*}")
/**
* 通过@PathVariable获取路径中的参数
* @param name 用户名
* @param pwd 密码
* @return
*/
@RequestMapping(value = "/add/{name}/{pwd}", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String addUserByPathVariable(@PathVariable String name, @PathVariable String pwd){
logger.debug("name:" + name + ",pwd:" + pwd);
return "name:" + name + ",pwd:" + pwd;
}
通过访问:http://localhost:8080/sty/param/add/zhangsan/123456
6. @RequestBody-JSON方式接收
/**
* RequestBody-JSON 对象方式
* @param user
* @return
*/
@RequestMapping(value = "/addByObjectJSON", produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String addUserByObjectJSON(@RequestBody User user){
logger.debug("name:" + user.getName() + ",pwd:" + user.getPwd());
return "name:" + user.getName() + ",pwd:" + user.getPwd();
}
/**
* RequestBody-JSON List对象方式(json数组格式传参)
* @param users
* @return
*/
@RequestMapping(value = "/addByListJSON", produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String addUsersByListJSON(@RequestBody List<User> users){
StringBuilder sb = new StringBuilder("{");
if(null != users){
for(User user : users){
sb.append("{" + "name:" + user.getName() + ",pwd:" + user.getPwd() + "}");
}
}
sb.append("}");
logger.debug(sb.toString());
return sb.toString();
}
/**
* RequestBody-JSON Map对象方式
* @param users
* @return
*/
@RequestMapping(value = "/addByMapJSON", produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String addUsersByMapJSON(@RequestBody Map<String, User> users){
StringBuilder sb = new StringBuilder("{");
if(null != users){
Iterator it = users.keySet().iterator();
while(it.hasNext()){
User user = users.get(it.next());
sb.append("{" + "name:" + user.getName() + ",pwd:" + user.getPwd() + "}");
}
}
sb.append("}");
logger.debug(sb.toString());
return sb.toString();
}
整体部分源码:
User.java
package com.mjs.study.action.dto;
public class User {
private String name;
private String pwd;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
TestParamController.java
package com.mjs.study.action;
import com.github.pagehelper.PageInfo;
import com.mjs.study.action.dto.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@Controller
@RequestMapping("/param")
public class TestParamController {
private static final Logger logger = LoggerFactory.getLogger(TestParamController.class);
/**
* 请求参数名和Controller方法的参数一致
* produces 设置返回参数的编码格式 可以设置返回数据的类型以及编码,可以是json或者xml
* {
* @RequestMapping(value="/xxx",produces = {"application/json;charset=UTF-8"})
* 或
* @RequestMapping(value="/xxx",produces = {"application/xml;charset=UTF-8"})
* 或
* @RequestMapping(value="/xxx",produces = "{text/html;charset=utf-8}")
* }
* @param name 用户名
* @param pwd 密码
* @return
*
*/
@RequestMapping(value = "/add", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String addUser(String name, String pwd){
logger.debug("name:" + name + ",pwd:" + pwd);
return "name:" + name + ",pwd:" + pwd;
}
/**
* 自定义方法参数名-当请求参数名与方法参数名不一致时
* @param u_name 用户名
* @param u_pwd 密码
* @return
*/
@RequestMapping(value = "/addByDifName", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String addUserByDifName(@RequestParam(name="name",defaultValue = "李四") String u_name, @RequestParam("pwd")String u_pwd){
logger.debug("name:" + u_name + ",pwd:" + u_pwd);
return "name:" + u_name + ",pwd:" + u_pwd;
}
/**
* 请求参数名和Controller方法的参数一致
* produces 设置返回参数的编码格式 可以设置返回数据的类型以及编码,可以是json或者xml
* @param user 用户信息
* @return
*
*/
@RequestMapping(value = "/addByObject", produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String addUserByObject(User user){
logger.debug("name:" + user.getName() + ",pwd:" + user.getPwd());
return "name:" + user.getName() + ",pwd:" + user.getPwd();
}
/**
* RequestBody-JSON 对象方式
* @param user
* @return
*/
@RequestMapping(value = "/addByObjectJSON", produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String addUserByObjectJSON(@RequestBody User user){
logger.debug("name:" + user.getName() + ",pwd:" + user.getPwd());
return "name:" + user.getName() + ",pwd:" + user.getPwd();
}
/**
* RequestBody-JSON List对象方式
* @param users
* @return
*/
@RequestMapping(value = "/addByListJSON", produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String addUsersByListJSON(@RequestBody List<User> users){
StringBuilder sb = new StringBuilder("{");
if(null != users){
for(User user : users){
sb.append("{" + "name:" + user.getName() + ",pwd:" + user.getPwd() + "}");
}
}
sb.append("}");
logger.debug(sb.toString());
return sb.toString();
}
/**
* RequestBody-JSON Map对象方式
* @param users
* @return
*/
@RequestMapping(value = "/addByMapJSON", produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String addUsersByMapJSON(@RequestBody Map<String, User> users){
StringBuilder sb = new StringBuilder("{");
if(null != users){
Iterator it = users.keySet().iterator();
while(it.hasNext()){
User user = users.get(it.next());
sb.append("{" + "name:" + user.getName() + ",pwd:" + user.getPwd() + "}");
}
}
sb.append("}");
logger.debug(sb.toString());
return sb.toString();
}
/**
* 通过HttpServletRequest接收
* @param request
* @return
*/
@RequestMapping(value = "/addByHttpServletRequest", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String addUserByHttpServletRequest(HttpServletRequest request){
String name = request.getParameter("name");
String pwd = request.getParameter("pwd");
logger.debug("name:" + name + ",pwd:" + pwd);
return "name:" + name + ",pwd:" + pwd;
}
/**
* 通过@PathVariable获取路径中的参数
* @param name 用户名
* @param pwd 密码
* @return
*/
@RequestMapping(value = "/add/{name}/{pwd}", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String addUserByPathVariable(@PathVariable String name, @PathVariable String pwd){
logger.debug("name:" + name + ",pwd:" + pwd);
return "name:" + name + ",pwd:" + pwd;
}
}
欢迎一起来学习和指导,谢谢关注!
本文来自博客园,作者:xiexie0812,转载请注明原文链接:https://www.cnblogs.com/mask-xiexie/p/15994437.html