gpt4 book ai didi

java - 在 Spring MVC 中使用 HttpServletRequest 之前替换/准备原始 POST 数据

转载 作者:行者123 更新时间:2023-11-29 04:59:36 24 4
gpt4 key购买 nike

我有基于 api 的客户端-服务器应用程序,php+yii 作为后端。我的目标是将后端部分的端口从 php 移植到 java(与来自客户端的旧查询兼容)。

我选择了 Spring MVC 框架,但在解密原始发布数据时遇到了问题。问题是旧客户端使用自定义加密算法,因此 HttpServletRequest.getParameterMap() 不会返回有效映射。

所以,我的问题是:在这种情况下,在对纯业务逻辑使用 request.getParameterMap() 方法之前替换/准备原始发布数据(解密)的最佳解决方案是什么?

Controller 代码是这样的:

@RestController
@RequestMapping(value = "/", method = RequestMethod.POST)
public class ApiController {

@RequestMapping
@ResponseBody
public String process(HttpServletRequest request) {
ApiQueryResponse queryResponse = new ApiQueryResponse();

try {
// request = APIEncryptor.decrypt(request); // 1
// now working with request.getParameterMap() // 2
// ...
queryResponse.setText(APIEncryptor.crypt(...))
} catch (Exception e) {
queryResponse.setError(e.getMessage());
}

return queryResponse.asText();
}

...

}

APIEncryptor 代码是这样的:

public class ApiEncryptor {
public static ApiQueryData encrypt(Java Object) {
// custom encryption algorithm...
return Raw data string;
}

// input post data: 103klg20fsl2g2fsldkfj20f9isjf
// output post data: a=1&b=2&c=3&d=some_text

public static ApiQueryData decrypt(Raw post data...) {
// decrypt algorithm...
return request; // HttpServletRequest object with valid post data
// after this action, .getParameter() will produce valid data
}
}

注意:我知道存在什么方法,例如request.getInputStream(),但我现在不需要它。我需要知道在使用 HttpServletRequest 参数 getter 之前是否有任何方法可以准备发布数据?或者(无论如何)我需要一次从请求中获取发布数据并做我想做的事(例如通过 getReader())?

最佳答案

The best way to handle your decryption logic is inside a http filter (uses spring MVC) as below. This filter decrypts the requests immediately after receiving the request to server and before reaching the controller method.

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

public class DecryptionFilter extends OncePerRequestFilter {

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {

request = ApiEncryptor.decrypt(request);

filterChain.doFilter(request, response);
}

}

关于java - 在 Spring MVC 中使用 HttpServletRequest 之前替换/准备原始 POST 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32542396/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com