代码优化 事务调整,返回信息调整

This commit is contained in:
zhuxiaomeng 2020-04-07 19:18:03 +08:00
parent a24c16d78a
commit 764c798abb
24 changed files with 513 additions and 467 deletions

View File

@ -79,7 +79,7 @@ public class BlogAdminController {
int serverPort = request.getServerPort();
int i = requestURL.indexOf(String.valueOf(serverPort));
String url = requestURL.substring(0, i);
json.setData(url + String.valueOf(serverPort) + "/img/" + path);
json.setData(url + serverPort + "/img/" + path);
json.setFlag(true);
return json;
}

View File

@ -2,6 +2,7 @@ package com.len.base;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.len.util.LenResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
@ -12,6 +13,7 @@ import org.springframework.web.bind.annotation.InitBinder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
@ -29,12 +31,12 @@ public abstract class BaseController<T> {
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Date.class, new CustomDateEditor(
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
binder.registerCustomEditor(Date.class, new CustomDateEditor(
new SimpleDateFormat("yyyy-MM-dd"), true));
new SimpleDateFormat("yyyy-MM-dd"), true));
}
@ExceptionHandler({UnauthorizedException.class, AuthorizationException.class})
@ExceptionHandler( {UnauthorizedException.class, AuthorizationException.class})
public String authorizationException(HttpServletRequest request, HttpServletResponse response) {
if (isAjaxRequest(request)) {
Map<String, Object> map = Maps.newHashMap();
@ -53,10 +55,45 @@ public abstract class BaseController<T> {
}
}
@ExceptionHandler( {Exception.class})
public void runTimeException(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("application/json");
try {
LenResponse lenResponse = new LenResponse(false, "处理错误");
response.getWriter().write(JSON.toJSONString(lenResponse));
} catch (IOException e) {
e.printStackTrace();
}
}
private static boolean isAjaxRequest(HttpServletRequest request) {
String requestedWith = request.getHeader("x-requested-with");
return requestedWith != null && requestedWith.equalsIgnoreCase("XMLHttpRequest");
}
public LenResponse resp(boolean flag, String msg) {
return new LenResponse(flag, msg);
}
public LenResponse resp(boolean flag) {
return resp(flag, null);
}
public LenResponse succ(String msg) {
return resp(true, msg);
}
public LenResponse succ() {
return succ(null);
}
public LenResponse error(String msg) {
return resp(false, null);
}
public LenResponse error() {
return error(null);
}
}

View File

@ -19,5 +19,5 @@ public interface BaseService<T,E extends Serializable> extends IService<T> {
public ReType getList(T t, int page, int limit);
public String showAll(T t);
public List<T> showAll(T t);
}

View File

