1.空属性赋值问题
(1)编写MyBeanUtils工具类;
public class MyBeanUtils {
public static String[] getNullPropertyNames(Object source){
BeanWrapper beanWrapper = new BeanWrapperImpl(source);
PropertyDescriptor[] pds = beanWrapper.getPropertyDescriptors();
List<String> nullPropertyNames = new ArrayList<>();
for (PropertyDescriptor pd:pds){
String propertyName = pd.getName();
if (beanWrapper.getPropertyValue(propertyName)==null){
nullPropertyNames.add(propertyName);
}
}
return nullPropertyNames.toArray(new String[nullPropertyNames.size()]);
}
}
(2)编写NewServiceImpl类
@Override
public News updateNew(Long id, News news) {
News news1 = newRepository.findById(id).orElse(null);
if (news1==null){
// System.out.println("未获得更新对象");
throw new NotFoundException("该新闻不存在");
}
BeanUtils.copyProperties(news,news1, MyBeanUtils.getNullPropertyNames(news));
news1.setUpdateTime(new Date());
return newRepository.save(news1);
}
(3)界面展示
2.aspect日志
(1)编写LogAspect类;
@Aspect
@Component
public class LogAspect {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Pointcut("execution(* com.roger0123.news.web.*.*(..))")
public void log(){}
@Before("log()")
public void doBefore(JoinPoint joinPoint){
//获得request
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
//获得url和ip...
String url = request.getRequestURL().toString();
String ip = request.getRemoteAddr();
String classMethod = joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName();
Object[] args = joinPoint.getArgs();
RequestLog requestLog = new RequestLog(url,ip,classMethod,args);
logger.info("Request :{}",requestLog);
logger.info("--------------doBefore----------------");
}
@After("log()")
public void doAfter(JoinPoint joinPoint){
logger.info("--------------doAfter----------------");
}
@AfterReturning(returning = "result",pointcut = "log()")
private void adAfterReturn(Object result){
logger.info("Result :{}",result);
}
private class RequestLog{
private String url;
private String ip;
private String classMethod;
private Object[] args;
public RequestLog(String url,String ip,String classMethod,Object[] args){
this.url = url;
this.ip = ip;
this.classMethod = classMethod;
this.args =args;
}
@Override
public String toString() {
return "RequestLog{" +
"url='" + url + '\'' +
", ip='" + ip + '\'' +
", classMethod='" + classMethod + '\'' +
", args=" + Arrays.toString(args) +
'}';
}
}
}
(2)界面展示
3.shiro配置
(1)编写permission类
@Entity
@Table(name = "t_permission")
public class Permission implements Serializable {
private static final long serialVersionUID = 7302091622398564357L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String code;
private String description;
public static long getSerialVersionUID() {
return serialVersionUID;
}
//此处省略get和set方法
}
(2)编写Role实体类
@Entity
@Table(name = "t_role")
public class Role implements Serializable {
private static final long serialVersionUID = 1505117035812042932L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
@ManyToMany(mappedBy = "roles")
private Set<User> users = new HashSet<>(0);
@ManyToMany(fetch = FetchType.EAGER)
private Set<Permission> permissions = new HashSet<>(0);
public static long getSerialVersionUID() {
return serialVersionUID;
}
@Override
public String toString() {
return "Role{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", description='" + description + '\'' +
", users=" + users +
", permissions=" + permissions +
'}';
}
//省略get和set方法
}
(3)编写newrealm类
public class NewsRealm extends AuthorizingRealm {
public void setName(String name){setName("newsRealm");}
@Autowired
private UserService userService;
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
UsernamePasswordToken upToken = (UsernamePasswordToken)authenticationToken;
String username = upToken.getUsername();
String password = new String(upToken.getPassword());
User user = userService.checkUsers(username,password);
if(user!=null){
return new SimpleAuthenticationInfo(user,user.getPassword(),this.getName());
}
return null;
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//获取认证用户数据
User user =(User)principalCollection.getPrimaryPrincipal();
//构造认证数据
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
Set<Role> roles = user.getRoles();
for(Role role:roles){
//添加角色信息
info.addRole(role.getName());
for(Permission permission:role.getPermissions()){
//添加权限信息
info.addStringPermission(permission.getCode());
}
}
return info;
}
}
(4)编写shiroConfiguration类
@Configuration
public class ShiroConfiguration {
//创建realm
@Bean
public NewsRealm getRealm(){return new NewsRealm();}
//创建安全管理器
@Bean
public SecurityManager securityManager(NewsRealm realm){
//使用默认的安全管理器
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(realm);
//将自定义的realm交给安全管理器统一调度
return securityManager;
}
//配置shiro过滤工厂
@Bean
public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){
ShiroFilterFactoryBean shiroFilterFactory =new ShiroFilterFactoryBean();
shiroFilterFactory.setSecurityManager(securityManager);
//通用配置
shiroFilterFactory.setLoginUrl("/admin");
shiroFilterFactory.setUnauthorizedUrl("/admin");
/*
* key:请求路径
* value:过滤器类型
*/
Map<String,String> filterMap = new LinkedHashMap<>();
filterMap.put("/admin/login","anon");
filterMap.put("/admin/**","authc");
shiroFilterFactory.setFilterChainDefinitionMap(filterMap);
return shiroFilterFactory;
}
//开启shiro注解支持
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager){
AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
advisor.setSecurityManager(securityManager);
return advisor;
}
}
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.3.2</version>
</dependency>