2012년 8월 11일 토요일

SpringMVC Tip

서블릿 매칭을 제외한 스프링프레임웍으로부터 현재 매핑된 주소 동적으로 가져오기


Case1. 단순매칭시

@RequestMapping(value=[이부분], method={RequestMethod.GET,RequestMethod.POST})
public ModelAndView index(HttpServletRequest request, HttpServletResponse reponse){
    String mappingValue = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
    System.out.println("Mapping Value = "  + mappingValue);
    return new ModelAndView("index");
}


Case2. url 변수 사용시

@RequestMapping(value=index. + "{val}", method={RequestMethod.GET,RequestMethod.POST})
public ModelAndView index(HttpServletRequest request, HttpServletResponse reponse,
    @PathVariable("val") final String val){
    String mappingValue = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
    Map<?, ?> mapping = (Map<?, ?>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
    Iterator<?> iter = mapping.keySet().iterator();
    while(iter.hasNext()){
        String key = (String) iter.next();
        Object value = mapping.get(key);
        if(mappingValue.contains("{"+key+"}")){
            mappingValue = mappingValue.replaceAll("\\{"+key+"\\}", value == null ? "" : value.toString());
        }
    }
    System.out.println("Mapping Value = "  + mappingValue);
    return new ModelAndView("index");
}


참고