Springboot项目修改请求参数

需求:前端传过来两个参数searchStartDate和searchEndDate,但是传的是带日期格式的,不带时分秒的,这就导致传到后台的时间都是00:00:0,searchStartDate倒无所谓,searchEndDate需加上23:59:59。

思路:1.用切面的方式,在切面对controller进行拦截

 

@Component
@Aspect
@Log4j2
public class SearchFormateAspect {

    @Pointcut("execution(public * cn.com.test.controller.*.*(..))")
    public void getMethods() {
    }

    @Before("getMethods()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {

        //获取目标方法的参数信息
        Object[] obj = joinPoint.getArgs();

        for (Object argItem : obj) {
            if (argItem instanceof BaseEntity) {
                BaseEntity baseEntity = (BaseEntity) argItem;
                // 前端传入年月日,searchEndDate拼接23:59:59
                Date searchEndDate = baseEntity.getSearchEndDate();
                if (searchEndDate != null) {
                    searchEndDate = DateUtils.setHours(searchEndDate,23);
                    searchEndDate = DateUtils.setMinutes(searchEndDate,59);
                    searchEndDate = DateUtils.setSeconds(searchEndDate,59);
                    baseEntity.setSearchEndDate(searchEndDate);
                }
            }
        }
    }
}

2.过滤器,自定义一个过滤器,自定义wrapper实现HttpServletRequestWrapper

@Component
@Slf4j
public class SearchDateFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException {

        // 获取你需要的参数
        String searchStartDate = request.getParameter("searchStartDate");
        String searchEndDate = request.getParameter("searchEndDate");
        if (StringUtils.isBlank(searchStartDate) && StringUtils.isBlank(searchEndDate)) {
            chain.doFilter(request, response);
        } else {
            RequestParameterWrapper wrapper = new RequestParameterWrapper(request);
            chain.doFilter(wrapper, response);
        }
    }

}
public class RequestParameterWrapper extends HttpServletRequestWrapper {
    private Map<String, String[]> params = new HashMap<>();

    public RequestParameterWrapper(HttpServletRequest request) {
        super(request);
        this.params.putAll(this.getParameterMap());
    }

    /**
     * 重写getParameter,代表参数从当前类中的map获取
     *
     * @param name
     * @return
     */
    @Override
    public String getParameter(String name) {
        String[] values = params.get(name);
        if (values == null || values.length == 0) {
            return null;
        }
        return values[0];
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        HashMap<String, String[]> newMap = new HashMap<>();
        newMap.putAll(super.getParameterMap());
        String[] searchEndDate = newMap.get("searchEndDate");
        if(searchEndDate != null && !StringUtils.isBlank(searchEndDate[0])){
            newMap.put("searchEndDate", new String[]{searchEndDate[0] + " 23:59:59"});
        }
        return Collections.unmodifiableMap(newMap);
    }

    /**
     * 同上
     *
     * @param name
     * @return
     */
    @Override
    public String[] getParameterValues(String name) {
        return params.get(name);
    }
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在Spring Boot中,接收HTTP请求参数乱码通常是由于默认字符编码不正确所致。解决该问题的方法有以下几种: 1. 使用RequestMapping或GetMapping注解的方法时,可在注解中指定produces和consumes属性,并指定字符编码。例如: ```java @RequestMapping(value = "/example", produces = "application/json;charset=UTF-8", consumes = "application/json;charset=UTF-8") public String example(@RequestBody String requestParam) { // 处理请求参数 } ``` 2. 修改Spring Boot应用的全局字符编码设置,可在application.properties或application.yml文件中配置。例如在application.properties中添加: ``` spring.http.encoding.force=true spring.http.encoding.charset=UTF-8 spring.http.encoding.enabled=true ``` 3. 可以通过在Spring Boot的启动类中添加Filter或Interceptor,手动处理请求参数的字符编码。例如创建一个字符编码过滤器: ```java @Component public class CharacterEncodingFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException {} @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("UTF-8"); chain.doFilter(request, response); } @Override public void destroy() {} } ``` 通过以上方法,可以解决Spring Boot接收HTTP请求参数乱码的问题。在实际应用中,根据具体需求选择适合的解决方案。 ### 回答2: 在Spring Boot中,接收HTTP请求参数乱码的问题通常是由于字符编码不一致导致的。可以通过以下几种方式来解决: 1. 使用过滤器(Filter): 可以在Spring Boot中注册一个字符编码过滤器,通过将所有的请求和响应的字符编码都设置为UTF-8来避免乱码问题。在Spring Boot中可以通过重写WebMvcConfigurer接口中的addInterceptors方法来注册过滤器。 2. 在application.properties(application.yml)文件中设置字符编码: 可以通过在application.properties(application.yml)文件中添加以下配置来设置字符编码: spring.http.encoding.charset=UTF-8 spring.http.encoding.enabled=true spring.http.encoding.force=true 3. 使用@RequestParam注解指定字符编码: 可以在Controller中的接收参数的方法上使用@RequestParam注解,并通过设置其value属性来指定字符编码。 例如: @RequestMapping("/test") public String test(@RequestParam(value = "name", required = false) String name) { // ...业务逻辑 return "success"; } 4. 在请求头中指定字符编码: 可以在发送HTTP请求时,在请求头中指定字符编码为UTF-8。例如,在使用HttpClient发送请求时,可以使用setHeader方法设置字符编码。 例如: HttpClient httpClient = new DefaultHttpClient(); HttpPost post = new HttpPost(url); post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); // ...设置请求参数 HttpResponse response = httpClient.execute(post); 通过以上几种方式,可以解决Spring Boot接收HTTP请求参数乱码的问题。 ### 回答3: 当Spring Boot接收到HTTP请求参数乱码的情况时,可以采取以下措施解决问题。 首先,可以在Spring Boot的配置文件application.properties(或application.yml)中添加以下配置,设置请求编码格式为UTF-8: ``` spring.http.encoding.charset=UTF-8 spring.http.encoding.enabled=true spring.http.encoding.force=true ``` 同时,可以使用过滤器请求进行编码处理。在新建一个类中,实现javax.servlet.Filter接口,并重写doFilter方法: ``` import javax.servlet.*; import javax.servlet.annotation.WebFilter; import java.io.IOException; @WebFilter(filterName = "encodingFilter", urlPatterns = "/*") public class EncodingFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); chain.doFilter(request, response); } } ``` 在上述代码中,设置请求和响应的编码格式为UTF-8。 然后,可以为Spring Boot的主类添加一个注解,启用过滤器: ``` import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; @SpringBootApplication @ServletComponentScan public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 在上述代码中,使用了@SpringBootAppliaction注解标记为Spring Boot主类,并使用@ServletComponentScan注解扫描过滤器。 最后,可以在控制器中使用@RequestParam注解显式指定请求参数的编码格式。例如: ``` import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @RequestMapping("/hello") public String hello(@RequestParam(value = "name", required = false) String name) { if (!StringUtils.isEmpty(name)) { // 对name参数进行进一步处理 } return "Hello, " + name; } } ``` 在上述代码中,使用@RequestParam注解指定了name参数,并设置了编码格式。 通过以上措施,可以解决Spring Boot接收HTTP请求参数乱码的问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值