原始问题在这里: How to resolve URI encoding problem in spring-boot?。遵循其中的建议之一,我试图提出一个拦截器解决方案,但仍然存在一些问题。
我需要能够处理URL中的一些特殊字符,例如“%”,而我的spring控制器在下面:
@Controller
@EnableAutoConfiguration
public class QueryController {
private static final Logger LOGGER = LoggerFactory.getLogger(QueryController.class);
@Autowired
QueryService jnService;
@RequestMapping(value="/extract", method = RequestMethod.GET)
@SuppressWarnings("unchecked")
@ResponseBody
public ExtractionResponse extract(@RequestParam(value = "extractionInput") String input) {
// LOGGER.info("input: " + input);
JSONObject inputObject = JSON.parseObject(input);
InputInfo inputInfo = new InputInfo();
JSONObject object = (JSONObject) inputObject.get(InputInfo.INPUT_INFO);
String inputText = object.getString(InputInfo.INPUT_TEXT);
inputInfo.setInputText(inputText);
return jnService.getExtraction(inputInfo);
}
}
以下建议是我想编写一个拦截器,以便在将请求发送到控制器之前对URL进行编码,而我的拦截器看起来像(尚未完成):
public class ParameterInterceptor extends HandlerInterceptorAdapter {
private static final Logger LOGGER = LoggerFactory.getLogger(ParameterInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse reponse,
Object handler) throws Exception {
Enumeration<?> e = request.getParameterNames();
LOGGER.info("Request URL::" + request.getRequestURL().toString());
StringBuffer sb = new StringBuffer();
if (e != null) {
sb.append("?");
}
while (e.hasMoreElements()) {
String curr = (String) e.nextElement();
sb.append(curr + "=");
sb.append(request.getParameter(curr));
}
LOGGER.info("Parameter: " + sb.toString());
return true;
}
}
我在浏览器中测试了一个网址:
http://localhost:8090/extract?extractionInput={"inputInfo":{"inputText":"5.00%"}}
由于%符号,我收到了错误消息:
[log] - Character decoding failed. Parameter [extractionInput] with value [{"inputInfo":{"inputText":"5.0022:%225.00%%22}}] has been ignored. Note that the name and value quoted here may be corrupted due to the failed decoding.
当我测试拦截器时,“ request.getRequestURL()”给出了预期的结果:
http://localhost:8090/extract
但是,“ request.getParameterNames()”始终获得一个空的Elumentation对象。为什么没有得到参数?我希望首先对参数值进行编码:
"inputText":"5.00%"
'inputText'是json格式的对象InputInfo的字段。那么如何获取请求参数来解决问题呢?