https://github.com/itheima2017/adminlte2-itheima
use ssm;
drop table if exists product ;
create table product(
id varchar(32) primary key,
productNum varchar(50) not null,
productName varchar(50),
cityName varchar(50),
DepartureTime timestamp,
productPrice double,
productDesc varchar(500),
productStatus int,
constraint product unique (id, productNum)
)engine innoDB default charset=utf8;
create trigger product_before_insert before insert on product for each row
begin
if new.id = '1' then
set new.id = upper(replace(uuid(), '-', ''));
end if;
end;
insert into PRODUCT (id, productnum, productname, cityname, departuretime, productprice,
productdesc, productstatus)
values ('676C5BD1D35E429A8C2E114939C5685A', 'itcast-002', '北京三日游', '北京', '20181010101000', 1200, '不错的旅行', 1);
insert into PRODUCT (id, productnum, productname, cityname, departuretime, productprice,
productdesc, productstatus)
values ('12B7ABF2A4C544568B0A7C69F36BF8B7', 'itcast-003', '上海五日游', '上海', '20180425143000', 1800, '魔都我来了', 0);
insert into PRODUCT (id, productnum, productname, cityname, departuretime, productprice,
productdesc, productstatus)
values ('9F71F01CB448476DAFB309AA6DF9497F', 'itcast-001', '北京三日游', '北京', '20181010101000', 1200, '不错的旅行', 1);
insert into PRODUCT (productnum, productname, cityname, departuretime, productprice,
productdesc, productstatus)
values ('itcast-004', '北京三日游', '北京', '20181010101000', 1200, '不错的旅行', 1);
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<body>
<jsp:forward page="pages/main.jsp"></jsp:forward>
</body>
</html>
--创建旅客表
drop table if exists traveller;
CREATE TABLE traveller(
id varchar(32) PRIMARY KEY,
NAME VARCHAR(20),
sex VARCHAR(20),
phoneNum VARCHAR(20),
credentialsType INT,
credentialsNum VARCHAR(50),
travellerType INT
);
create trigger traveller_before_insert before insert on traveller for each row
begin
if new.id = '1' then
set new.id = upper(replace(uuid(), '-', ''));
end if;
end;
insert into TRAVELLER (id, name, sex, phonenum, credentialstype, credentialsnum, travellertype)
values ('3FE27DF2A4E44A6DBC5D0FE4651D3D3E', '张龙', '男', '13333333333', 0, '123456789009876543', 0);
insert into TRAVELLER (id, name, sex, phonenum, credentialstype, credentialsnum, travellertype)
values ('EE7A71FB6945483FBF91543DBE851960', '张小龙', '男', '15555555555', 0, '987654321123456789', 1);
-- 订单与旅客中间表
drop table if exists order_traveller;
CREATE TABLE order_traveller(
orderId varchar(32),
travellerId varchar(32),
PRIMARY KEY (orderId,travellerId),
FOREIGN KEY (orderId) REFERENCES orders(id),
FOREIGN KEY (travellerId) REFERENCES traveller(id)
);
insert into ORDER_TRAVELLER (orderid, travellerid)
values ('0E7231DC797C486290E8713CA3C6ECCC', '3FE27DF2A4E44A6DBC5D0FE4651D3D3E');
insert into ORDER_TRAVELLER (orderid, travellerid)
values ('2FF351C4AC744E2092DCF08CFD314420', '3FE27DF2A4E44A6DBC5D0FE4651D3D3E');
insert into ORDER_TRAVELLER (orderid, travellerid)
values ('3081770BC3984EF092D9E99760FDABDE', 'EE7A71FB6945483FBF91543DBE851960');
insert into ORDER_TRAVELLER (orderid, travellerid)
values ('55F9AF582D5A4DB28FB4EC3199385762', 'EE7A71FB6945483FBF91543DBE851960');
insert into ORDER_TRAVELLER (orderid, travellerid)
values ('5DC6A48DD4E94592AE904930EA866AFA', '3FE27DF2A4E44A6DBC5D0FE4651D3D3E');
insert into ORDER_TRAVELLER (orderid, travellerid)
values ('96CC8BD43C734CC2ACBFF09501B4DD5D', 'EE7A71FB6945483FBF91543DBE851960');
insert into ORDER_TRAVELLER (orderid, travellerid)
values ('A0657832D93E4B10AE88A2D4B70B1A28', '3FE27DF2A4E44A6DBC5D0FE4651D3D3E');
insert into ORDER_TRAVELLER (orderid, travellerid)
values ('CA005CF1BE3C4EF68F88ABC7DF30E976', 'EE7A71FB6945483FBF91543DBE851960');
insert into ORDER_TRAVELLER (orderid, travellerid)
values ('E4DD4C45EED84870ABA83574A801083E', 'EE7A71FB6945483FBF91543DBE851960');
drop table if exists users;
create table users(
id varchar(32) default '1' primary key,
email varchar(50) unique not null,
username varchar(50),
password varchar(50),
phoneNum varchar(20),
status int
)engine innodb default charset=utf8;
create trigger users_before_insert before insert on users for each row
begin
if new.id = '1' then
set new.id = upper(replace(uuid(), '-', ''));
end if;
end;
-- 建立role
drop table if exists role;
create table role(
id varchar(32) default '1' primary key,
roleName varchar(50),
roleDesc varchar(50)
)engine innodb default charset=utf8;
create trigger role_before_insert before insert on role for each row
begin
if new.id = '1' then
set new.id = upper(replace(uuid(), '-', ''));
end if;
end;
-- 建立users_role
drop table if exists users_role;
create table users_role(
userId varchar(32),
roleId varchar(32),
primary key (userId, roleId),
foreign key (userId) references users(id),
foreign key (roleId) references role(id)
)engine innodb default charset=utf8;
-- 建立peimission表
create table permission(
id varchar(32) default '1' primary key,
permissionName varchar(50),
url varchar(50)
)engine innodb default charset=utf8;
-- 建立role_permission表
create table role_permission(
permissionId varchar(32),
roleId varchar(32),
primary key (permissionId, roleId),
foreign key (permissionId) references permission(id),
foreign key (roleId) references role(id)
)engine innodb default charset=utf8;
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<security:http pattern="/login.jsp" security="none"/>
<security:http pattern="/failer.jsp" security="none"/>
<security:http pattern="/css/**" security="none"/>
<security:http pattern="/img/**" security="none"/>
<security:http pattern="/plugins/**" security="none"/>
<security:http auto-config="true" use-expressions="false">
<security:intercept-url pattern="/**" access="ROLE_USER,ROLE_ADMIN"/>
<security:form-login
login-page="/login.jsp"
login-processing-url="/login.jsp"
default-target-url="/index.jsp"
authentication-failure-url="/failer.jsp"
authentication-success-forward-url="/pages/main.jsp"
/>
<security:csrf disabled="true"/>
<security:logout invalidate-session="true" logout-url="/logout.do" logout-success-url="/login.jsp" />
security:http>
<security:authentication-manager>
<security:authentication-provider user-service-ref="userService">
<security:password-encoder ref="passwordEncoder"/>
security:authentication-provider>
security:authentication-manager>
<bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
beans>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath*:applicationContext.xml,classpath*:spring-security.xmlparam-value>
context-param>
<filter>
<filter-name>springSecurityFilterChainfilter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class>
filter>
<filter-mapping>
<filter-name>springSecurityFilterChainfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
public interface IUserService extends UserDetailsService {
}
@Service("userService")
public class UserServiceImpl implements IUserService {
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
return null;
}
}
@Repository
public interface IUserDao {
@Select("select * from users where username = #{username}")
UserInfo findByUsername(String username);
}
private String id;
private String username;
private String email;
private String password;
private String phoneNum;
private int status;
private String statusStr;
private List<Role> roles;
private String id;
private String roleName;
private String roleDesc;
private List<Permission> permissions;
private List<UserInfo> users;
private String id;
private String permissionName;
private String url;
private List<Role> roles;
@Service("userService")
public class UserServiceImpl implements IUserService {
@Autowired
private IUserDao userDao;
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserInfo userInfo = userDao.findByUsername(username);
// 处理自己的用户对象封装成UserDetails
User user = new User(userInfo.getUsername(), userInfo.getPassword(), null);
return user;
}
}
@Service("userService")
@Transactional
public class UserServiceImpl implements IUserService {
@Autowired
private IUserDao userDao;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserInfo userInfo = userDao.findByUsername(username);
// 处理自己的用户对象封装成UserDetails
User user = new User(userInfo.getUsername(), "{noop}"+userInfo.getPassword(), getAuthority());
return user;
}
public List<SimpleGrantedAuthority> getAuthority(){
List<SimpleGrantedAuthority> list = new ArrayList<SimpleGrantedAuthority>();
list.add(new SimpleGrantedAuthority("ROLE_USER"));
return list;
}
}
userInfo.getPassword()
加上"{noop}"
User user = new User(userInfo.getUsername(), "{noop}"+userInfo.getPassword(), getAuthority());
<security:authentication-manager>
<security:authentication-provider user-service-ref="userService">
security:authentication-provider>
security:authentication-manager>
@Service("userService")
@Transactional
public class UserServiceImpl implements IUserService {
@Autowired
private IUserDao userDao;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserInfo userInfo = userDao.findByUsername(username);
List<Role> roles = userInfo.getRoles();
List<SimpleGrantedAuthority> authorities = getAuthority(roles);
// 处理自己的用户对象封装成UserDetails
User user = new User(userInfo.getUsername(), "{noop}"+userInfo.getPassword(),
userInfo.getStatus() == 0?false:true, true, true, true, authorities);
return user;
}
public List<SimpleGrantedAuthority> getAuthority(List<Role> roles){
List<SimpleGrantedAuthority> list = new ArrayList<SimpleGrantedAuthority>();
for (Role role : roles) {
list.add(new SimpleGrantedAuthority(role.getRoleName()));
}
return list;
}
}
@Repository
public interface IUserDao {
@Select("select * from users where username = #{username}")
@Results({
@Result(id = true, property = "id", column = "id"),
@Result(property = "username", column = "username"),
@Result(property = "email", column = "email"),
@Result(property = "password", column = "password"),
@Result(property = "phoneNum", column = "phoneNum"),
@Result(property = "status", column = "status"),
@Result(property = "roles", column = "id", javaType = List.class,
many = @Many(select = "com.itheima.ssm.dao.IRoleDao.findRoleByUserId"))
})
UserInfo findByUsername(String username);
}
@Repository
public interface IRoleDao {
@Select("select * from role where id in (select roleId from users_role where userId = #{userId})")
List<Role> findRoleByUserId(String userId);
}
<div class="pull-right">
<a href="${pageContext.request.contextPath}/logout.do"
class="btn btn-default btn-flat">注销</a>
</div>
<security:logout invalidate-session="true" logout-url="/logout.do" logout-success-url="/login.jsp" />
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private IUserService userService = new UserServiceImpl();
@RequestMapping("/findAll.do")
public ModelAndView findAll(){
ModelAndView mv = new ModelAndView();
List<UserInfo> userInfos = userService.findAll();
mv.addObject("userList", userInfos);
mv.setViewName("user-list");
return mv;
}
}
public interface IUserService extends UserDetailsService {
List<UserInfo> findAll();
}
@Override
public List<UserInfo> findAll() {
List<UserInfo> userInfos= userDao.findAll();
return userInfos;
}
@Select("select * from users")
List<UserInfo> findAll();
@RequestMapping("/save.do")
public String save(UserInfo userInfo){
userService.save(userInfo);
return "redirect:findAll.do";
}
void save(UserInfo userInfo);
@Override
public void save(UserInfo userInfo) {
userDao.save(userInfo);
}
@Insert("insert into users(email, username, password, phoneNum, status) values (#{email}, #{username}, #{password}, #{phoneNum}, #{status})")
void save(UserInfo userInfo);
<!-- 配置加密类 -->
<bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"/>
@Override
public void save(UserInfo userInfo) {
// 密码加密
userInfo.setPassword(bCryptPasswordEncoder.encode(userInfo.getPassword()));
userDao.save(userInfo);
}
<security:authentication-manager>
<security:authentication-provider user-service-ref="userService">
<security:password-encoder ref="passwordEncoder"/>
security:authentication-provider>
security:authentication-manager>
{noop}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserInfo userInfo = userDao.findByUsername(username);
List<Role> roles = userInfo.getRoles();
List<SimpleGrantedAuthority> authorities = getAuthority(roles);
// 处理自己的用户对象封装成UserDetails
User user = new User(userInfo.getUsername(), "{noop}"+userInfo.getPassword(),
userInfo.getStatus() == 0?false:true, true, true, true, authorities);
return user;
}
<a href="${pageContext.request.contextPath}/user/findById.do?id=${user.id}" class="btn bg-olive btn-xs">详情</a>
@RequestMapping("/findById.do")
public ModelAndView findById(@RequestParam(name = "id", required = true)String id) {
ModelAndView mv = new ModelAndView();
UserInfo userInfo = userService.findById(id);
mv.addObject("user", userInfo);
mv.setViewName("user-show");
return mv;
}
public interface IUserService extends UserDetailsService {
List<UserInfo> findAll();
void save(UserInfo userInfo);
UserInfo findById(String id);
}
@Override
public UserInfo findById(String id) {
return userDao.findById(id);
}
@Select("select * from users where id = #{id}")
@Results({
@Result(id = true, property = "id", column = "id"),
@Result(property = "username", column = "username"),
@Result(property = "email", column = "email"),
@Result(property = "password", column = "password"),
@Result(property = "phoneNum", column = "phoneNum"),
@Result(property = "status", column = "status"),
@Result(property = "roles", column = "id", javaType = List.class,
many = @Many(select = "com.itheima.ssm.dao.IRoleDao.findRoleByUserId"))
})
UserInfo findById(String id);
@Repository
public interface IRoleDao {
@Select("select * from role where id in (select roleId from users_role where userId = #{userId})")
@Results({
@Result(id = true, property = "id", column = "id"),
@Result(property = "roleName", column = "roleName"),
@Result(property = "roleDesc", column = "roleDesc"),
@Result(property = "permissions", column = "id", javaType = List.class,
many = @Many(select = "com.itheima.ssm.dao.IPermissionDao.findByRoleId"))
})
List<Role> findRoleByUserId(String userId);
}
public interface IPermissionDao {
@Select("select * from permission where id in (select permissionId from role_permission where roleId = #{roleId})")
List<Permission> findByRoleId(String roleId);
}
@Controller
@RequestMapping("/role")
public class RoleController {
@Autowired
private IRoleService roleService;
@RequestMapping("/findAll.do")
public ModelAndView findAll() {
ModelAndView mv = new ModelAndView();
List<Role> roles = roleService.findAll();
mv.addObject("roleList", roles);
mv.setViewName("role-list");
return mv;
}
}
@Service
public interface IRoleService {
List<Role> findAll();
}
public class RoleServiceImpl implements IRoleService {
@Autowired
private IRoleDao roleDao;
@Override
public List<Role> findAll() {
return roleDao.findAll();
}
}
@Select("select * from role")
List<Role> findAll();
@RequestMapping("/save.do")
public String save(Role role) {
roleService.save(role);
return "redirect:findAll.do";
}
public interface IRoleService {
List<Role> findAll();
void save(Role role);
}
@Override
public void save(Role role) {
roleDao.save(role);
}
@Insert("insert into role(roleName, roleDesc) values(#{roleName}, #{roleDesc})")
void save(Role role);
href="${pageContext.request.contextPath}/permission/findAll.do">
<i class="fa fa-circle-o"></i> 资源权限管理
@Controller
@RequestMapping("/permission")
public class PermissionController {
@Autowired
private IPermissionService permissionService;
@RequestMapping("/findAll")
public ModelAndView findAll(){
ModelAndView mv = new ModelAndView();
List<Permission> permissions = permissionService.findAll();
mv.addObject("permissionList", permissions);
mv.setViewName("permission-list");
return mv;
}
}
public interface IPermissionService {
List<Permission> findAll();
}
@Override
public List<Permission> findAll() {
return permissionDao.findAll();
}
@Select("select * from permission")
List<Permission> findAll();
@RequestMapping("/save.do")
public String save(Permission permission){
permissionService.save(permission);
return "redirect:findAll.do";
}
void save(Permission permission);
@Override
public void save(Permission permission) {
permissionDao.save(permission);
}
@Insert("insert into permission (permissionName, url) values (#{permissionName}, #{url})")
void save(Permission permission);
<a href="${pageContext.request.contextPath}/user/findUserByIdAndAllRole.do?id=${user.id}" class="btn bg-olive btn-xs">添加角色a>
@RequestMapping("/findUserByIdAndAllRole.do")
public ModelAndView findUserByIdAndAllRole(@RequestParam(name = "id", required = true) String userid) {
ModelAndView mv = new ModelAndView();
UserInfo user = userService.findById(userid);
mv.addObject("user", user);
List<Role> otherRoles = userService.findOtherRoles(userid);
mv.addObject("roleList", otherRoles);
mv.setViewName("user-role-add");
return mv;
}
List<Role> findOtherRoles(String userid);
@Override
public List<Role> findOtherRoles(String userid) {
return userDao.findOtherRoles(userid);
}
@Select("select * from role where id not in (select roleId from users_role where userId = #{userid})")
List<Role> findOtherRoles(String userid);
@RequestMapping("/addRoleToUser.do")
public String addRoleToUser(@RequestParam(name = "userId") String userId, @RequestParam(name = "ids") String[] roleIds){
userService.addRoleToUser(userId, roleIds);
return "redirect:findAll.do";
}
void addRoleToUser(String userId, String[] roleIds);
@Override
public void addRoleToUser(String userId, String[] roleIds) {
for (String roleId : roleIds) {
userDao.addRoleToUser(userId, roleId);
}
}
@Insert("insert into users_role values (#{userId}, #{roleId})")
void addRoleToUser(@Param("userId") String userId, @Param("roleId") String roleId);
@RequestMapping("/findRoleByIdAndAllPermission.do")
public ModelAndView findRoleByIdAndAllPermission(@RequestParam(name = "id") String roleId){
ModelAndView mv = new ModelAndView();
Role role = roleService.findById(roleId);
mv.addObject("role", role);
List<Permission> permissionList = roleService.findOtherPermissions(roleId);
mv.addObject("permissionList", permissionList);
mv.setViewName("role-permission-add");
return mv;
}
List<Permission> findOtherPermissions(String roleId);
@Override
public List<Permission> findOtherPermissions(String roleId) {
return roleDao.findOtherPermissions(roleId);
}
@Select("select * from permission where id not in (select permissionId from role_permission where roleId = #{roleId})")
List<Permission> findOtherPermissions(String roleId);
@RequestMapping("/addPermissionToRole.do")
public String addPermissionToRole(@RequestParam("roleId") String roleId, @RequestParam("ids") String[] ids){
roleService.addPermissionToRole(roleId, ids);
return "redirect:findAll.do";
}
void addPermissionToRole(String roleId, String[] ids);
@Override
public void addPermissionToRole(String roleId, String[] ids) {
for (String id : ids) {
roleDao.addPermissionToRole(roleId, id);
}
}
@Insert("insert into role_permission values (#{id}, #{roleId})")
void addPermissionToRole(@Param("roleId") String roleId, @Param("id") String id);
<security:global-method-security jsr250-annotations="enabled"/>
@RequestMapping("/findAll.do")
@RolesAllowed("ADMIN") // ROlE_可省
public ModelAndView findAll(@RequestParam( name = "page", required = true, defaultValue = "1")Integer page,
@RequestParam( name = "size", required = true, defaultValue = "4")Integer size) {
ModelAndView mv = new ModelAndView();
List<Orders> orders = ordersService.findAll(page, size);
PageInfo pageInfo = new PageInfo(orders);
mv.addObject("pageInfo", pageInfo);
mv.setViewName("orders-page-list");
return mv;
}
<dependency>
<groupId>javax.annotationgroupId>
<artifactId>jsr250-apiartifactId>
<version>1.0version>
dependency>
<error-page>
<error-code>403error-code>
<location>/403.jsplocation>
error-page>
<security:global-method-security secured-annotations="enabled"/>
@RequestMapping("/findAll.do")
// @RolesAllowed("ADMIN") // ROlE_可省
@Secured("ROLE_ADMIN") // ROLE_不可省
public ModelAndView findAll(@RequestParam( name = "page", required = true, defaultValue = "1")Integer page,
@RequestParam( name = "size", required = true, defaultValue = "4")Integer size) {
ModelAndView mv = new ModelAndView();
List<Orders> orders = ordersService.findAll(page, size);
PageInfo pageInfo = new PageInfo(orders);
mv.addObject("pageInfo", pageInfo);
mv.setViewName("orders-page-list");
return mv;
}
<security:global-method-security pre-post-annotations="enabled"/>
@RequestMapping("/findAll.do")
// @RolesAllowed("ADMIN") // ROlE_可省
// @Secured("ROLE_ADMIN") // ROLE_不可省
@PreAuthorize("hasRole('ROLE_ADMIN')")
public ModelAndView findAll(@RequestParam( name = "page", required = true, defaultValue = "1")Integer page,
@RequestParam( name = "size", required = true, defaultValue = "4")Integer size) {
ModelAndView mv = new ModelAndView();
List<Orders> orders = ordersService.findAll(page, size);
PageInfo pageInfo = new PageInfo(orders);
mv.addObject("pageInfo", pageInfo);
mv.setViewName("orders-page-list");
return mv;
}
@RequestMapping("/findById.do")
@PreAuthorize("authentication.principal.username == 'sss'")
public ModelAndView findById(@RequestParam(name = "id", required = true) String id) {
ModelAndView mv = new ModelAndView();
Orders orders = ordersService.findById(id);
mv.addObject("orders", orders);
mv.setViewName("orders-show");
return mv;
}
<dependency>
<groupId>org.springframework.securitygroupId>
<artifactId>spring-security-taglibsartifactId>
<version>${spring.security.version}version>
dependency>
<%@taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
<security:authentication property="principal.username"/>
<li id="system-setting">
<security:authorize access="hasRole('ROLE_ADMIN')">
<a
href="${pageContext.request.contextPath}/user/findAll.do"> <i
class="fa fa-circle-o">i> 用户管理
a>
security:authorize>
li>
<security:http auto-config="true" use-expressions="true">
<security:intercept-url pattern="/**" access="has('ROLE_USER','ROLE_ADMIN')"/>
<bean id="webSecurityExpressionHandler" class="org.springframework.security.web.access.expression.DefaultWebSecurityExpressionHandler"/>
-- 建立sysLog表
create table sysLog(
id varchar(32) default '1' primary key,
visitTime timestamp,
username varchar(50),
ip varchar(30),
url varchar(50),
executionTime int,
method varchar(200)
)engine innodb default charset=utf8;
create trigger sysLog_before_insert before insert on sysLog for each row
begin
if new.id = '1' then
set new.id = upper(replace(uuid(), '-', ''));
end if;
end;
public class SysLog implements Serializable {
private String id;
private Date visitTime;
private String visitTimeStr;
private String username;
private String ip;
private String url;
private Long executionTime;
private String method;
public class LogAOP {
@Autowired
private HttpServletRequest request;
@Autowired
private ISysLogService sysLogService;
private Date visitTime; //开始时间
private Class clazz; //访问的类
private Method method;//访问的方法
//前置通知 主要是获取开始时间,执行的类是哪一个,执行的是哪一个方法
@Before("execution(* com.itheima.ssm.controller.*.*(..))")
public void doBefore(JoinPoint jp) throws NoSuchMethodException {
visitTime = new Date();//当前时间就是开始访问的时间
clazz = jp.getTarget().getClass(); //具体要访问的类
String methodName = jp.getSignature().getName(); //获取访问的方法的名称
Object[] args = jp.getArgs();//获取访问的方法的参数
//获取具体执行的方法的Method对象
if (args == null || args.length == 0) {
method = clazz.getMethod(methodName); //只能获取无参数的方法
} else {
Class[] classArgs = new Class[args.length];
for (int i = 0; i < args.length; i++) {
classArgs[i] = args[i].getClass();
}
clazz.getMethod(methodName, classArgs);
}
}
//后置通知
@After("execution(* com.itheima.ssm.controller.*.*(..))")
public void doAfter(JoinPoint jp) throws Exception {
long time = new Date().getTime() - visitTime.getTime(); //获取访问的时长
String url = "";
//获取url
if (clazz != null && method != null && clazz != LogAOP.class) {
//1.获取类上的@RequestMapping("/orders")
RequestMapping classAnnotation = (RequestMapping) clazz.getAnnotation(RequestMapping.class);
if (classAnnotation != null) {
String[] classValue = classAnnotation.value();
//2.获取方法上的@RequestMapping(xxx)
RequestMapping methodAnnotation = method.getAnnotation(RequestMapping.class);
if (methodAnnotation != null) {
String[] methodValue = methodAnnotation.value();
url = classValue[0] + methodValue[0];
//获取访问的ip
String ip = request.getRemoteAddr();
//获取当前操作的用户
SecurityContext context = SecurityContextHolder.getContext();//从上下文中获了当前登录的用户
User user = (User) context.getAuthentication().getPrincipal();
String username = user.getUsername();
//将日志相关信息封装到SysLog对象
SysLog sysLog = new SysLog();
sysLog.setExecutionTime(time); //执行时长
sysLog.setIp(ip);
sysLog.setMethod("[类名] " + clazz.getName() + "[方法名] " + method.getName());
sysLog.setUrl(url);
sysLog.setUsername(username);
sysLog.setVisitTime(visitTime);
//调用Service完成操作
sysLogService.save(sysLog);
}
}
}
}
}
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListenerlistener-class>
listener>