牛客网-高级项目(三)

一. 页面跳转

    @RequestMapping(path = {"/redirect/{code}"}, method = {RequestMethod.GET})
    public RedirectView redirect(@PathVariable("code") int code,
                                 HttpSession httpSession) {
        httpSession.setAttribute("msg", "jump from redirect");
        RedirectView red = new RedirectView("/", true);
        if (code == 301) {
            red.setStatusCode(HttpStatus.MOVED_PERMANENTLY);
        }
        return  red;
    }

 

二. Aspect (@Aspect注解需要加上@Component)


@Aspect
@Component
public class LogAspect {
    public static final Logger logger = LoggerFactory.getLogger(LogAspect.class);

    @Before("execution(* com.fsy.bookmanager.controller.*Controller.*(..))")
    public void beforeMethod(JoinPoint joinPoint){
        StringBuilder sb = new StringBuilder();
        for (Object arg: joinPoint.getArgs()){
            if(arg != null){
                sb.append("arg:" + arg.toString() + "|");
            }
        }
        logger.info("beforeMethod:" + sb.toString());
    }

    @After("execution(* com.fsy.bookmanager.controller.*Controller.*(..))")
    public void afterMethod(){
        logger.info("afterMethod" + new Date());
    }
}

 三. 异常统一处理

    @RequestMapping(path = {"/admin"}, method = {RequestMethod.GET})
    @ResponseBody
    public String admin(@RequestParam("key") String key) {
        if ("admin".equals(key)) {
            return "hello admin";
        }
        throw  new IllegalArgumentException("参数不对");
    }

    @ExceptionHandler()
    @ResponseBody
    public String error(Exception e) {
        return "error:" + e.getMessage();
    }

 

你可能感兴趣的:(JAVA,Springboot)