Java Spring Controller 获取请求参数的几种方法
1、直接把表单的参数写在Controller相应的方法的形参中,适用于get方式提交,不适用于post方式提交。若"Content-Type"="application/x-www-form-urlencoded",可用post提交
url形式:http://localhost:8080/SSMDemo/demo/addUser1?username=lixiaoxi&password=111111 提交的参数需要和Controller方法中的入参名称一致。
1
2
3
4
5
6
7
8
9
10
11
12
|
/**
* 1.直接把表单的参数写在Controller相应的方法的形参中
* @param username
* @param password
* @return
*/
@RequestMapping ( "/addUser1" )
public String addUser1(String username,String password) {
System.out.println( "username is:" +username);
System.out.println( "password is:" +password);
return "demo/index" ;
}
|
2、通过HttpServletRequest接收,post方式和get方式都可以。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
/**
* 2、通过HttpServletRequest接收
* @param request
* @return
*/
@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" ;
}
|
3、通过一个bean来接收,post方式和get方式都可以。
1
2
3
4
5
6
7
8
9
10
11
|
/**
* 3、通过一个bean来接收
* @param user
* @return
*/
@RequestMapping ( "/addUser3" )
public String addUser3(UserModel user) {
System.out.println( "username is:" +user.getUsername());
System.out.println( "password is:" +user.getPassword());
return "demo/index" ;
}
|
4、使用@ModelAttribute注解获取POST请求的FORM表单数据
1
2
3
4
5
6
7
8
9
10
11
|
/**
* 4、使用@ModelAttribute注解获取POST请求的FORM表单数据
* @param user
* @return
*/
@RequestMapping (value= "/addUser5" ,method=RequestMethod.POST)
public String addUser5( @ModelAttribute ( "user" ) UserModel user) {
System.out.println( "username is:" +user.getUsername());
System.out.println( "password is:" +user.getPassword());
return "demo/index" ;
}
|
5、用注解@RequestParam绑定请求参数到方法入参
当请求参数username不存在时会有异常发生,可以通过设置属性required=false解决,例如:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
@RequestParam (value= "username" , required= false )
**** 若 "Content-Type" = "application/x-www-form-urlencoded" ,post get都可以
**** 若 "Content-Type" = "application/application/json" ,只适用get
/**
* 5、用注解@RequestParam绑定请求参数到方法入参
* @param username
* @param password
* @return
*/
@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" ;
}
|
6、用request.getQueryString() 获取spring MVC get请求的参数,只适用get请求
1
2
3
4
5
|
@RequestMapping (value= "/addUser6" ,method=RequestMethod.GET)
public String addUser6(HttpServletRequest request) {
System.out.println( "username is:" +request.getQueryString());
return "demo/index" ;
}
|
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
原文链接:http://www.cnblogs.com/wxwBlog/p/6128882.html