作者 朱兆平

用户权限目录表优化

正在显示 25 个修改的文件 包含 778 行增加184 行删除
... ... @@ -17,6 +17,7 @@
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Greenwich.BUILD-SNAPSHOT</spring-cloud.version>
<fastjson_version>1.2.28</fastjson_version>
</properties>
<dependencies>
... ... @@ -85,6 +86,11 @@
<artifactId>commons-codec</artifactId>
<version>1.11</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson_version}</version>
</dependency>
<!-- tools-->
<!-- alibaba的druid数据库连接池 -->
<dependency>
... ...
... ... @@ -26,8 +26,8 @@ public class ImfLog {
public String Home(Model model){
PERMISSION msg = new PERMISSION();
msg.setDescription("权限描述");
msg.setPermissionName("权限名称");
msg.setPermissionSign("权限路径");
msg.setName("权限名称");
msg.setPermissionOrder("权限路径");
model.addAttribute("msg", msg);
return "home";
}
... ...
package com.tianbo.warehouse.controller;
import com.github.pagehelper.PageInfo;
import com.tianbo.warehouse.controller.response.ResultJson;
import com.tianbo.warehouse.dao.PERMISSIONMapper;
import com.tianbo.warehouse.model.PERMISSION;
import com.tianbo.warehouse.model.ROLE;
import com.tianbo.warehouse.service.PermissionService;
import org.apache.cxf.annotations.Logging;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
@Logging
@RestController()
public class PermssionController {
@Autowired
PermissionService permissionService;
@GetMapping("/perm/list")
public PageInfo<PERMISSION> list(@RequestParam(value = "pageNum",required = false,defaultValue = "1")
int pageNum,
@RequestParam(value = "pageSize",required = false,defaultValue = "5")
int pageSize){
return permissionService.findAll(pageNum,pageSize);
}
@PostMapping("/perm/add")
public ResultJson add(@RequestBody PERMISSION permission){
int i =permissionService.insertSelective(permission);
ResultJson resultJson = new ResultJson();
if (1==i){
resultJson = new ResultJson("200","添加账户成功");
}else {
resultJson = new ResultJson("500","insert faild");
}
return resultJson;
}
@GetMapping("/perm/userMenus")
public Map<String,Object> getLoginUserMenus(){
try{
UserDetails userDetails =(UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
int i;
}catch (Exception e){
e.printStackTrace();
}
Map<String,Object> menuMap = permissionService.getUserMenus();
return menuMap;
}
}
... ...
package com.tianbo.warehouse.controller;
import com.github.pagehelper.PageInfo;
import com.tianbo.warehouse.controller.response.ResultJson;
import com.tianbo.warehouse.model.ROLE;
import com.tianbo.warehouse.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController()
public class RoleController {
@Autowired
RoleService roleService;
@GetMapping("/role/list")
public PageInfo<ROLE> list(@RequestParam(value = "pageNum",required = false,defaultValue = "1")
int pageNum,
@RequestParam(value = "pageSize",required = false,defaultValue = "5")
int pageSize){
return roleService.findAll(pageNum,pageSize);
}
@PostMapping("/role/add")
public ResultJson add(@RequestBody ROLE role){
int i =roleService.insertSelective(role);
ResultJson resultJson = new ResultJson();
if (1==i){
resultJson = new ResultJson("200","添加账户成功");
}else {
resultJson = new ResultJson("500","insert faild");
}
return resultJson;
}
}
... ...
package com.tianbo.warehouse.controller;
import com.github.pagehelper.PageInfo;
import com.tianbo.warehouse.controller.response.ResultJson;
import com.tianbo.warehouse.model.USERS;
import com.tianbo.warehouse.service.UserService;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ocsp.ResponseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@RestController
... ... @@ -21,7 +25,7 @@ public class UserController {
@GetMapping("/user/list")
public PageInfo<USERS> list(@RequestParam(value = "pageNum",required = false,defaultValue = "1")
int pageNum,
@RequestParam(value = "pageSize",required = false,defaultValue = "10")
@RequestParam(value = "pageSize",required = false,defaultValue = "5")
int pageSize){
return userService.selectAllUser(pageNum,pageSize);
}
... ... @@ -32,4 +36,42 @@ public class UserController {
UserDetails userDetails =(UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return "欢迎回来:"+userDetails.getUsername();
}
@PutMapping("/user/edit")
public ResultJson updateUserById(@RequestBody USERS user){
int i = userService.updateByPrimaryKeySelective(user);
ResultJson resultJson = new ResultJson();
if (1==i){
resultJson = new ResultJson("200","success");
}else {
resultJson = new ResultJson("500","update faild");
}
return resultJson;
}
@PostMapping("/user/add")
public ResultJson addUser(@RequestBody USERS user,HttpServletRequest request,HttpServletResponse response){
int i = userService.insertSelective(user);
ResultJson resultJson = new ResultJson();
if (1==i){
resultJson = new ResultJson("200","新建账户成功");
}else {
resultJson = new ResultJson("500","insert faild");
}
return resultJson;
}
@DeleteMapping("/user/del")
public ResultJson delUser(@RequestBody USERS user,HttpServletRequest request,HttpServletResponse response){
//String username = getusername();
int i = userService.deleteByPrimaryKey(user.getUserId());
ResultJson resultJson = new ResultJson();
if (1==i){
resultJson = new ResultJson("200","删除账户成功");
}else {
resultJson = new ResultJson("500","delete faild");
}
return resultJson;
}
}
... ...
package com.tianbo.warehouse.controller.response;
import com.alibaba.fastjson.JSON;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
/**
* 统一拦截response接口返回数据
*/
//@ControllerAdvice
public class RestControllerResponseAdvice implements ResponseBodyAdvice<Object>{
/**
* //判断支持的类型,因为我们定义的BaseResponseVo 里面的data可能是任何类型,这里就不判断统一放过
* 如果你想对执行的返回体进行操作,可将上方的Object换成你自己的类型
* @param returnType
* @param converterType
* @return
*/
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType){
return true;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response){
// 对body进行封装处理
if (body instanceof String) {
String msg = (String) body;
ResultJson resultJson = new ResultJson("-1", msg);
// 因为在controller层中返回的是String类型,这边如果换成ResultJson的话,会导致StringMessageConverter方法类型转换异常,所以这边将对象转成字符串
return JSON.toJSONString(resultJson);
} else if (body instanceof Object) {
Object data = (Object) body;
ResultJson resultJson = new ResultJson(data);
return resultJson;
}
return body;
}
}
... ...
package com.tianbo.warehouse.controller.response;
import java.io.Serializable;
public class ResultJson implements Serializable{
private static final long serialVersionUID = 1L;
// 状态码 正确为0
private String code = "0";
// 错误描述
private String msg = "";
// 返回对象
private Object data = "";
public ResultJson() {
}
public ResultJson(String code) {
this.code = code;
}
public ResultJson(String code, String msg) {
this.code = code;
this.msg = msg;
}
public ResultJson(Object data) {
this.data = data;
}
public ResultJson(String code, String msg, Object data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
... ...
... ... @@ -20,6 +20,8 @@ public interface PERMISSIONMapper {
List<PERMISSION> findAll();
List<PERMISSION> getAllMenus();
List<PERMISSION> findByUserId(Integer userId);
List<String> findRoleListByUrl(String permissionUrl);
... ...
package com.tianbo.warehouse.model;
import java.util.List;
public class PERMISSION {
private Integer permissionId;
private String permissionName;
private String name;
private String permissionSign;
private String permissionOrder;
private String description;
private String groupName;
private Boolean ismenu;
private Boolean hidden;
private Integer parentId;
... ... @@ -17,34 +21,32 @@ public class PERMISSION {
private String url;
private String ext1;
private String method;
private String ext2;
private String iconCls;
private String ext3;
private String component;
private List<PERMISSION> children;
public Integer getPermissionId() {
return permissionId;
}
public void setPermissionId(Integer permissionId) {
this.permissionId = permissionId;
}
public String getPermissionName() {
return permissionName;
public String getName() {
return name;
}
public void setPermissionName(String permissionName) {
this.permissionName = permissionName == null ? null : permissionName.trim();
public void setName(String name) {
this.name = name;
}
public String getPermissionSign() {
return permissionSign;
public String getPermissionOrder() {
return permissionOrder;
}
public void setPermissionSign(String permissionSign) {
this.permissionSign = permissionSign == null ? null : permissionSign.trim();
public void setPermissionOrder(String permissionOrder) {
this.permissionOrder = permissionOrder;
}
public String getDescription() {
... ... @@ -55,12 +57,12 @@ public class PERMISSION {
this.description = description == null ? null : description.trim();
}
public String getGroupName() {
return groupName;
public Boolean getIsmenu() {
return ismenu;
}
public void setGroupName(String groupName) {
this.groupName = groupName == null ? null : groupName.trim();
public void setIsmenu(Boolean ismenu) {
this.ismenu = ismenu;
}
public Integer getParentId() {
... ... @@ -87,28 +89,35 @@ public class PERMISSION {
this.url = url == null ? null : url.trim();
}
public String getExt1() {
return ext1;
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public void setExt1(String ext1) {
this.ext1 = ext1 == null ? null : ext1.trim();
public String getIconCls() {
return iconCls;
}
public String getExt2() {
return ext2;
public void setIconCls(String iconCls) {
this.iconCls = iconCls;
}
public void setExt2(String ext2) {
this.ext2 = ext2 == null ? null : ext2.trim();
public String getComponent() {
return component;
}
public String getExt3() {
return ext3;
public void setComponent(String component) {
this.component = component;
}
public void setExt3(String ext3) {
this.ext3 = ext3 == null ? null : ext3.trim();
public List<PERMISSION> getChildren() {
return children;
}
public void setChildren(List<PERMISSION> children) {
this.children = children;
}
}
\ No newline at end of file
... ...
... ... @@ -35,11 +35,11 @@ public class USERS implements UserDetails {
private String userface;
private String ext1;
private String realname;
private String ext2;
private String email;
private String ext3;
private Integer age;
private List<ROLE> roles;
... ... @@ -135,28 +135,28 @@ public class USERS implements UserDetails {
this.userface = userface == null ? null : userface.trim();
}
public String getExt1() {
return ext1;
public String getRealname() {
return realname;
}
public void setExt1(String ext1) {
this.ext1 = ext1 == null ? null : ext1.trim();
public void setRealname(String realname) {
this.realname = realname;
}
public String getExt2() {
return ext2;
public String getEmail() {
return email;
}
public void setExt2(String ext2) {
this.ext2 = ext2 == null ? null : ext2.trim();
public void setEmail(String email) {
this.email = email;
}
public String getExt3() {
return ext3;
public Integer getAge() {
return age;
}
public void setExt3(String ext3) {
this.ext3 = ext3 == null ? null : ext3.trim();
public void setAge(Integer age) {
this.age = age;
}
public List<ROLE> getRoles() {
... ... @@ -176,8 +176,8 @@ public class USERS implements UserDetails {
}
/**
* 账户未过期
* @return
*
* @return 账户未过期
*/
@Override
public boolean isAccountNonExpired(){
... ... @@ -185,17 +185,17 @@ public class USERS implements UserDetails {
}
/**
* 账户未锁定
* @return
*
* @return 账户未锁定
*/
@Override
public boolean isAccountNonLocked(){
return true;
}
/**密码未过期
/**
*
* @return
* @return 密码未过期
*/
@Override
public boolean isCredentialsNonExpired(){
... ... @@ -203,8 +203,8 @@ public class USERS implements UserDetails {
}
/**
* //账户可用
* @return
*
* @return 账户可用
*/
@Override
public boolean isEnabled(){
... ... @@ -212,8 +212,8 @@ public class USERS implements UserDetails {
}
/**
* user的权限列表
* @return
*
* @return user的权限列表
*/
@Override
public Collection<? extends GrantedAuthority> getAuthorities(){
... ...
... ... @@ -36,24 +36,42 @@ public class MyAccessDecisionManager implements AccessDecisionManager{
c = iter.next();
needRole = c.getAttribute();
//如果URL需要的权限为匿名访问,返回
if(("ROLE_ANONYMOUS").equals(needRole.trim())){
return;
}
//authentication 为在注释1 中循环添加到 GrantedAuthority 对象中的权限信息集合
for(GrantedAuthority ga : authentication.getAuthorities()) {
//如果URL需要的权限为匿名访问,返回
if(("ROLE_admin").equals(ga.getAuthority())){
return;
}
if(needRole.trim().equals(ga.getAuthority())) {
return;
}
}
}
throw new AccessDeniedException("权限不足!");
/**
* ExceptionTranslationFilter
ExceptionTranslationFilter 是Spring Security的核心filter之一,用来处理AuthenticationException和AccessDeniedException两种异常。
在我们的例子中,AuthenticationException指的是未登录状态下访问受保护资源,AccessDeniedException指的是登陆了但是由于权限不足(比如普通用户访问管理员界面)。
ExceptionTranslationFilter 持有两个处理类,分别是AuthenticationEntryPoint和AccessDeniedHandler。
ExceptionTranslationFilter 对异常的处理是通过这两个处理类实现的,处理规则很简单:
规则1. 如果异常是 AuthenticationException,使用 AuthenticationEntryPoint 处理
规则2. 如果异常是 AccessDeniedException 且用户是匿名用户,使用 AuthenticationEntryPoint 处理
规则3. 如果异常是 AccessDeniedException 且用户不是匿名用户,如果否则交给 AccessDeniedHandler 处理。
*/
}
@Override
public boolean supports(ConfigAttribute var1){
return true;
}
... ...
... ... @@ -15,7 +15,7 @@ import java.io.IOException;
public class MyFilterSecurityInterceptor extends AbstractSecurityInterceptor implements Filter {
@Autowired
private FilterInvocationSecurityMetadataSource securityMetadataSource;
private MyInvocationSecurityMetadataSourceService securityMetadataSource;
@Autowired
... ...
... ... @@ -9,6 +9,7 @@ import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Service;
import org.springframework.util.AntPathMatcher;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
... ... @@ -22,11 +23,12 @@ public class MyInvocationSecurityMetadataSourceService implements FilterInvocati
@Autowired
PERMISSIONMapper permissionMapper;
AntPathMatcher pathMatcher = new AntPathMatcher();
private HashMap<String, Collection<ConfigAttribute>> map =null;
/**
* 加载权限表中所有权限
* 加载权限表中所有权限,还是加载URL所需要的权限
*/
public void loadResourceDefine(String requestUrl){
map = new HashMap<>();
... ... @@ -41,37 +43,86 @@ public class MyInvocationSecurityMetadataSourceService implements FilterInvocati
// 此处添加的信息将会作为MyAccessDecisionManager类的decide的第三个参数。
//CFG存储访问的URL需要的权限"ROLE_??"LIST
List<String> urlOfRoles = permissionMapper.findRoleListByUrl(requestUrl);
String pUrl = permission.getUrl();
List<String> urlOfRoles = permissionMapper.findRoleListByUrl(pUrl);
//路径适配,这个很重要,是配上后会包含其他适配的所有权限,比如/**与/user/List是可以适配上的,
// 那么/**这个通用适配是要有/user/list这个路径所对应的角色信息的
if(pathMatcher.match(pUrl,requestUrl)){
}
for (String roleName:urlOfRoles) {
cfg = new SecurityConfig(roleName);
array.add(cfg);
if(null!=roleName) {
cfg = new SecurityConfig(roleName);
array.add(cfg);
}
}
//用权限的getUrl() 作为map的key,用ConfigAttribute的集合作为 value,
map.put(permission.getUrl(), array);
map.put(pUrl, array);
}
}
/**
* 此方法是为了判定用户请求的url 是否在权限表中,
* 如果在权限表中,则返回给 decide 方法,
* 所有的权限表中的url所对应的角色信息
* @return 有就返回集合 没有就返回null
*/
public Collection<ConfigAttribute> loadResourceDefine(){
Collection<ConfigAttribute> array;
ConfigAttribute cfg;
List<PERMISSION> permissions = permissionMapper.findAll();
for(PERMISSION permission : permissions) {
array = new ArrayList<>();
//此处只添加了用户的名字,其实还可以添加更多权限的信息,
// 例如请求方法到ConfigAttribute的集合中去。
// 此处添加的信息将会作为MyAccessDecisionManager类的decide的第三个参数。
//CFG存储访问的URL需要的权限"ROLE_??"LIST
String pUrl = permission.getUrl();
List<String> urlOfRoles = permissionMapper.findRoleListByUrl(pUrl);
for (String roleName:urlOfRoles) {
if(null!=roleName) {
cfg = new SecurityConfig(roleName);
array.add(cfg);
}
}
return array;
}
return null;
}
/**
* 此方法是为了判定用户请求的url权限 是否有对应的角色,
* 如果有对应角色信息,则返回给 decide 方法,
* 用来判定用户是否有此权限。如果不在权限表中则放行。
* 如果getAttributes(Object o)方法返回null的话,意味着当前这个请求不需要任何角色就能访问
* getAttributes(Object o)方法返回的集合最终会来到AccessDecisionManager类中
* @param object
* @return
* @throws IllegalArgumentException
*/
@Override
public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
//清楚地址
String requestUrl = ((FilterInvocation)object).getRequestUrl();
if(map ==null) {loadResourceDefine(requestUrl);}
String requestUrl = ((FilterInvocation)object).getRequest().getRequestURI();
//每次判定的时候都加载权限对应URL表
// if(map ==null) {
loadResourceDefine(requestUrl);
// }
//object 中包含用户请求的request 信息
HttpServletRequest request = ((FilterInvocation) object).getHttpRequest();
AntPathRequestMatcher matcher;
String resUrl;
for(Iterator<String> iter = map.keySet().iterator(); iter.hasNext(); ) {
resUrl = iter.next();
matcher = new AntPathRequestMatcher(resUrl);
AntPathRequestMatcher matcher = new AntPathRequestMatcher(resUrl);
if(matcher.matches(request)) {
return map.get(resUrl);
}
... ... @@ -79,8 +130,13 @@ public class MyInvocationSecurityMetadataSourceService implements FilterInvocati
return null;
}
/**
*
* @return 所有URL对应的所有权限
*/
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
// return loadResourceDefine();
return null;
}
... ...
package com.tianbo.warehouse.security.config;
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateConverter implements Converter<String,Date>{
private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
@Override
public Date convert(String s) {
if ("".equals(s) || s == null) {
return null;
}
try {
return simpleDateFormat.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
... ...
package com.tianbo.warehouse.security.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
//@Configuration
public class MyWebMvcConfig {
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new DateConverter());
}
}
... ...
package com.tianbo.warehouse.security.config;
import com.netflix.discovery.converters.Auto;
import com.tianbo.warehouse.security.CustomUserDetailService;
import com.tianbo.warehouse.security.handel.MyAuthenticationAccessDeniedHandler;
import com.tianbo.warehouse.security.handel.MyAuthenticationFailHandler;
import com.tianbo.warehouse.security.handel.MyAuthenticationSuccessHandler;
... ... @@ -41,7 +42,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Qualifier("customuserservice")
@Autowired
private UserDetailsService userDetailsService;
private CustomUserDetailService userDetailsService;
@Autowired
private MyAuthenticationAccessDeniedHandler myAuthenticationAccessDeniedHandler;
... ... @@ -53,6 +54,8 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//user Details Service验证
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
//不删除凭据,以便记住用户
auth.eraseCredentials(false);
}
/**
... ... @@ -69,7 +72,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
//跨域配置
.requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
//管理页面只允许管理员角色访问
.antMatchers("/admin","/role").authenticated()
.antMatchers("/admin/**","/role/**","/user/**").authenticated()
//任何请求,登录后可以访问
//其余的不需要验证
.anyRequest().permitAll()
... ... @@ -107,5 +110,11 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
.csrf().disable();
http.addFilterBefore(myFilterSecurityInterceptor, FilterSecurityInterceptor.class);
//session管理
//session失效后跳转
// http.sessionManagement().invalidSessionUrl("/login");
// //只允许一个用户登录,如果同一个账户两次登录,那么第一个账户将被踢下线,跳转到登录页面
// http.sessionManagement().maximumSessions(1).expiredUrl("/login");
}
}
... ...
package com.tianbo.warehouse.service;
import com.github.pagehelper.PageInfo;
import com.tianbo.warehouse.model.PERMISSION;
import java.util.List;
import java.util.Map;
public interface PermissionService {
PageInfo<PERMISSION> findAll(int pageNum, int pageSize);
int insertSelective(PERMISSION record);
Map<String,Object> getUserMenus();
}
... ...
package com.tianbo.warehouse.service;
import com.github.pagehelper.PageInfo;
import com.tianbo.warehouse.model.ROLE;
public interface RoleService {
PageInfo<ROLE> findAll(int pageNum, int pageSize);
int insertSelective(ROLE record);
}
... ...
... ... @@ -7,5 +7,12 @@ import java.util.List;
public interface UserService {
USERS loadByUsername(String username);
PageInfo<USERS> selectAllUser(int pageNum, int pageSize);
int updateByPrimaryKeySelective(USERS record);
int insertSelective(USERS record);
int deleteByPrimaryKey(Integer userId);
}
... ...
package com.tianbo.warehouse.service.imp;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tianbo.warehouse.dao.PERMISSIONMapper;
import com.tianbo.warehouse.model.PERMISSION;
import com.tianbo.warehouse.model.ROLE;
import com.tianbo.warehouse.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
@Service("PermissionService")
public class PermissionServiceImp implements PermissionService{
@Autowired
PERMISSIONMapper permissionMapper;
@Override
public PageInfo<PERMISSION> findAll(int pageNum, int pageSize){
Page<PERMISSION> page = PageHelper.startPage(pageNum,pageSize);
List<PERMISSION> list = permissionMapper.findAll();
PageInfo<PERMISSION> result = new PageInfo<>(list);
return result;
}
@Override
public int insertSelective(PERMISSION record){
return permissionMapper.insertSelective(record);
}
@Override
public Map<String,Object> getUserMenus(){
Map<String,Object> data = new HashMap<String,Object>();
try {
//查询所有菜单
List<PERMISSION> allMenu = permissionMapper.getAllMenus();
//根节点
List<PERMISSION> rootMenu = new ArrayList<PERMISSION>();
for (PERMISSION nav : allMenu) {
if(nav.getParentId()==0){//父节点是0的,为根节点。
rootMenu.add(nav);
}
}
/* 根据Menu类的order排序 */
// Collections.sort(rootMenu, order());
//为根菜单设置子菜单,getClild是递归调用的
for (PERMISSION nav : rootMenu) {
/* 获取根节点下的所有子节点 使用getChild方法*/
List<PERMISSION> childList = getChild(nav.getPermissionId(), allMenu);
nav.setChildren(childList);//给根节点设置子节点
}
/**
* 输出构建好的菜单数据。
*
*/
data.put("success", "true");
data.put("list", rootMenu);
return data;
} catch (Exception e) {
data.put("success", "false");
data.put("list", new ArrayList());
return data;
}
}
/**
* 获取子节点
* @param id 父节点id
* @param allMenu 所有菜单列表
* @return 每个根节点下,所有子菜单列表
*/
public List<PERMISSION> getChild(Integer id,List<PERMISSION> allMenu){
//子菜单
List<PERMISSION> childList = new ArrayList<PERMISSION>();
for (PERMISSION nav : allMenu) {
// 遍历所有节点,将所有菜单的父id与传过来的根节点的id比较
//相等说明:为该根节点的子节点。
if(nav.getParentId().equals(id)){
childList.add(nav);
}
}
//递归
for (PERMISSION nav : childList) {
nav.setChildren(getChild(nav.getPermissionId(), allMenu));
}
// Collections.sort(childList,order());//排序
//如果节点下没有子节点,返回一个空List(递归退出)
if(childList.size() == 0){
return new ArrayList<PERMISSION>();
}
return childList;
}
}
... ...
package com.tianbo.warehouse.service.imp;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tianbo.warehouse.dao.ROLEMapper;
import com.tianbo.warehouse.model.PERMISSION;
import com.tianbo.warehouse.model.ROLE;
import com.tianbo.warehouse.model.USERS;
import com.tianbo.warehouse.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service(value = "roleService")
public class RoleServiceImp implements RoleService{
@Autowired
ROLEMapper roleMapper;
@Override
public PageInfo<ROLE> findAll(int pageNum, int pageSize){
Page<ROLE> page = PageHelper.startPage(pageNum,pageSize);
List<ROLE> list = roleMapper.findAll();
PageInfo<ROLE> result = new PageInfo<ROLE>(list);
return result;
}
@Override
public int insertSelective(ROLE record){
return roleMapper.insertSelective(record);
}
}
... ...
... ... @@ -62,4 +62,32 @@ public class UserServiceImpl implements UserService{
PageInfo<USERS> result = new PageInfo<USERS>(list);
return result;
}
@Override
public int updateByPrimaryKeySelective(USERS record){
int i = 0;
if (record!=null){
i = usersMapper.updateByPrimaryKeySelective(record);
}
return i;
}
@Override
public int insertSelective(USERS record){
if (null!=record){
return usersMapper.insertSelective(record);
}else {
return 0;
}
}
@Override
public int deleteByPrimaryKey(Integer userId){
if (null!=userId && userId>0){
return usersMapper.deleteByPrimaryKey(userId);
}else {
return 0;
}
}
}
... ...
... ... @@ -8,10 +8,15 @@ server.servlet.context-path=${SERVER_CONTEXTPATH:}
spring.application.name=tianbo.base.dev.devkit
spring.jackson.serialization.fail-on-empty-beans=false
#springboot2.0之后会把Date类型字段自动给转成UTC字符串 如:1990-11-26T16:00:00.000+0000,如果想转成时间戳在application.properties配置文件增加以下配置
spring.jackson.serialization.write-dates-as-timestamps=true
#jackson相关配置
spring.jackson.date-format = yyyy-MM-dd HH:mm:ss
spring.jackson.serialization.write-dates-as-timestamps=false
#时区必须要设置
spring.jackson.time-zone=GMT+8
#ALWAYS的意思是即时属性为null,仍然也会输出这个key
spring.jackson.default-property-inclusion=always
#springcloud 基本配置
... ... @@ -37,8 +42,8 @@ spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#spring.datasource.username=CGOETL
#spring.datasource.password=1q2w3e4r
#spring datasource mysql
spring.datasource.url=jdbc:mysql://127.0.0.1:3307/statistics
#spring datasource mysql,注意编码配置,缺少数据库编码配置容易引起中文入库乱码
spring.datasource.url=jdbc:mysql://127.0.0.1:3307/statistics?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
... ...
... ... @@ -3,31 +3,38 @@
<mapper namespace="com.tianbo.warehouse.dao.PERMISSIONMapper" >
<resultMap id="BaseResultMap" type="com.tianbo.warehouse.model.PERMISSION" >
<id column="permission_id" property="permissionId" jdbcType="INTEGER" />
<result column="permission_name" property="permissionName" jdbcType="VARCHAR" />
<result column="permission_sign" property="permissionSign" jdbcType="VARCHAR" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="permission_order" property="permissionOrder" jdbcType="VARCHAR" />
<result column="description" property="description" jdbcType="VARCHAR" />
<result column="group_name" property="groupName" jdbcType="VARCHAR" />
<result column="ismenu" property="ismenu" jdbcType="BOOLEAN" />
<result column="hidden" property="hidden" jdbcType="BOOLEAN" />
<result column="parent_id" property="parentId" jdbcType="INTEGER" />
<result column="path" property="path" jdbcType="VARCHAR" />
<result column="url" property="url" jdbcType="VARCHAR" />
<result column="ext1" property="ext1" jdbcType="VARCHAR" />
<result column="ext2" property="ext2" jdbcType="VARCHAR" />
<result column="ext3" property="ext3" jdbcType="VARCHAR" />
<result column="method" property="method" jdbcType="VARCHAR" />
<result column="iconCls" property="iconCls" jdbcType="VARCHAR" />
<result column="component" property="component" jdbcType="VARCHAR" />
</resultMap>
<sql id="Base_Column_List" >
permission_id, permission_name, permission_sign, description, group_name, parent_id,
path, url, ext1, ext2, ext3
permission_id, name, permission_order, description, ismenu,hidden,parent_id,
path, url, method, iconCls, component
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from permission
where permission_id = #{permissionId,jdbcType=INTEGER}
where permission_id = #{permissionId,jdbcType=INTEGER} ORDER BY permission_order
</select>
<select id="findAll" resultMap="BaseResultMap" >
select
<include refid="Base_Column_List" />
from permission
from permission ORDER BY permission_order
</select>
<select id="getAllMenus" resultMap="BaseResultMap" >
select
<include refid="Base_Column_List" />
from permission where ismenu is TRUE ORDER BY permission_order
</select>
<select id="findRoleListByUrl" resultType="java.lang.String" parameterType="java.lang.String">
SELECT
... ... @@ -36,7 +43,7 @@ FROM
permission P
LEFT JOIN role_permission RP ON P.permission_id = RP.permission_id
LEFT JOIN ROLE R ON R.ROLE_ID= RP.ROLE_ID
where P.url = #{permissionUrl,jdbcType=VARCHAR}
where P.url = #{permissionUrl,jdbcType=VARCHAR} ORDER BY permission_order
</select>
<select id="findByUserId" parameterType="java.lang.Integer" resultMap="BaseResultMap">
SELECT
... ... @@ -65,21 +72,21 @@ where P.url = #{permissionUrl,jdbcType=VARCHAR}
UR.USER_ID = #{userId,jdbcType=INTEGER}
)
)
)
) ORDER BY permission_order
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from permission
where permission_id = #{permissionId,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.tianbo.warehouse.model.PERMISSION" >
insert into permission (permission_id, permission_name, permission_sign,
description, group_name, parent_id,
path, url, ext1, ext2,
ext3)
values (#{permissionId,jdbcType=INTEGER}, #{permissionName,jdbcType=VARCHAR}, #{permissionSign,jdbcType=VARCHAR},
#{description,jdbcType=VARCHAR}, #{groupName,jdbcType=VARCHAR}, #{parentId,jdbcType=INTEGER},
#{path,jdbcType=VARCHAR}, #{url,jdbcType=VARCHAR}, #{ext1,jdbcType=VARCHAR}, #{ext2,jdbcType=VARCHAR},
#{ext3,jdbcType=VARCHAR})
insert into permission (permission_id, name, permission_order,
description, ismenu,hidden, parent_id,
path, url, method, iconCls,
component)
values (#{permissionId,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{permissionOrder,jdbcType=VARCHAR},
#{description,jdbcType=VARCHAR}, #{ismenu,jdbcType=BOOLEAN},#{hidden,jdbcType=BOOLEAN},#{parentId,jdbcType=INTEGER},
#{path,jdbcType=VARCHAR}, #{url,jdbcType=VARCHAR}, #{method,jdbcType=VARCHAR}, #{iconCls,jdbcType=VARCHAR},
#{component,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="com.tianbo.warehouse.model.PERMISSION" >
insert into permission
... ... @@ -87,17 +94,20 @@ where P.url = #{permissionUrl,jdbcType=VARCHAR}
<if test="permissionId != null" >
permission_id,
</if>
<if test="permissionName != null" >
permission_name,
<if test="name != null" >
name,
</if>
<if test="permissionSign != null" >
permission_sign,
<if test="permissionOrder != null" >
permission_order,
</if>
<if test="description != null" >
description,
</if>
<if test="groupName != null" >
group_name,
<if test="ismenu != null" >
ismenu,
</if>
<if test="hidden != null" >
hidden,
</if>
<if test="parentId != null" >
parent_id,
... ... @@ -108,31 +118,34 @@ where P.url = #{permissionUrl,jdbcType=VARCHAR}
<if test="url != null" >
url,
</if>
<if test="ext1 != null" >
ext1,
<if test="method != null" >
method,
</if>
<if test="ext2 != null" >
ext2,
<if test="iconCls != null" >
iconCls,
</if>
<if test="ext3 != null" >
ext3,
<if test="component != null" >
component,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="permissionId != null" >
#{permissionId,jdbcType=INTEGER},
</if>
<if test="permissionName != null" >
#{permissionName,jdbcType=VARCHAR},
<if test="name != null" >
#{name,jdbcType=VARCHAR},
</if>
<if test="permissionSign != null" >
#{permissionSign,jdbcType=VARCHAR},
<if test="permissionOrder != null" >
#{permissionOrder,jdbcType=VARCHAR},
</if>
<if test="description != null" >
#{description,jdbcType=VARCHAR},
</if>
<if test="groupName != null" >
#{groupName,jdbcType=VARCHAR},
<if test="ismenu != null" >
#{ismenu,jdbcType=BOOLEAN},
</if>
<if test="hidden != null" >
#{hidden,jdbcType=BOOLEAN},
</if>
<if test="parentId != null" >
#{parentId,jdbcType=INTEGER},
... ... @@ -143,31 +156,34 @@ where P.url = #{permissionUrl,jdbcType=VARCHAR}
<if test="url != null" >
#{url,jdbcType=VARCHAR},
</if>
<if test="ext1 != null" >
#{ext1,jdbcType=VARCHAR},
<if test="method != null" >
#{method,jdbcType=VARCHAR},
</if>
<if test="ext2 != null" >
#{ext2,jdbcType=VARCHAR},
<if test="iconCls != null" >
#{iconCls,jdbcType=VARCHAR},
</if>
<if test="ext3 != null" >
#{ext3,jdbcType=VARCHAR},
<if test="component != null" >
#{component,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.tianbo.warehouse.model.PERMISSION" >
update permission
<set >
<if test="permissionName != null" >
permission_name = #{permissionName,jdbcType=VARCHAR},
<if test="name != null" >
name = #{name,jdbcType=VARCHAR},
</if>
<if test="permissionSign != null" >
permission_sign = #{permissionSign,jdbcType=VARCHAR},
<if test="permissionOrder != null" >
permission_order = #{permissionOrder,jdbcType=VARCHAR},
</if>
<if test="description != null" >
description = #{description,jdbcType=VARCHAR},
</if>
<if test="groupName != null" >
group_name = #{groupName,jdbcType=VARCHAR},
<if test="ismenu != null" >
ismenu = #{ismenu,jdbcType=BOOLEAN},
</if>
<if test="hidden != null" >
hidden = #{hidden,jdbcType=BOOLEAN},
</if>
<if test="parentId != null" >
parent_id = #{parentId,jdbcType=INTEGER},
... ... @@ -178,30 +194,31 @@ where P.url = #{permissionUrl,jdbcType=VARCHAR}
<if test="url != null" >
url = #{url,jdbcType=VARCHAR},
</if>
<if test="ext1 != null" >
ext1 = #{ext1,jdbcType=VARCHAR},
<if test="method != null" >
method = #{method,jdbcType=VARCHAR},
</if>
<if test="ext2 != null" >
ext2 = #{ext2,jdbcType=VARCHAR},
<if test="iconCls != null" >
iconCls = #{iconCls,jdbcType=VARCHAR},
</if>
<if test="ext3 != null" >
ext3 = #{ext3,jdbcType=VARCHAR},
<if test="component != null" >
component = #{component,jdbcType=VARCHAR},
</if>
</set>
where permission_id = #{permissionId,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.tianbo.warehouse.model.PERMISSION" >
update permission
set permission_name = #{permissionName,jdbcType=VARCHAR},
permission_sign = #{permissionSign,jdbcType=VARCHAR},
set name = #{name,jdbcType=VARCHAR},
permission_order = #{permissionOrder,jdbcType=VARCHAR},
description = #{description,jdbcType=VARCHAR},
group_name = #{groupName,jdbcType=VARCHAR},
ismenu = #{ismenu,jdbcType=BOOLEAN},
hidden = #{hidden,jdbcType=BOOLEAN},
parent_id = #{parentId,jdbcType=INTEGER},
path = #{path,jdbcType=VARCHAR},
url = #{url,jdbcType=VARCHAR},
ext1 = #{ext1,jdbcType=VARCHAR},
ext2 = #{ext2,jdbcType=VARCHAR},
ext3 = #{ext3,jdbcType=VARCHAR}
method = #{method,jdbcType=VARCHAR},
iconCls = #{iconCls,jdbcType=VARCHAR},
component = #{component,jdbcType=VARCHAR}
where permission_id = #{permissionId,jdbcType=INTEGER}
</update>
</mapper>
\ No newline at end of file
... ...
... ... @@ -13,13 +13,13 @@
<result column="creatTime" property="creattime" jdbcType="TIMESTAMP" />
<result column="updateTime" property="updatetime" jdbcType="TIMESTAMP" />
<result column="userFace" property="userface" jdbcType="VARCHAR" />
<result column="ext1" property="ext1" jdbcType="VARCHAR" />
<result column="ext2" property="ext2" jdbcType="VARCHAR" />
<result column="ext3" property="ext3" jdbcType="VARCHAR" />
<result column="realName" property="realname" jdbcType="VARCHAR" />
<result column="email" property="email" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
</resultMap>
<sql id="Base_Column_List" >
user_id, username, password, birthday, sex, address, state, mobilePhone, creatTime,
updateTime, userFace, ext1, ext2, ext3
updateTime, userFace, realName, email, age
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
... ... @@ -46,13 +46,13 @@
insert into users (user_id, username, password,
birthday, sex, address,
state, mobilePhone, creatTime,
updateTime, userFace, ext1,
ext2, ext3)
updateTime, userFace, realName,
email, age)
values (#{userId,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
#{birthday,jdbcType=TIMESTAMP}, #{sex,jdbcType=CHAR}, #{address,jdbcType=VARCHAR},
#{state,jdbcType=BIT}, #{mobilephone,jdbcType=VARCHAR}, #{creattime,jdbcType=TIMESTAMP},
#{updatetime,jdbcType=TIMESTAMP}, #{userface,jdbcType=VARCHAR}, #{ext1,jdbcType=VARCHAR},
#{ext2,jdbcType=VARCHAR}, #{ext3,jdbcType=VARCHAR})
#{updatetime,jdbcType=TIMESTAMP}, #{userface,jdbcType=VARCHAR}, #{realname,jdbcType=VARCHAR},
#{email,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})
</insert>
<insert id="insertSelective" parameterType="com.tianbo.warehouse.model.USERS" >
insert into users
... ... @@ -90,14 +90,14 @@
<if test="userface != null" >
userFace,
</if>
<if test="ext1 != null" >
ext1,
<if test="realname != null" >
realname,
</if>
<if test="ext2 != null" >
ext2,
<if test="email != null" >
email,
</if>
<if test="ext3 != null" >
ext3,
<if test="age != null" >
age,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
... ... @@ -134,23 +134,20 @@
<if test="userface != null" >
#{userface,jdbcType=VARCHAR},
</if>
<if test="ext1 != null" >
#{ext1,jdbcType=VARCHAR},
<if test="realname != null" >
#{realname,jdbcType=VARCHAR},
</if>
<if test="ext2 != null" >
#{ext2,jdbcType=VARCHAR},
<if test="email != null" >
#{email,jdbcType=VARCHAR},
</if>
<if test="ext3 != null" >
#{ext3,jdbcType=VARCHAR},
<if test="age != null" >
#{age,jdbcType=INTEGER},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.tianbo.warehouse.model.USERS" >
update users
<set >
<if test="username != null" >
username = #{username,jdbcType=VARCHAR},
</if>
<if test="password != null" >
password = #{password,jdbcType=VARCHAR},
</if>
... ... @@ -178,22 +175,21 @@
<if test="userface != null" >
userFace = #{userface,jdbcType=VARCHAR},
</if>
<if test="ext1 != null" >
ext1 = #{ext1,jdbcType=VARCHAR},
<if test="realname != null" >
realname = #{realname,jdbcType=VARCHAR},
</if>
<if test="ext2 != null" >
ext2 = #{ext2,jdbcType=VARCHAR},
<if test="email != null" >
email = #{email,jdbcType=VARCHAR},
</if>
<if test="ext3 != null" >
ext3 = #{ext3,jdbcType=VARCHAR},
<if test="age != null" >
age = #{age,jdbcType=INTEGER},
</if>
</set>
where user_id = #{userId,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.tianbo.warehouse.model.USERS" >
update users
set username = #{username,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR},
set password = #{password,jdbcType=VARCHAR},
birthday = #{birthday,jdbcType=TIMESTAMP},
sex = #{sex,jdbcType=CHAR},
address = #{address,jdbcType=VARCHAR},
... ... @@ -202,9 +198,9 @@
creatTime = #{creattime,jdbcType=TIMESTAMP},
updateTime = #{updatetime,jdbcType=TIMESTAMP},
userFace = #{userface,jdbcType=VARCHAR},
ext1 = #{ext1,jdbcType=VARCHAR},
ext2 = #{ext2,jdbcType=VARCHAR},
ext3 = #{ext3,jdbcType=VARCHAR}
realName = #{realname,jdbcType=VARCHAR},
email = #{email,jdbcType=VARCHAR},
age = #{age,jdbcType=INTEGER}
where user_id = #{userId,jdbcType=INTEGER}
</update>
</mapper>
\ No newline at end of file
... ...