本文共 5454 字,大约阅读时间需要 18 分钟。
spring-boot中通过标签@Aspect ,@Component将类作为切面类,比如日志打印,在特定方法执行前后,执行切面里面方法。
package com.zhou.wenda.aspect;import org.aspectj.lang.JoinPoint;import org.aspectj.lang.annotation.After;import org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.annotation.Before;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Component;import java.util.Date;/** * @author liangzhenzhou * @create 2018-10-23 22:24 */@Aspect@Componentpublic class LogAspect { private static final Logger logger = LoggerFactory.getLogger(LogAspect.class); //拦截制定所有controller,方法执行前执行 @Before("execution(* com.zhou.wenda.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("before method:" + sb.toString()); } //拦截制定IndexController,方法执行前执行 @After("execution(* com.zhou.wenda.controller.IndexController.*(..))") public void afterMethod() { logger.info("after method" + new Date()); }}
package com.zhou.wenda.controller;import com.zhou.wenda.model.User;import com.zhou.wenda.service.WendaService;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.HttpStatus;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.*;import org.springframework.web.servlet.view.RedirectView;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;import java.util.*;/** * @author liangzhenzhou * @create 2018-10-17 21:22 *///@Controllerpublic class IndexController { private static final Logger logger = LoggerFactory.getLogger(IndexController.class); @Autowired WendaService wendaService; @RequestMapping(path = {"/", "/index"}, method = {RequestMethod.GET}) @ResponseBody public String index(HttpSession httpSession) { logger.info("VISIT HOME"); return wendaService.getMessage(2) + "Hello NowCoder" + httpSession.getAttribute("msg"); } @RequestMapping(path = {"/profile/{groupId}/{userId}"}) @ResponseBody public String profile(@PathVariable("userId") int userId, @PathVariable("groupId") String groupId, @RequestParam(value = "type", defaultValue = "1") int type, @RequestParam(value = "key", required = false) String key) { return String.format("Profile Page of %s / %d, t:%d k: %s", groupId, userId, type, key); } @RequestMapping(path = {"/vm"}, method = {RequestMethod.GET}) public String template(Model model) { model.addAttribute("value1", "vvvvv1"); Listcolors = Arrays.asList(new String[]{"RED", "GREEN", "BLUE"}); model.addAttribute("colors", colors); Map map = new HashMap<>(); for (int i = 0; i < 4; ++i) { map.put(String.valueOf(i), String.valueOf(i * i)); } model.addAttribute("map", map); model.addAttribute("user", new User("LEE")); return "home"; } @RequestMapping(path = {"/request"}, method = {RequestMethod.GET}) @ResponseBody public String request(Model model, HttpServletResponse response, HttpServletRequest request, HttpSession httpSession, @CookieValue("JSESSIONID") String sessionId) { StringBuilder sb = new StringBuilder(); sb.append("COOKIEVALUE:" + sessionId+" "); Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = headerNames.nextElement(); sb.append(name + ":" + request.getHeader(name) + " "); } if (request.getCookies() != null) { for (Cookie cookie : request.getCookies()) { sb.append("Cookie:" + cookie.getName() + " value:" + cookie.getValue()); } } sb.append(request.getMethod() + " "); sb.append(request.getQueryString() + " "); sb.append(request.getPathInfo() + " "); sb.append(request.getRequestURI() + " "); response.addHeader("nowcoderId", "hello"); response.addCookie(new Cookie("username", "nowcoder")); return sb.toString(); } @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; } @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(); }}
转载地址:http://ipwci.baihongyu.com/