@ -17,7 +17,7 @@ import java.util.List;
* @author zhuxiaomeng
* @date 2017/12/13.
* @email 154040976@qq.com
* update by 2019/11/12 tkmapper替换成mybatisplus
* update by 2019/11/12 mybatisplus
*/
@Slf4j
public class AbstractServiceImpl<T, E extends Serializable> extends ServiceImpl<BaseMapper<T>, T> implements BaseService<T, E> {
@ -45,7 +45,7 @@ public class AbstractServiceImpl<T, E extends Serializable> extends ServiceImpl<
}
@Override
public String showAll(T t) {
public List<T> showAll(T t) {
List<T> tList = null;
try {
tList = getBaseMapper().selectListByPage(t);
@ -53,7 +53,7 @@ public class AbstractServiceImpl<T, E extends Serializable> extends ServiceImpl<
log.error("class:BaseServiceImpl ->method:show->message:" + e.getMessage());
e.printStackTrace();
}
return JSON.toJSONString(tList);
return tList;
}
@Override

View File

@ -5,7 +5,6 @@ import com.len.core.annotation.Log;
import com.len.core.annotation.Log.LOG_TYPE;
import com.len.core.quartz.JobTask;
import com.len.entity.SysJob;
import com.len.exception.MyException;
import com.len.service.JobService;
import com.len.util.LenResponse;
import com.len.util.ReType;
@ -30,7 +29,7 @@ import org.springframework.web.bind.annotation.ResponseBody;
*/
@Controller
@RequestMapping("/job")
@Api(value = "定时任务",tags="定时任务")
@Api(value = "定时任务", tags = "定时任务")
public class JobController extends BaseController<SysJob> {
@Autowired
@ -62,18 +61,9 @@ public class JobController extends BaseController<SysJob> {
@PostMapping(value = "addJob")
@ResponseBody
public LenResponse addJob(SysJob job) {
LenResponse j = new LenResponse();
String msg = "保存成功";
job.setStatus(false);
try {
jobService.save(job);
} catch (MyException e) {
msg = "保存失败";
j.setFlag(false);
e.printStackTrace();
}
j.setMsg(msg);
return j;
jobService.save(job);
return succ("保存成功");
}
@GetMapping(value = "updateJob")
@ -92,23 +82,17 @@ public class JobController extends BaseController<SysJob> {
@PostMapping(value = "updateJob")
@ResponseBody
public LenResponse updateJob(SysJob job) {
LenResponse lenResponse = new LenResponse();
lenResponse.setFlag(false);
if (job == null) {
lenResponse.setMsg("获取数据失败");
return lenResponse;
return error("获取数据失败");
}
if (jobTask.checkJob(job)) {
lenResponse.setMsg("已经启动任务无法更新,请停止后更新");
return lenResponse;
return error("已经启动任务无法更新,请停止后更新");
}
if (jobService.updateJob(job)) {
lenResponse.setFlag(true);
lenResponse.setData("更新成功");
return succ("更新成功");
} else {
lenResponse.setData("更新失败");
return error("更新失败");
}
return lenResponse;
}
@Log(desc = "删除任务", type = LOG_TYPE.DEL)
@ -126,20 +110,16 @@ public class JobController extends BaseController<SysJob> {
@ResponseBody
@RequiresPermissions("job:start")
public LenResponse startJob(String id) {
LenResponse j = new LenResponse();
String msg = null;
String msg;
if (StringUtils.isEmpty(id)) {
j.setMsg("获取数据失败");
j.setFlag(false);
return j;
return error("获取数据失败");
}
if (jobService.startJob(id)) {
msg = "启动成功";
} else {
msg = "启动失败";
}
j.setMsg(msg);
return j;
return succ(msg);
}
@Log(desc = "停止任务")
@ -147,20 +127,16 @@ public class JobController extends BaseController<SysJob> {
@ResponseBody
@RequiresPermissions("job:end")
public LenResponse endJob(String id) {
LenResponse j = new LenResponse();
String msg;
if (StringUtils.isEmpty(id)) {
j.setMsg("获取数据失败");
j.setFlag(false);
return j;
return error("获取数据失败");
}
if (jobService.stopJob(id)) {
msg = "停止成功";
} else {
msg = "停止失败";
}
j.setMsg(msg);
return j;
return succ(msg);
}
}

View File

@ -8,9 +8,6 @@ import com.len.exception.MyException;
import com.len.mapper.SysLogMapper;
import com.len.util.LenResponse;
import com.len.util.ReType;
import java.util.List;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
@ -21,6 +18,8 @@ import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
/**
* @author zhuxiaomeng
* @date 2017/12/29.
@ -31,7 +30,7 @@ import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping(value = "/log")
@Slf4j
@Api(value = "日志管理",tags="操作日志记录")
@Api(value = "日志管理", tags = "操作日志记录")
public class LogController extends BaseController {
@Autowired
private SysLogMapper logMapper;
@ -72,18 +71,10 @@ public class LogController extends BaseController {
@PostMapping(value = "del")
@ResponseBody
public LenResponse del(String[] ids) {
LenResponse j = new LenResponse();
String msg = "删除成功";
try {
for (String id : ids) {
logMapper.deleteById(Integer.valueOf(id));
}
} catch (MyException e) {
msg = "删除失败";
log.error(msg + e.getMessage());
for (String id : ids) {
logMapper.deleteById(Integer.valueOf(id));
}
j.setMsg(msg);
return j;
return succ("删除成功");
}

View File

@ -32,7 +32,7 @@ import javax.servlet.http.HttpSession;
*/
@Controller
@Slf4j
@Api(value = "登录业务",tags="登录校验处理")
@Api(value = "登录业务", tags = "登录校验处理")
public class LoginController {
@Autowired
@ -58,9 +58,7 @@ public class LoginController {
@GetMapping(value = "/login")
public String loginCheck() {
Subject sub = SecurityUtils.getSubject();
Boolean flag2 = sub.isRemembered();
boolean flag = sub.isAuthenticated() || flag2;
if (flag) {
if (sub.isAuthenticated() || sub.isRemembered()) {
return "/main/main";
}
return "/login2";
@ -83,7 +81,7 @@ public class LoginController {
return "/login2";
}*/
CustomUsernamePasswordToken token = new CustomUsernamePasswordToken(user.getUsername().trim(),
user.getPassword(), "UserLogin");
user.getPassword(), "UserLogin");
Subject subject = Principal.getSubject();
String msg = null;
try {

View File

@ -5,7 +5,6 @@ import com.len.base.BaseController;
import com.len.core.annotation.Log;
import com.len.core.annotation.Log.LOG_TYPE;
import com.len.entity.SysMenu;
import com.len.exception.MyException;
import com.len.service.MenuService;
import com.len.util.BeanUtil;
import com.len.util.LenResponse;
@ -29,7 +28,7 @@ import org.springframework.web.bind.annotation.ResponseBody;
*/
@RequestMapping("/menu")
@Controller
@Api(value = "菜单管理",tags="菜单业务处理")
@Api(value = "菜单管理", tags = "菜单业务处理")
public class MenuController extends BaseController {
@Autowired
@ -61,12 +60,9 @@ public class MenuController extends BaseController {
@ApiOperation(value = "/addMenu", httpMethod = "POST", notes = "添加菜单")
@PostMapping(value = "addMenu")
@ResponseBody
public LenResponse addMenu(SysMenu sysMenu, Model model) {
LenResponse lenResponse = new LenResponse();
lenResponse.setFlag(false);
public LenResponse addMenu(SysMenu sysMenu) {
if (sysMenu == null) {
lenResponse.setMsg("获取数据失败");
return lenResponse;
return error("获取数据失败");
}
if (StringUtils.isEmpty(sysMenu.getPId())) {
sysMenu.setPId(null);
@ -77,18 +73,11 @@ public class MenuController extends BaseController {
if (StringUtils.isEmpty(sysMenu.getPermission())) {
sysMenu.setPermission(null);
}
try {
if (sysMenu.getMenuType() == 2) {
sysMenu.setMenuType((byte) 0);
}
menuService.save(sysMenu);
lenResponse.setMsg("添加成功");
} catch (MyException e) {
e.printStackTrace();
lenResponse.setMsg("添加失败");
if (sysMenu.getMenuType() == 2) {
sysMenu.setMenuType((byte) 0);
}
return lenResponse;
menuService.save(sysMenu);
return succ("添加成功");
}
@GetMapping(value = "showUpdateMenu")
@ -112,7 +101,7 @@ public class MenuController extends BaseController {
SysMenu oldMenu = menuService.getById(sysMenu.getId());
BeanUtil.copyNotNullBean(sysMenu, oldMenu);
menuService.updateById(oldMenu);
return LenResponse.sucess("保存成功");
return succ("保存成功");
}
@Log(desc = "删除菜单", type = LOG_TYPE.DEL)

View File

@ -1,11 +1,11 @@
package com.len.controller;
import com.len.base.BaseController;
import com.len.base.CurrentUser;
import com.len.core.annotation.Log;
import com.len.core.shiro.Principal;
import com.len.entity.SysUser;
import com.len.service.SysUserService;
import com.len.util.BeanUtil;
import com.len.util.Checkbox;
import com.len.util.LenResponse;
import io.swagger.annotations.Api;
@ -27,14 +27,14 @@ import java.util.List;
*/
@Controller
@RequestMapping("/person")
@Api(value = "个人业务",tags="个人业务处理")
public class PersonController {
@Api(value = "个人业务", tags = "个人业务处理")
public class PersonController extends BaseController {
@Autowired
SysUserService userService;
@GetMapping("/index")
public String main(){
public String main() {
return "/main/index";
}
@ -57,18 +57,10 @@ public class PersonController {
@PostMapping(value = "updateUser")
@ResponseBody
public LenResponse updatePerson(SysUser user) {
LenResponse jsonUtil = new LenResponse();
jsonUtil.setFlag(false);
if (user == null) {
jsonUtil.setMsg("获取数据失败");
return jsonUtil;
return error("获取数据失败");
}
SysUser oldUser = userService.getById(user.getId());
BeanUtil.copyNotNullBean(user, oldUser);
userService.updateById(oldUser);
jsonUtil.setFlag(true);
jsonUtil.setMsg("修改成功");
userService.updateCurrent(user);
return jsonUtil;
userService.updatePerson(user);
return succ("修改成功");
}
}

View File

@ -22,6 +22,8 @@ import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
/**
* @author zhuxiaomeng
* @date 2017/12/19.
@ -30,7 +32,7 @@ import org.springframework.web.bind.annotation.ResponseBody;
*/
@Controller
@RequestMapping(value = "/role")
@Api(value = "用户角色管理",tags="角色业务处理")
@Api(value = "用户角色管理", tags = "角色业务处理")
public class RoleController extends BaseController {
@Autowired
@ -44,7 +46,7 @@ public class RoleController extends BaseController {
@GetMapping(value = "showRole")
@RequiresPermissions(value = "role:show")
public String showRole(Model model) {
public String showRole() {
return "/system/role/roleList";
}
@ -52,7 +54,7 @@ public class RoleController extends BaseController {
@GetMapping(value = "showRoleList")
@ResponseBody
@RequiresPermissions("role:show")
public ReType showRoleList(SysRole role, Model model, String page, String limit) {
public ReType showRoleList(SysRole role, String page, String limit) {
return roleService.show(role, Integer.valueOf(page), Integer.valueOf(limit));
}
@ -60,7 +62,7 @@ public class RoleController extends BaseController {
@GetMapping(value = "showaLLRoleList")
@ResponseBody
@RequiresPermissions("role:show")
public String showRoleList(SysRole role, Model model) {
public List<SysRole> showRoleList(SysRole role) {
return roleService.showAll(role);
}
@ -78,7 +80,7 @@ public class RoleController extends BaseController {
@ResponseBody
public LenResponse addRole(SysRole sysRole, String[] menus) {
if (StringUtils.isEmpty(sysRole.getRoleName())) {
LenResponse.error("角色名称不能为空");
return error("角色名称不能为空");
}
return roleService.addRole(sysRole, menus);
}
@ -101,7 +103,7 @@ public class RoleController extends BaseController {
@ResponseBody
public LenResponse updateUser(SysRole role, String[] menus) {
if (role == null) {
return LenResponse.error("获取数据失败");
return error("获取数据失败");
}
return roleService.updateUser(role, menus);
}
@ -113,7 +115,7 @@ public class RoleController extends BaseController {
@RequiresPermissions("role:del")
public LenResponse del(String id) {
if (StringUtils.isEmpty(id)) {
return LenResponse.error("获取数据失败");
return error("获取数据失败");
}
return roleService.del(id);
}

View File

@ -2,19 +2,20 @@ package com.len.controller;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.len.base.BaseController;
import com.len.core.annotation.Log;
import com.len.core.annotation.Log.LOG_TYPE;
import com.len.core.quartz.JobTask;
import com.len.entity.SysRoleUser;
import com.len.entity.SysUser;
import com.len.exception.MyException;
import com.len.service.RoleUserService;
import com.len.service.SysUserService;
import com.len.util.*;
import com.len.util.Checkbox;
import com.len.util.LenResponse;
import com.len.util.Md5Util;
import com.len.util.ReType;
import com.len.util.UploadUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
@ -22,11 +23,15 @@ import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
/**
@ -38,7 +43,7 @@ import java.util.List;
//@Api(value="user")
@Controller
@RequestMapping(value = "/user")
@Api(value = "用户管理",tags="用户管理业务")
@Api(value = "用户管理", tags = "用户管理业务")
public class UserController extends BaseController {
//private static final Logger
@ -60,14 +65,14 @@ public class UserController extends BaseController {
@GetMapping(value = "showUser")
@RequiresPermissions("user:show")
public String showUser(Model model) {
public String showUser() {
return "/system/user/userList";
}
@GetMapping(value = "showUserList")
@ResponseBody
@RequiresPermissions("user:show")
public ReType showUser(Model model, SysUser user, String page, String limit) {
public ReType showUser(SysUser user, String page, String limit) {
return userService.show(user, Integer.valueOf(page), Integer.valueOf(limit));
}
@ -75,7 +80,7 @@ public class UserController extends BaseController {
@GetMapping(value = "listByRoleId")
@ResponseBody
@RequiresPermissions("user:show")
public String showUser(Model model, String roleId, int page, int limit) {
public String showUser(String roleId, int page, int limit) {
JSONObject returnValue = new JSONObject();
Page<Object> startPage = PageHelper.startPage(page, limit);
List<SysUser> users = userService.getUserByRoleId(roleId);
@ -98,38 +103,24 @@ public class UserController extends BaseController {
@ResponseBody
public LenResponse addUser(SysUser user, String[] role) {
if (user == null) {
return LenResponse.error("获取数据失败");
return error("获取数据失败");
}
if (StringUtils.isBlank(user.getUsername())) {
return LenResponse.error("用户名不能为空");
return error("用户名不能为空");
}
if (StringUtils.isBlank(user.getPassword())) {
return LenResponse.error("密码不能为空");
return error("密码不能为空");
}
if (role == null) {
return LenResponse.error("请选择角色");
return error("请选择角色");
}
int result = userService.checkUser(user.getUsername());
if (result > 0) {
return LenResponse.error("用户名已存在");
return error("用户名已存在");
}
LenResponse j = new LenResponse();
try {
user.setPassword(Md5Util.getMD5(user.getPassword(),user.getUsername()));
userService.save(user);
SysRoleUser sysRoleUser = new SysRoleUser();
sysRoleUser.setUserId(user.getId());
for (String r : role) {
sysRoleUser.setRoleId(r);
roleUserService.save(sysRoleUser);
}
j.setMsg("保存成功");
} catch (MyException e) {
j.setMsg("保存失败");
j.setFlag(false);
e.printStackTrace();
}
return j;
userService.add(user, Arrays.asList(role));
return succ();
}
@GetMapping(value = "updateUser")
@ -145,42 +136,17 @@ public class UserController extends BaseController {
return "system/user/update-user";
}
@ApiOperation(value = "/updateUser", httpMethod = "POST", notes = "更新用户")
@Log(desc = "更新用户", type = LOG_TYPE.UPDATE)
@PostMapping(value = "updateUser")
@ResponseBody
public LenResponse updateUser(SysUser user, String role[]) {
LenResponse jsonUtil = new LenResponse();
jsonUtil.setFlag(false);
public LenResponse updateUser(SysUser user, String[] role) {
if (user == null) {
jsonUtil.setMsg("获取数据失败");
return jsonUtil;
return error("获取数据失败");
}
try {
SysUser oldUser = userService.getById(user.getId());
BeanUtil.copyNotNullBean(user, oldUser);
userService.updateById(oldUser);
SysRoleUser sysRoleUser = new SysRoleUser();
sysRoleUser.setUserId(oldUser.getId());
List<SysRoleUser> keyList = userService.selectByCondition(sysRoleUser);
for (SysRoleUser currentRoleUser : keyList) {
QueryWrapper<SysRoleUser> queryWrapper = new QueryWrapper<>(currentRoleUser);
roleUserService.remove(queryWrapper);
}
if (role != null) {
for (String r : role) {
sysRoleUser.setRoleId(r);
roleUserService.save(sysRoleUser);
}
}
jsonUtil.setFlag(true);
jsonUtil.setMsg("修改成功");
userService.updateCurrent(user);
} catch (MyException e) {
e.printStackTrace();
}
return jsonUtil;
userService.updateUser(user, Arrays.asList(role));
return succ("修改成功");
}
@Log(desc = "删除用户", type = LOG_TYPE.DEL)
@ -206,7 +172,6 @@ public class UserController extends BaseController {
* 修改密码
*
* @param id
* @param pass
* @param newPwd
* @return
*/
@ -214,35 +179,20 @@ public class UserController extends BaseController {
@PostMapping(value = "rePass")
@ResponseBody
@RequiresPermissions("user:repass")
public LenResponse rePass(String id, String pass, String newPwd) {
boolean flag = StringUtils.isEmpty(id) || StringUtils.isEmpty(pass) || StringUtils.isEmpty(newPwd);
LenResponse j = new LenResponse();
j.setFlag(false);
public LenResponse rePass(String id, String newPwd) {
boolean flag = StringUtils.isEmpty(id) || StringUtils.isEmpty(newPwd);
if (flag) {
j.setMsg("获取数据失败,修改失败");
return j;
return error("获取数据失败,修改失败");
}
SysUser user = userService.getById(id);
newPwd = Md5Util.getMD5(newPwd, user.getUsername());
pass = Md5Util.getMD5(pass, user.getUsername());
if (!pass.equals(user.getPassword())) {
j.setMsg("密码不正确");
return j;
}
if (newPwd.equals(user.getPassword())) {
j.setMsg("新密码不能与旧密码相同");
return j;
return resp(false, "新密码不能与旧密码相同");
}
user.setPassword(newPwd);
try {
userService.rePass(user);
j.setMsg("修改成功");
j.setFlag(true);
} catch (MyException e) {
e.printStackTrace();
}
return j;
userService.rePass(user);
return succ("修改成功");
}
@Autowired
@ -253,8 +203,7 @@ public class UserController extends BaseController {
*/
@PostMapping(value = "upload")
@ResponseBody
public LenResponse imgUpload(HttpServletRequest req, @RequestParam("file") MultipartFile file,
ModelMap model) {
public LenResponse imgUpload(HttpServletRequest req, @RequestParam("file") MultipartFile file) {
String fileName = uploadUtil.upload(file);
LenResponse j = new LenResponse();
j.setMsg(fileName);
@ -266,21 +215,15 @@ public class UserController extends BaseController {
*/
@GetMapping(value = "checkUser")
@ResponseBody
public LenResponse checkUser(String uname, HttpServletRequest req) {
LenResponse j = new LenResponse();
j.setFlag(Boolean.FALSE);
public LenResponse checkUser(String uname) {
if (StringUtils.isEmpty(uname)) {
j.setMsg("获取数据失败");
return j;
return error("获取数据失败");
}
int result = userService.checkUser(uname);
if (result > 0) {
j.setMsg("用户名已存在");
return j;
return error("用户名已存在");
}
j.setFlag(true);
return j;
return succ();
}

View File

@ -19,12 +19,21 @@ public interface SysUserService extends BaseService<SysUser, String> {
SysUser login(String username);
/**
* 新增
* 新增用户和用户角色信息
*
* @param user
* @param user 用户对象
* @param role 角色列表
* @return
*/
int add(SysUser user);
boolean add(SysUser user, List<String> role);
/**
* 更新用户和用户角色信息
* @param user
* @param role
* @return
*/
boolean updateUser(SysUser user, List<String> role);
/**
* 删除
@ -55,4 +64,6 @@ public interface SysUserService extends BaseService<SysUser, String> {
void setMenuAndRoles(String username);
void updateCurrent(SysUser user);
boolean updatePerson(SysUser user);
}

View File

@ -53,53 +53,38 @@ public class JobServiceImpl extends BaseServiceImpl<SysJob, String> implements J
j.setMsg("获取数据失败");
return j;
}
try {
SysJob job = getById(id);
boolean flag = jobTask.checkJob(job);
if ((flag && !job.getStatus()) || !flag && job.getStatus()) {
j.setMsg("您任务表状态和web任务状态不一致,无法删除");
return j;
}
if (flag) {
j.setMsg("该任务处于启动中,无法删除");
return j;
}
removeById(id);
j.setFlag(true);
j.setMsg("任务删除成功");
} catch (MyException e) {
j.setMsg("任务删除异常");
e.printStackTrace();
SysJob job = getById(id);
boolean flag = jobTask.checkJob(job);
if ((flag && !job.getStatus()) || !flag && job.getStatus()) {
j.setMsg("您任务表状态和web任务状态不一致,无法删除");
return j;
}
if (flag) {
j.setMsg("该任务处于启动中,无法删除");
return j;
}
removeById(id);
j.setFlag(true);
j.setMsg("任务删除成功");
return j;
}
@Override
public boolean startJob(String id) {
try {
SysJob job = getById(id);
jobTask.startJob(job);
job.setStatus(true);
updateById(job);
return true;
} catch (MyException e) {
log.error(e.getMessage());
e.printStackTrace();
}
return false;
SysJob job = getById(id);
jobTask.startJob(job);
job.setStatus(true);
updateById(job);
return true;
}
@Override
public boolean stopJob(String id) {
try {
SysJob job = getById(id);
jobTask.remove(job);
job.setStatus(false);
updateById(job);
return true;
} catch (MyException e) {
e.printStackTrace();
}
return false;
SysJob job = getById(id);
jobTask.remove(job);
job.setStatus(false);
updateById(job);
return true;
}
}

View File

@ -49,14 +49,13 @@ public class MenuServiceImpl extends BaseServiceImpl<SysMenu, String> implements
return menuDao.getMenuChildren(id);
}
public SysMenu child(SysMenu sysMenu, List<SysMenu> sysMenus, Integer pNum, Integer num) {
public SysMenu child(SysMenu sysMenu, List<SysMenu> sysMenus, Integer num) {
List<SysMenu> childSysMenu = sysMenus.stream().filter(s ->
s.getPId().equals(sysMenu.getId())).collect(Collectors.toList());
sysMenus.removeAll(childSysMenu);
SysMenu m;
for (SysMenu menu : childSysMenu) {
++num;
m = child(menu, sysMenus, pNum, num);
child(menu, sysMenus, num);
sysMenu.addChild(menu);
}
return sysMenu;
@ -72,7 +71,7 @@ public class MenuServiceImpl extends BaseServiceImpl<SysMenu, String> implements
supers.sort(Comparator.comparingInt(SysMenu::getOrderNum));
JSONArray jsonArr = new JSONArray();
for (SysMenu sysMenu : supers) {
SysMenu child = child(sysMenu, sysMenus, 0, 0);
SysMenu child = child(sysMenu, sysMenus, 0);
jsonArr.add(child);
}
return jsonArr;
@ -81,7 +80,7 @@ public class MenuServiceImpl extends BaseServiceImpl<SysMenu, String> implements
@Override
public JSONArray getMenuJsonByUser(List<SysMenu> menuList) {
JSONArray jsonArr = new JSONArray();
Collections.sort(menuList, (o1, o2) -> {
menuList.sort((o1, o2) -> {
if (o1.getOrderNum() == null || o2.getOrderNum() == null) {
return -1;
}
@ -160,7 +159,7 @@ public class MenuServiceImpl extends BaseServiceImpl<SysMenu, String> implements
@Override
public JSONArray getTreeUtil(String roleId) {
TreeUtil treeUtil = null;
TreeUtil treeUtil;
List<SysMenu> sysMenus = list();
List<SysMenu> supers = sysMenus.stream().filter(sysMenu ->
StringUtils.isEmpty(sysMenu.getPId()))
@ -181,7 +180,7 @@ public class MenuServiceImpl extends BaseServiceImpl<SysMenu, String> implements
return menuDao.getUserMenu(id);
}
public TreeUtil getChildByTree(SysMenu sysMenu, List<SysMenu> sysMenus, int layer, String pId, String roleId) {
private TreeUtil getChildByTree(SysMenu sysMenu, List<SysMenu> sysMenus, int layer, String pId, String roleId) {
layer++;
List<SysMenu> childSysMenu = sysMenus.stream().filter(s ->
s.getPId().equals(sysMenu.getId())).collect(Collectors.toList());
@ -191,7 +190,7 @@ public class MenuServiceImpl extends BaseServiceImpl<SysMenu, String> implements
treeUtil.setName(sysMenu.getName());
treeUtil.setLayer(layer);
treeUtil.setPId(pId);
/**判断是否存在*/
/*判断是否存在*/
if (!StringUtils.isEmpty(roleId)) {
SysRoleMenu sysRoleMenu = new SysRoleMenu();
sysRoleMenu.setMenuId(sysMenu.getId());

View File

@ -18,6 +18,7 @@ import java.util.List;
@Service
public class RoleMenuServiceImpl extends BaseServiceImpl<SysRoleMenu, String> implements
RoleMenuService {
@Autowired
private SysRoleMenuMapper roleMenuMapper;

View File

@ -5,14 +5,12 @@ import com.len.base.impl.BaseServiceImpl;
import com.len.entity.SysRole;
import com.len.entity.SysRoleMenu;
import com.len.entity.SysRoleUser;
import com.len.exception.MyException;
import com.len.mapper.SysRoleMapper;
import com.len.service.RoleMenuService;
import com.len.service.RoleService;
import com.len.service.RoleUserService;
import com.len.util.BeanUtil;
import com.len.util.LenResponse;
import com.len.util.UuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@ -36,33 +34,21 @@ public class RoleServiceImpl extends BaseServiceImpl<SysRole, String> implements
private RoleUserService roleUserService;
/*@Override
public int insert(SysRole record) {
record = super.addValue(record, true);
return roleMapper.insert(record);
}*/
@Override
public LenResponse addRole(SysRole sysRole, String[] menus) {
LenResponse j = new LenResponse();
try {
roleMapper.insert(sysRole);
//操作role-menu data
if (menus != null) {
for (String menu : menus) {
SysRoleMenu sysRoleMenu = new SysRoleMenu();
sysRoleMenu.setRoleId(sysRole.getId());
sysRoleMenu.setMenuId(menu);
roleMenuService.save(sysRoleMenu);
}
roleMapper.insert(sysRole);
//操作role-menu data
if (menus != null) {
for (String menu : menus) {
SysRoleMenu sysRoleMenu = new SysRoleMenu();
sysRoleMenu.setRoleId(sysRole.getId());
sysRoleMenu.setMenuId(menu);
roleMenuService.save(sysRoleMenu);
}
j.setMsg("保存成功");
} catch (MyException e) {
j.setMsg("保存失败");
j.setFlag(false);
e.printStackTrace();
}
j.setMsg("保存成功");
return j;
}
@ -70,29 +56,25 @@ public class RoleServiceImpl extends BaseServiceImpl<SysRole, String> implements
public LenResponse updateUser(SysRole role, String[] menus) {
LenResponse jsonUtil = new LenResponse();
jsonUtil.setFlag(false);
try {
SysRole oldRole = roleMapper.selectById(role.getId());
BeanUtil.copyNotNullBean(role, oldRole);
roleMapper.updateById(oldRole);
SysRole oldRole = roleMapper.selectById(role.getId());
BeanUtil.copyNotNullBean(role, oldRole);
roleMapper.updateById(oldRole);
SysRoleMenu sysRoleMenu = new SysRoleMenu();
sysRoleMenu.setRoleId(role.getId());
List<SysRoleMenu> menuList = roleMenuService.selectByCondition(sysRoleMenu);
for (SysRoleMenu sysRoleMenu1 : menuList) {
roleMenuService.deleteByPrimaryKey(sysRoleMenu1);
}
if (menus != null) {
for (String menu : menus) {
sysRoleMenu.setMenuId(menu);
roleMenuService.save(sysRoleMenu);
}
}
jsonUtil.setFlag(true);
jsonUtil.setMsg("修改成功");
} catch (MyException e) {
jsonUtil.setMsg("修改失败");
e.printStackTrace();
SysRoleMenu sysRoleMenu = new SysRoleMenu();
sysRoleMenu.setRoleId(role.getId());
List<SysRoleMenu> menuList = roleMenuService.selectByCondition(sysRoleMenu);
for (SysRoleMenu sysRoleMenu1 : menuList) {
roleMenuService.deleteByPrimaryKey(sysRoleMenu1);
}
if (menus != null) {
for (String menu : menus) {
sysRoleMenu.setMenuId(menu);
roleMenuService.save(sysRoleMenu);
}
}
jsonUtil.setFlag(true);
jsonUtil.setMsg("修改成功");
return jsonUtil;
}
@ -101,19 +83,13 @@ public class RoleServiceImpl extends BaseServiceImpl<SysRole, String> implements
SysRoleUser sysRoleUser = new SysRoleUser();
sysRoleUser.setRoleId(id);
LenResponse j = new LenResponse();
try {
QueryWrapper<SysRoleUser> wrapper = new QueryWrapper<>(sysRoleUser);
int count = roleUserService.count(wrapper);
if (count > 0) {
return LenResponse.error("已分配给用户,删除失败");
}
roleMapper.deleteById(id);
j.setMsg("删除成功");
} catch (MyException e) {
j.setMsg("删除失败");
j.setFlag(false);
e.printStackTrace();
QueryWrapper<SysRoleUser> wrapper = new QueryWrapper<>(sysRoleUser);
int count = roleUserService.count(wrapper);
if (count > 0) {
return LenResponse.error("已分配给用户,删除失败");
}
roleMapper.deleteById(id);
j.setMsg("删除成功");
return j;
}
}

View File

@ -2,7 +2,6 @@ package com.len.service.impl;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.len.base.BaseMapper;
import com.len.base.CurrentMenu;
import com.len.base.CurrentRole;
import com.len.base.CurrentUser;
@ -12,7 +11,6 @@ import com.len.entity.SysMenu;
import com.len.entity.SysRole;
import com.len.entity.SysRoleUser;
import com.len.entity.SysUser;
import com.len.exception.MyException;
import com.len.mapper.SysRoleUserMapper;
import com.len.mapper.SysUserMapper;
import com.len.service.MenuService;
@ -23,15 +21,15 @@ import com.len.util.BeanUtil;
import com.len.util.Checkbox;
import com.len.util.LenResponse;
import com.len.util.Md5Util;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
@ -59,9 +57,6 @@ public class SysUserServiceImpl extends BaseServiceImpl<SysUser, String> impleme
private static final String ADMIN = "admin";
//
// String pwd = Md5Util.getMD5(record.getPassword().trim(), record.getUsername().trim());
// record.setPassword(pwd);
@Override
public SysUser login(String username) {
return sysUserMapper.login(username);
@ -80,11 +75,41 @@ public class SysUserServiceImpl extends BaseServiceImpl<SysUser, String> impleme
}
@Override
public int add(SysUser user) {
public boolean add(SysUser user, List<String> role) {
//密码加密
String pwd = Md5Util.getMD5(user.getPassword().trim(), user.getUsername().trim());
user.setPassword(pwd);
return sysUserMapper.add(user);
user.setPassword(Md5Util.getMD5(user.getPassword(), user.getUsername()));
boolean save = save(user);
SysRoleUser sysRoleUser = new SysRoleUser();
sysRoleUser.setUserId(user.getId());
for (String r : role) {
sysRoleUser.setRoleId(r);
roleUserService.save(sysRoleUser);
}
return save;
}
@Override
public boolean updateUser(SysUser user, List<String> role) {
SysUser oldUser = getById(user.getId());
BeanUtil.copyNotNullBean(user, oldUser);
updateById(oldUser);
SysRoleUser sysRoleUser = new SysRoleUser();
sysRoleUser.setUserId(oldUser.getId());
List<SysRoleUser> keyList = selectByCondition(sysRoleUser);
for (SysRoleUser currentRoleUser : keyList) {
QueryWrapper<SysRoleUser> queryWrapper = new QueryWrapper<>(currentRoleUser);
roleUserService.remove(queryWrapper);
}
if (role != null) {
for (String r : role) {
sysRoleUser.setRoleId(r);
roleUserService.save(sysRoleUser);
}
}
updateCurrent(user);
return true;
}
@Override
@ -93,32 +118,27 @@ public class SysUserServiceImpl extends BaseServiceImpl<SysUser, String> impleme
return LenResponse.error("获取数据失败");
}
LenResponse j = new LenResponse();
try {
SysUser sysUser = sysUserMapper.selectById(id);
if (ADMIN.equals(sysUser.getUsername())) {
return LenResponse.error("超管无法删除");
}
SysRoleUser roleUser = new SysRoleUser();
roleUser.setUserId(id);
QueryWrapper<SysRoleUser> wrapper=new QueryWrapper<>(roleUser);
int count = roleUserService.count(wrapper);
if (count > 0) {
return LenResponse.error("账户已经绑定角色,无法删除");
}
if (flag) {
//逻辑
sysUser.setDelFlag(Byte.parseByte("1"));
sysUserMapper.updateById(sysUser);
} else {
//物理
sysUserMapper.delById(id);
}
j.setMsg("删除成功");
} catch (MyException e) {
j.setMsg("删除失败");
j.setFlag(false);
e.printStackTrace();
SysUser sysUser = sysUserMapper.selectById(id);
if (ADMIN.equals(sysUser.getUsername())) {
return LenResponse.error("超管无法删除");
}
SysRoleUser roleUser = new SysRoleUser();
roleUser.setUserId(id);
QueryWrapper<SysRoleUser> wrapper = new QueryWrapper<>(roleUser);
int count = roleUserService.count(wrapper);
if (count > 0) {
return LenResponse.error("账户已经绑定角色,无法删除");
}
if (flag) {
//逻辑
sysUser.setDelFlag(Byte.parseByte("1"));
sysUserMapper.updateById(sysUser);
} else {
//物理
sysUserMapper.delById(id);
}
int i = 1 / 0;
j.setMsg("删除成功");
return j;
}
@ -163,12 +183,11 @@ public class SysUserServiceImpl extends BaseServiceImpl<SysUser, String> impleme
}
@Override
public void setMenuAndRoles(String username) {
SysUser s = new SysUser();
s.setUsername(username);
QueryWrapper<SysUser> userQueryWrapper=new QueryWrapper<>(s);
QueryWrapper<SysUser> userQueryWrapper = new QueryWrapper<>(s);
s = sysUserMapper.selectOne(userQueryWrapper);
CurrentUser currentUser = new CurrentUser(s.getId(), s.getUsername(), s.getAge(), s.getEmail(), s.getPhoto(), s.getRealName());
Subject subject = Principal.getSubject();
@ -178,7 +197,7 @@ public class SysUserServiceImpl extends BaseServiceImpl<SysUser, String> impleme
List<SysMenu> menuList = menuService.getUserMenu(s.getId());
JSONArray json = menuService.getMenuJsonByUser(menuList);
session.setAttribute("menu", json);
session.setAttribute("menu", json.toJSONString());
List<CurrentMenu> currentMenuList = new ArrayList<>();
@ -208,13 +227,21 @@ public class SysUserServiceImpl extends BaseServiceImpl<SysUser, String> impleme
@Override
public void updateCurrent(SysUser sysUser) {
CurrentUser principal = Principal.getPrincipal();
if(principal.getId().equals(sysUser.getId())){
if (principal.getId().equals(sysUser.getId())) {
//当前用户
CurrentUser currentUse = Principal.getCurrentUse();
Session session=Principal.getSession();
Session session = Principal.getSession();
currentUse.setPhoto(sysUser.getPhoto());
session.setAttribute("currentPrincipal",currentUse);
session.setAttribute("currentPrincipal", currentUse);
}
}
@Override
public boolean updatePerson(SysUser user) {
SysUser oldUser = getById(user.getId());
BeanUtil.copyNotNullBean(user, oldUser);
updateById(oldUser);
updateCurrent(user);
return true;
}
}

View File

@ -22,16 +22,6 @@ To change this template use File | Settings | File Templates.-->
<legend style="font-size:16px;">修改账户:${user.username}</legend>
</fieldset>
</div>
<div class="layui-form-item">
<label for="pass" class="layui-form-label">
<span class="x-red">*</span>原密码
</label>
<div class="layui-input-inline">
<input type="hidden" value="${user.id}" name="id">
<input type="password" id="pass" name="pass" lay-verify="pass"
autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label for="newPass" class="layui-form-label">
<span class="x-red">*</span>新密码
@ -72,12 +62,7 @@ To change this template use File | Settings | File Templates.-->
,layer = layui.layer;
//自定义验证规则
form.verify({
pass: function(value){
if(value.trim()==""){
return "密码不能为空";
}
}
,newPass: [/(.+){6,12}$/, '密码必须6到12位']
newPass: [/(.+){6,12}$/, '密码必须6到12位']
,reNewPass: function(value){
if($('#newPass').val()!=$('#reNewPass').val()){
return '两次密码不一致';

View File

@ -0,0 +1,62 @@
package com.len.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class RConfig {
@Value("${spring.redis.port}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.timeout}")
private int timeout;
@Value("${spring.redis.maxRetryCount}")
private int maxRetryCount;
@Value("${spring.redis.second}")
private Long second;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public int getMaxRetryCount() {
return maxRetryCount;
}
public void setMaxRetryCount(int maxRetryCount) {
this.maxRetryCount = maxRetryCount;
}
public Long getSecond() {
return second;
}
public void setSecond(Long second) {
this.second = second;
}
}

View File

@ -7,7 +7,6 @@ import com.len.core.filter.VerfityCodeFilter;
import com.len.core.shiro.LoginRealm;
import com.len.core.shiro.RetryLimitCredentialsMatcher;
import org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
@ -15,15 +14,24 @@ import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSource
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.filter.DelegatingFilterProxy;
import javax.servlet.Filter;
import java.util.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* @author zhuxiaomeng
@ -35,25 +43,19 @@ import java.util.*;
@Configuration
public class ShiroConfig {
@Autowired
RConfig redisConfig;
@Bean
public RetryLimitCredentialsMatcher getRetryLimitCredentialsMatcher() {
// RetryLimitCredentialsMatcher rm = new RetryLimitCredentialsMatcher(getCacheManager(),2);
RetryLimitCredentialsMatcher rm = new RetryLimitCredentialsMatcher(getCacheManager());
RetryLimitCredentialsMatcher rm = new RetryLimitCredentialsMatcher(cacheManager());
rm.setHashAlgorithmName("md5");
rm.setHashIterations(4);
return rm;
}
/* @Bean
public BlogRetryLimitCredentialsMatcher getBlogRetryLimitCredentialsMatcher() {
BlogRetryLimitCredentialsMatcher rm = new BlogRetryLimitCredentialsMatcher(getCacheManager());
rm.setHashAlgorithmName("md5");
rm.setHashIterations(4);
return rm;
}*/
@Bean(name = "userLoginRealm")
public LoginRealm getLoginRealm() {
LoginRealm realm = new LoginRealm();
@ -66,12 +68,12 @@ public class ShiroConfig {
return new BlogRealm();
}
@Bean
/*@Bean
public EhCacheManager getCacheManager() {
EhCacheManager ehCacheManager = new EhCacheManager();
ehCacheManager.setCacheManagerConfigFile("classpath:ehcache/ehcache.xml");
return ehCacheManager;
}
}*/
@Bean
public LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
@ -101,8 +103,8 @@ public class ShiroConfig {
loginRealms.add(loginRealm);
loginRealms.add(blogLoginRealm);
dwm.setRealms(loginRealms);
dwm.setCacheManager(getCacheManager());
dwm.setSessionManager(defaultWebSessionManager());
dwm.setCacheManager(cacheManager());
dwm.setSessionManager(sessionManager());
return dwm;
}
@ -167,26 +169,55 @@ public class ShiroConfig {
return as;
}
/* @Bean
public DefaultWebSessionManager defaultWebSessionManager() {
DefaultWebSessionManager defaultWebSessionManager = new DefaultWebSessionManager();
defaultWebSessionManager.setSessionIdCookieEnabled(true);
defaultWebSessionManager.setGlobalSessionTimeout(21600000);
defaultWebSessionManager.setDeleteInvalidSessions(true);
defaultWebSessionManager.setSessionValidationSchedulerEnabled(true);
defaultWebSessionManager.setSessionIdUrlRewritingEnabled(false);
return defaultWebSessionManager;
}*/
@Bean
public DefaultWebSessionManager defaultWebSessionManager() {
DefaultWebSessionManager defaultWebSessionManager = new DefaultWebSessionManager();
defaultWebSessionManager.setSessionIdCookieEnabled(true);
defaultWebSessionManager.setGlobalSessionTimeout(21600000);
defaultWebSessionManager.setDeleteInvalidSessions(true);
defaultWebSessionManager.setSessionValidationSchedulerEnabled(true);
defaultWebSessionManager.setSessionIdUrlRewritingEnabled(false);
return defaultWebSessionManager;
}
@Bean
public FilterRegistrationBean delegatingFilterProxy(){
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
DelegatingFilterProxy proxy = new DelegatingFilterProxy();
proxy.setTargetFilterLifecycle(true);
proxy.setTargetBeanName("shiroFilter");
public FilterRegistrationBean delegatingFilterProxy() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
DelegatingFilterProxy proxy = new DelegatingFilterProxy();
proxy.setTargetFilterLifecycle(true);
proxy.setTargetBeanName("shiroFilter");
filterRegistrationBean.setFilter(proxy);
return filterRegistrationBean;
}
filterRegistrationBean.setFilter(proxy);
return filterRegistrationBean;
}
public RedisCacheManager cacheManager() {
RedisCacheManager redisCacheManager = new RedisCacheManager();
redisCacheManager.setRedisManager(redisManager());
return redisCacheManager;
}
private RedisManager redisManager() {
RedisManager redisManager = new RedisManager();
// redisManager.setHost(redisConfig.getHost());
// redisManager.setPort(redisConfig.getPort());
redisManager.setExpire(1800);
// redisManager.setTimeout(redisConfig.getTimeout());
return redisManager;
}
@Bean
public RedisSessionDAO redisSessionDAO() {
RedisSessionDAO redisSessionDAO = new RedisSessionDAO();
redisSessionDAO.setRedisManager(redisManager());
return redisSessionDAO;
}
@Bean
public DefaultWebSessionManager sessionManager() {
DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
sessionManager.setSessionDAO(redisSessionDAO());
return sessionManager;
}
}

View File

@ -0,0 +1,34 @@
package com.len.config;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.StringUtils;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
public class ShiroSessionManager extends DefaultWebSessionManager {
private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";
public ShiroSessionManager() {
super();
}
@Override
protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
HttpServletRequest httpRequest = WebUtils.toHttp(request);
String sessionId = httpRequest.getHeader("Authorization");
if (!StringUtils.isEmpty(sessionId)) {
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sessionId);
request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, true);
return sessionId;
} else {
return super.getSessionId(request, response);
}
}
}

View File

@ -1,53 +1,58 @@
package com.len.config;
import java.util.Properties;
import com.len.util.SpringUtil;
import org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.interceptor.TransactionInterceptor;
import java.util.Properties;
/**
* @author zhuxiaomeng
* @date 2018/1/30.
* @email 154040976@qq.com
* 事务不能忘
* 事务管理
*/
@Configuration
public class TransactionalConfig {
private static final String PROPAGATION_REQUIRED="PROPAGATION_REQUIRED,-Throwable";
private static final String PROPAGATION_REQUIRED_READ="PROPAGATION_REQUIRED,-Throwable,readOnly";
private static final String[] REQUIRED_RULE_TRANSACTION={"insert*","add*","update*","del*","create*"};
private static final String[] READ_RULE_TRANSACTION={"select*","get*","count*","find*"};
private static final String PROPAGATION_REQUIRED = "PROPAGATION_REQUIRED,-Throwable";
private static final String PROPAGATION_REQUIRED_READ = "PROPAGATION_REQUIRED,-Throwable,readOnly";
private static final String[] REQUIRED_RULE_TRANSACTION = {"insert*", "add*", "update*", "del*", "create*", "save*"};
private static final String[] READ_RULE_TRANSACTION = {"select*", "get*", "count*", "find*"};
/**
*aop
* @param platformTransactionManager 自动注入 无需手动
* @return
*/
@Bean(name="transactionInterceptor")
public TransactionInterceptor transactionInterceptor(PlatformTransactionManager platformTransactionManager) {
TransactionInterceptor interceptor = new TransactionInterceptor();
Properties properties = new Properties();
for(String s:REQUIRED_RULE_TRANSACTION){
properties.setProperty(s, PROPAGATION_REQUIRED);
/**
* aop 自动注入 无需手动
*
* @return
*/
@Bean("lenTransaction")
public TransactionInterceptor lenTransaction() {
PlatformTransactionManager platformTransactionManager = SpringUtil.getBean(PlatformTransactionManager.class);
TransactionInterceptor interceptor = new TransactionInterceptor();
Properties properties = new Properties();
for (String s : REQUIRED_RULE_TRANSACTION) {
//PROPAGATION_REQUIRED 级别事务
properties.setProperty(s, PROPAGATION_REQUIRED);
}
for (String s : READ_RULE_TRANSACTION) {
properties.setProperty(s, PROPAGATION_REQUIRED_READ);
}
interceptor.setTransactionManager(platformTransactionManager);
interceptor.setTransactionAttributes(properties);
return interceptor;
}
for(String s:READ_RULE_TRANSACTION){
properties.setProperty(s, PROPAGATION_REQUIRED_READ);
@Bean
public BeanNameAutoProxyCreator getBeanNameAutoProxyCreator() {
BeanNameAutoProxyCreator proxyCreator = new BeanNameAutoProxyCreator();
proxyCreator.setProxyTargetClass(true);
proxyCreator.setBeanNames("*ServiceImpl", "*Controller");
proxyCreator.setInterceptorNames("lenTransaction");
return proxyCreator;
}
interceptor.setTransactionManager(platformTransactionManager);
interceptor.setTransactionAttributes(properties);
return interceptor;
}
@Bean
public BeanNameAutoProxyCreator getBeanNameAutoProxyCreator(){
BeanNameAutoProxyCreator proxyCreator=new BeanNameAutoProxyCreator();
proxyCreator.setProxyTargetClass(true);
proxyCreator.setBeanNames("*ServiceImpl","*Controller");
proxyCreator.setInterceptorNames("transactionInterceptor");
return proxyCreator;
}
}

View File

@ -23,28 +23,18 @@ spring:
max-lifetime: 1800000
connection-timeout: 30000
connection-test-query: SELECT 1
# 如果你喜欢druid 可以放开pom注释 DruidConfig 注释 使用此数据源
# datasource:
# url: jdbc:mysql://localhost:3306/lenos?useUnicode=true&characterEncoding=UTF-8
# username: root
# password: 123456
# # 使用druid数据源
# type: com.alibaba.druid.pool.DruidDataSource
# driver-class-name: com.mysql.jdbc.Driver
# filters: stat
# maxActive: 20
# initialSize: 1
# maxWait: 60000
# minIdle: 1
# timeBetweenEvictionRunsMillis: 60000
# minEvictableIdleTimeMillis: 300000
# validationQuery: select 'x'
# testWhileIdle: true
# testOnBorrow: false
# testOnReturn: false
# poolPreparedStatements: true
# maxOpenPreparedStatements: 20
redis:
host: 127.0.0.1
port: 6379
timeout: 3000
maxRetryCount: 10
second: 300
session:
store-type: redis
data:
redis:
repositories:
enabled: false
http:
encoding:
force: true
@ -55,14 +45,14 @@ spring:
url: http://localhost:8082
management:
#management:
endpoints:
web:
exposure:
include: "*"
endpoint:
health:
show-details: ALWAYS
show-details: ALWAYS
eureka:
client:
fetch-registry: false
@ -77,15 +67,8 @@ mybatis:
mapper-locations: classpath*:mapper/*.xml
check-config-location: true
#mapper:
# mappers:
# - com.len.base.BaseMapper
# - tk.mybatis.mapper.common.Mapper
# not-empty: true
# identity: mysql
# PageHelperConfig 可以替代此方案
# PageHelperConfig
pagehelper:
helperDialect: mysql
reasonable: true

23
pom.xml
View File

@ -11,7 +11,7 @@
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.9.RELEASE</version>
<version>2.1.12.RELEASE</version>
<relativePath />
</parent>
<properties>
@ -99,13 +99,20 @@
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--Mysql数据库驱动-->
@ -358,6 +365,18 @@
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
<version>2.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.crazycake</groupId>
<artifactId>shiro-redis</artifactId>
<version>2.4.2.1-RELEASE</version>
</dependency>
</dependencies>