ajax application/json传入后台,拦截器怎么获取参数且不破坏 @RequestBody正常接收?

如题:

  前端传入代码:
   
   $("#button").click(function(){
 var user = {"name":"张三","age":9,"key":"xx"};
$.ajax({
    url:"http://localhost:8080/mybatis/insert",    
    contentType : 'application/json',
    type : "POST",
    dataType: 'json',
    data: JSON.stringify(user),
    success : function(data) {
        alert(data.result);
    }
});

拦截器:

    @Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse arg1, Object arg2) throws Exception {

    System.out.println("我拦截了");
    // 不能使用 request.getReader(); 和流的方式获取(流只能取一次,导致后台获取不到参数),request.getParameter();获取不到 json格式参数
    
    return true;
}

后台:

@RequestMapping("/insert")

public Map<String, Object> insert(@RequestBody User user){
    service.insert(user);
    Map<String, Object> result = new HashMap<>();
    result.put("result", "success");
    return result;
}

,请问谁有办法在不破坏后台:流和@RequestBody情况下,在拦截器里面获取我前台传入的key?

阅读 9.6k
2 个回答

当然使用aop来做咯。
代码如下。

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Aspect
@Component
public class LoggingAspect {

    private final Logger log = LoggerFactory.getLogger(this.getClass());
    
    @Pointcut("within(@org.springframework.stereotype.Repository *)" +
        " || within(@org.springframework.stereotype.Service *)" +
        " || within(@org.springframework.web.bind.annotation.RestController *)")
    public void springBeanPointcut() {
        
    }
    
    @Pointcut("within(com.fanxian.logic.*.repository..*)"+
        " || within(com.fanxian.logic.*.service..*)"+
        " || within(com.fanxian.logic.*.controller..*)")
    public void applicationPackagePointcut() {
        
    }


    @AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
        log.error("Exception in {}.{}() with cause = \'{}\' and exception = \'{}\'", joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL", e.getMessage(), e);
    }
    
    @Around("applicationPackagePointcut() && springBeanPointcut()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        if (log.isDebugEnabled()) {
            log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
        }
        try {
            Object result = joinPoint.proceed();
            if (log.isDebugEnabled()) {
                log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
                    joinPoint.getSignature().getName(), result);
            }
            return result;
        } catch (IllegalArgumentException e) {
            log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
                joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());

            throw e;
        }
    }
}

springBeanPointcut方法配置了spring注解的切入点,applicationPackagePointcut则为你想要拦截方法的切入点。
logAfterThrowing为拦截捕获到的异常,logAround环绕方法获取到拦截的方法打印方法名,输入的参数等等,再往下的Object result = joinPoint.proceed();为调用目标方法,最后打印了返回值。

你需要的只是获取输入的参数,所以joinPoint.getArgs()就是你需要的方法。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题