博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring面向切面aop编程
阅读量:4045 次
发布时间:2019-05-24

本文共 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");        List
colors = 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/

你可能感兴趣的文章
kprobe学习
查看>>
慢慢欣赏linux phy驱动初始化2
查看>>
慢慢欣赏linux CPU占用率学习
查看>>
2020年终总结
查看>>
Homebrew指令集
查看>>
React Native(一):搭建开发环境、出Hello World
查看>>
React Native(二):属性、状态
查看>>
JSX使用总结
查看>>
React Native(四):布局(使用Flexbox)
查看>>
React Native(七):Android双击Back键退出应用
查看>>
Android自定义apk名称、版本号自增
查看>>
adb command not found
查看>>
Xcode 启动页面禁用和显示
查看>>
【剑指offer】q50:树中结点的最近祖先
查看>>
二叉树的非递归遍历
查看>>
【leetcode】Reorder List (python)
查看>>
【leetcode】Linked List Cycle (python)
查看>>
【leetcode】Linked List Cycle (python)
查看>>
【leetcode】Candy(python)
查看>>
【leetcode】Clone Graph(python)
查看>>