IT

Spring MVC-Spring 컨트롤러의 맵에서 모든 요청 매개 변수를 얻는 방법은 무엇입니까?

lottoking 2020. 6. 1. 08:08
반응형

Spring MVC-Spring 컨트롤러의 맵에서 모든 요청 매개 변수를 얻는 방법은 무엇입니까?


샘플 URL :

../search/?attr1=value1&attr2=value2&attr4=value4

attr1, att2 및 attr4의 이름을 모릅니다.

요청 매개 변수 이름-> 값의 맵에 액세스 할 수있는 한 이와 비슷한 작업을 수행하고 싶습니다.

@RequestMapping(value = "/search/{parameters}", method = RequestMethod.GET)
public void search(HttpServletRequest request, 
@PathVariable Map<String,String> allRequestParams, ModelMap model)
throws Exception {//TODO: implement}

Spring MVC로 어떻게 이것을 달성 할 수 있습니까?


다른 답변은 정확하지만 HttpServletRequest 객체를 직접 사용하는 "봄 방법"은 아닙니다. 대답은 실제로 매우 간단하며 Spring MVC에 익숙 경우 예상 되는 것입니다.

@RequestMapping(value = {"/search/", "/search"}, method = RequestMethod.GET)
public String search(
@RequestParam Map<String,String> allRequestParams, ModelMap model) {
   return "viewName";
}

편집하다

이 데이터를 얻을 수있는 순수한 Spring MVC 메커니즘 이 존재한다는 것이 지적되었다 ( 적어도 3.0에서 ). 다른 사용자의 답변이므로 여기서 자세히 설명하지 않습니다. 자세한 내용은 @AdamGent의 답변 을 참조하십시오.

Spring 3.2 문서에서이 메커니즘은 RequestMappingJavaDoc 페이지와 JavaDoc 페이지 모두에 언급되어 RequestParam있지만 이전에는 RequestMapping페이지 에서만 언급되어 있습니다. 2.5 문서에는이 메커니즘에 대한 언급이 없습니다.

이것은 HttpServletRequest서블릿 -api jar에 의해 정의 된 객체 에 대한 바인딩을 제거하기 때문에 대부분의 개발자에게 선호되는 방법 일 것 입니다.

/편집하다

를 통해 요청 쿼리 문자열에 액세스 할 수 있어야합니다 request.getQueryString().

대해 getQueryString뿐만 아니라, 쿼리 매개 변수도에서 검색 할 수 있습니다 request.getParameterMap () 지도로.


HttpServletRequest 객체는 이미 매개 변수 맵을 제공합니다. 자세한 내용은 request.getParameterMap () 을 참조하십시오.


당신은 단순히 이것을 사용할 수 있습니다 :

Map<String, String[]> parameters = request.getParameterMap();

잘 작동합니다


org.springframework.web.context.request.WebRequest컨트롤러 메소드에서 매개 변수로 사용 하면 메소드가 제공됩니다. getParameterMap()이점은 애플리케이션을 Servlet API에 고정하지 않으며 WebRequest는 JavaEE 패턴 컨텍스트 오브젝트의 예입니다.


두 가지 인터페이스가 있습니다

  1. org.springframework.web.context.request.WebRequest
  2. org.springframework.web.context.request.NativeWebRequest

기본 서블릿 / 포틀릿 API에 연결하지 않고도request/session 속성 요청뿐만 아니라 일반 요청 매개 변수 액세스를 허용합니다 .

전의.:

@RequestMapping(value = "/", method = GET)
public List<T> getAll(WebRequest webRequest){
    Map<String, String[]> params = webRequest.getParameterMap();
    //...
}

PS는 있다 컨트롤러 PARAMS로 사용할 수 있습니다 인수에 대한 문서.


나는 파티에 늦을지도 모르지만 내 이해에 따라 다음과 같은 것을 찾고 있습니다.

for(String params : Collections.list(httpServletRequest.getParameterNames())) {
    // Whatever you want to do with your map
    // Key : params
    // Value : httpServletRequest.getParameter(params)                
}

다음은 맵에서 요청 매개 변수가져 오는 간단한 예입니다 .

 @RequestMapping(value="submitForm.html", method=RequestMethod.POST)
     public ModelAndView submitForm(@RequestParam Map<String, String> reqParam) 
       {
          String name  = reqParam.get("studentName");
          String email = reqParam.get("studentEmail");

          ModelAndView model = new ModelAndView("AdmissionSuccess");
          model.addObject("msg", "Details submitted by you::
          Name: " + name + ", Email: " + email );
       }

이 경우 studentName 및 studentEmail의 값을 각각 이름 및 이메일 변수와 바인딩합니다.


@SuppressWarnings("unchecked")
Map<String,String[]> requestMapper=request.getParameterMap();
JsonObject jsonObject=new JsonObject();
for(String key:requestMapper.keySet()){
    jsonObject.addProperty(key, requestMapper.get(key)[0]);
}

모든 매개 변수는에 저장됩니다 jsonObject.


쿼리 매개 변수와 경로 매개 변수에는 근본적인 차이가 있습니다. 다음과 같이 진행됩니다 : www.your_domain?queryparam1=1&queryparam2=2-쿼리 매개 변수. www.your_domain/path_param1/entity/path_param2-경로 매개 변수.

What I found surprising is that in Spring MVC world a lot of people confuse one for the other. While query parameters are more like criteria for a search, path params will most likely uniquely identify a resource. Having said that, it doesn't mean that you can't have multiple path parameters in your URI, because the resource structure can be nested. For example, let's say you need a specific car resource of a specific person:

www.my_site/customer/15/car/2 - looking for a second car of a 15th customer.

What would be a usecase to put all path parameters into a map? Path parameters don't have a "key" when you look at a URI itself, those keys inside the map would be taken from your @Mapping annotation, for example:

@GetMapping("/booking/{param1}/{param2}")

From HTTP/REST perspective path parameters can't be projected onto a map really. It's all about Spring's flexibility and their desire to accommodate any developers whim, in my opinion.

I would never use a map for path parameters, but it can be quite useful for query parameters.

참고URL : https://stackoverflow.com/questions/7312436/spring-mvc-how-to-get-all-request-params-in-a-map-in-spring-controller

반응형