2012-02-24 60 views
4

我想用HttpServletRequest的如何使用读取春天请求PARAM值的HttpServletRequest

http://localhost:8080/api/type?name=xyz&age=20 

我控制器的方法会不会@RequestParam定义,它仅仅是

读取从URL中requestParams数据
@RequestMapping(value = "/**", method = RequestMethod.GET) 
    public ResponseEntity<String> getResponse(
      final HttpServletRequest request) {} 

我想阅读使用请求只有参数不是整个网址。

回答

8

第一,为什么你定义:

@RequestMapping(value = "/**", method = RequestMethod.GET)` 

也许你应该使用:

@RequestMapping(value = "/api/type", method = RequestMethod.GET) 

和read参数:

request.getParameter("name"); 
request.getParameter("age"): 
0

这是你在找什么?

public java.lang.String getParameter(java.lang.String name) 

API

的getParameter

字符串的getParameter(String name)返回一个请求 参数为字符串,或者如果参数不存在空的值。 请求参数是与请求一起发送的额外信息。对于 HTTP servlet,参数包含在查询字符串中或发布为 表单数据。只有在确定参数 只有一个值时,才应使用此方法。如果参数的值可能超过 ,请使用getParameterValues(java.lang.String)。

如果对多值参数使用此方法,则返回的值 等于 getParameterValues返回的数组中的第一个值。

如果参数数据在请求体中发送,例如具有HTTP POST请求发生 ,然后直接通过 的getInputStream()或getReader读取体()可以与 该方法的执行产生干扰。

参数:name - 一个String指定参数 名返回:表示该参数的单个值的字符串见 另外:getParameterValues(java.lang.String中)

1

您可以使用

request.getParameter("parameter name") 
5

翔适合您的具体问题:“我想用的要求只有PARAMS阅读”

但是为什么你要让它尽量d ifficult。Spring支持你,所以你不需要自己处理请求对象等常见任务:

我建议使用

@RequestMapping(value = "/*", method = RequestMethod.GET) 
public ResponseEntity<String> getResponse(
    @RequestParam("name") String name 
    @RequestParam("age") int age){ 

    ... 
} 

代替。

@See Spring参考章节15.3.2.4. Binding request parameters to method parameters with @RequestParam

相关问题