第二章 项目搭建
二.后端搭建
4.Swagger引用
应用Swagger的主要目的是为了便于别人了解后端设置了哪些业务,业务接口是什么。源码如下:
在项目结构下新建软件包config
,将java文件直接复制粘贴进去,或者新建类复制以下代码,均可
package com.wang.library.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("RestfulApi")
// .genericModelSubstitutes(DeferredResult.class)
.genericModelSubstitutes(ResponseEntity.class)
.useDefaultResponseMessages(true)
.forCodeGeneration(false)
.pathMapping("/")
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.wang.library.controller"))
.paths(PathSelectors.any())
.build()
.globalOperationParameters(headerToken());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("图书管理系统后台API")
.description("图书管理系统后台API信息")
.contact(new Contact("王文涛",
"",
""))
.version("1.0.0")
.build();
}
private List<Parameter> headerToken() {
ParameterBuilder tokenPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<>();
tokenPar.name("token").description("令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
pars.add(tokenPar.build());
return pars;
}
}
5.smtUser控制层业务实现
(1)登录接口
在controller
控制层,添加smtUser的业务,登录引用接口源码如下,然后在项目下,新建软件包form(前端业务)和utils(公共业务),将引用的对应java类复制粘贴进去。引用的类具体源码可以见附属java文件,其所需要引用的类如下
1)utils软件包下:
Result.java
;
ResultEnum.java
;
ResultUtil.java
;
StringOper.java
;
JwtConfig.java
2)form软件包下:
LoginForm.java
smtUser的Login接口源码:
/**
* 用户登录接口
*
* @param loginForm
* @return
*/
@ApiOperation(value = "用户登录接口", notes = "用户登录")
@PostMapping("login")
public Result login(@RequestBody LoginForm loginForm, HttpServletRequest request){
SmtUser smtUserParam = new SmtUser();
try {
smtUserParam.setUserid(loginForm.getUsername());
List<SmtUser> smtUserList = smtUserService.queryAll(smtUserParam);
if (smtUserList.size() < 1){
smtUserParam.setUserid(null);
smtUserParam.setMobile(loginForm.getUsername());
smtUserList = smtUserService.queryAll(smtUserParam);
if (smtUserList.size() < 1) {
JSONObject resData = new JSONObject();
resData.put("token", "");
resData.put("data", loginForm.getUsername());
return ResultUtil.error(ResultEnum.USER_NOT_EXIST.getCode(), ResultEnum.USER_NOT_EXIST.getMsg(), resData);
}
}
SmtUser smtUser = smtUserList.get(0);
if (smtUser.getIssysuser() != 1){
JSONObject resData = new JSONObject();
resData.put("token","");
resData.put("data",smtUser);
return ResultUtil.error(ResultEnum.USER_NOT_SYSTEM.getCode(),ResultEnum.USER_NOT_SYSTEM.getMsg(),resData);
}
if (!MD5Encrypt(loginForm.getPassword()).equals(smtUser.getPassword())){
JSONObject resData = new JSONObject();
resData.put("token","");
resData.put("data",smtUser);
return ResultUtil.error(ResultEnum.PASSWORD_IS_ERROR.getCode(),ResultEnum.PASSWORD_IS_ERROR.getMsg(),resData);
}
//记录操作日志-----------
// String syslogRes = this.hqtStatisticService.setSyslog(smtUser.getId(),null,request.getRemoteAddr(),
// "登录系统", request.getHeader("User-Agent"));
// if (!syslogRes.equals("")){
// return ResultUtil.error(ResultEnum.SYSTEM_ERROR.getCode(),syslogRes);
// }
//---------------------
Map claims = new HashMap<>();
claims.put("id", smtUser.getId()); claims.put("userid", smtUser.getUserid());
claims.put("username", smtUser.getUsername());
claims.put("userdept", smtUser.getDeptid());
String token = jwtConfig.createToken(claims);
JSONObject resData = new JSONObject();
resData.put("token",token);
resData.put("data",smtUser);
return ResultUtil.success(resData);
} catch (Exception e) {
JSONObject resData = new JSONObject();
resData.put("token","");
resData.put("data",loginForm.getUsername());
return ResultUtil.error(ResultEnum.SYSTEM_ERROR.getCode(),ResultEnum.SYSTEM_ERROR.getMsg()+e.getMessage(),resData);
}
}
(2)获取功能菜单接口
添加如下内容,并引入以下类
在utils软件包内引用TokenInterceptor.java
/**
* 用户菜单接口
*
* @param id
* @return
*/
@ApiOperation(value = "用户菜单接口", notes = "用户菜单")
@GetMapping("getUserMenu")
public Result getUserMenu(String id){
List menuList = new ArrayList();
try {
SmtMenu smtMenuParam = new SmtMenu();
smtMenuParam.setParentid("###");
List<SmtMenu> smtMenus = smtMenuService.queryAll(smtMenuParam);
smtMenus.sort(Comparator.comparing(SmtMenu::getOrderid));
for (SmtMenu smtMenu:smtMenus) { //遍历顶级菜单
SmtMenu smtChildMenuParam = new SmtMenu();
smtChildMenuParam.setParentid(smtMenu.getId());
List<SmtMenu> smtChildMenus = smtMenuService.queryAll(smtChildMenuParam);
smtChildMenus.sort(Comparator.comparing(SmtMenu::getOrderid));
if (smtChildMenus.size() > 0){
List childList = new ArrayList();
for (SmtMenu smtChildMenu:smtChildMenus) {
//获取菜单权限值------------
String sRightValue = getUserMenuRightValue(id,smtChildMenu.getId());
//---------------------------
if (sRightValue.substring(0,1).equals("1")) { //有使用权限
Map menuChildMap = new HashMap();
menuChildMap.put("href", smtChildMenu.getHref());
menuChildMap.put("title", smtChildMenu.getMenuuname());
menuChildMap.put("menuid", smtChildMenu.getId());
menuChildMap.put("icon", smtChildMenu.getIconname());
menuChildMap.put("target", "_self");
menuChildMap.put("rightvalue", sRightValue);
childList.add(menuChildMap);
}
}
if (childList.size() > 0) {
Map menuMap = new HashMap();
menuMap.put("href","");
menuMap.put("title",smtMenu.getMenuuname());
menuMap.put("icon",smtMenu.getIconname());
menuMap.put("target","_self");
menuMap.put("meta","{ title: '"+smtMenu.getMenuuname()+"', icon: 'el-icon-s-help', affix: true }");
menuMap.put("child", childList);
menuList.add(menuMap);
}
}
}
return ResultUtil.success(menuList);
} catch (Exception e) {
return ResultUtil.error(ResultEnum.SYSTEM_ERROR.getCode(),"获取用户菜单出错!"+e.getMessage());
}
}
private String getUserMenuRightValue(String userId, String menuId) {
if (userId.toUpperCase().equals("ADMIN")){
SmtMenu smtMenu = this.smtMenuService.queryById(menuId);
if (smtMenu.getParentid().equals("SMT"))
return "1111111111111111";
else
return "0000000000000000";
}
int rightLen = 0;
//获取用户权限值-----------------
SmtUserright smtUserrightParam = new SmtUserright();
smtUserrightParam.setMenuid(menuId); smtUserrightParam.setUserid(userId);
smtUserrightParam.setRightvalue("");
List<SmtUserright> smtUserrights = smtUserrightService.queryAll(smtUserrightParam);
int iRightValue = 0;
if (smtUserrights.size() > 0) {
SmtUserright smtUserright = smtUserrights.get(0);
iRightValue = Integer.parseInt(smtUserright.getRightvalue(), 2);
rightLen = smtUserright.getRightvalue().length();
}
//----------------------------
//遍历用户角色权限值与用户私有权限值进行或运算,获取用户最终权限值-------------
SmtUserrole smtUserroleParam = new SmtUserrole();
smtUserroleParam.setUserid(userId);
List<SmtUserrole> userRoles = smtUserroleService.queryAll(smtUserroleParam);
for (SmtUserrole userRole:userRoles) {
SmtRoleright smtRolerightParam = new SmtRoleright();
smtRolerightParam.setId(userRole.getRoleid());
smtRolerightParam.setMenuid(menuId); smtRolerightParam.setRightvalue("");
List<SmtRoleright> smtRolerights = smtRolerightService.queryAll(smtRolerightParam);
if (smtRolerights.size() == 0) continue;
SmtRoleright roleRight = smtRolerights.get(0);
int iRoleRight =Integer.parseInt(roleRight.getRightvalue(), 2);
if (rightLen < roleRight.getRightvalue().length()) rightLen = roleRight.getRightvalue().length();
iRightValue = iRightValue | iRoleRight;
}
//------------------------------------------------------------------
return addZeroForNum(Integer.toBinaryString(iRightValue),rightLen); //十进制转二进制并缺位补0
}
6.smtRole控制层业务实现
(1)增删查改业务接口
/**
* 通过分页获取数据
*
* @return 数据列表
*/
@GetMapping("queryAllByLimit")
public Result queryAllByLimit(PagedQueryForm<T> param) {
SmtRole smtRoleParam = new SmtRole();
try {
List<SmtRole> smtRoles = this.smtRoleService.queryAllByLimit(smtRoleParam,
(param.getPage() - 1) * param.getLimit(), param.getLimit(),
param.getSort(), param.getOrdertype(), null, null);
List<SmtRoleForm> smtRoleForms = new ArrayList<>();
for (SmtRole smtRole: smtRoles) {
SmtRoleForm smtRoleForm = new SmtRoleForm();
CommonUtil.copyObjProperties(smtRoleForm,smtRole);
smtRoleForm.setEdtbyusername((this.smtUserService.queryById(smtRole.getEdtbyuserid()) == null)? "未知" :
this.smtUserService.queryById(smtRole.getEdtbyuserid()).getUsername());
smtRoleForms.add(smtRoleForm);
}
JSONObject resData = new JSONObject();
resData.put("total",this.smtRoleService.getCount(smtRoleParam,null,null));
resData.put("newtoken",jwtConfig.getNewToken());
resData.put("data",smtRoleForms);
return ResultUtil.success(resData);
}catch (Exception e) {
JSONObject resData = new JSONObject();
resData.put("total",0);
resData.put("newtoken",jwtConfig.getNewToken());
resData.put("data",null);
return ResultUtil.error(ResultEnum.SYSTEM_ERROR.getCode(),"获取角色出错!"+e.getMessage(), resData);
}
}
/**
* 通过主键更新单条数据
** @param smtRoleForm
* @return 更新反馈
*/
@ApiOperation(value = "更新角色信息")
@PostMapping("update")
public Result update(@RequestBody SmtRoleForm smtRoleForm, HttpServletRequest request) {
SmtRole smtRole = this.smtRoleService.queryById(smtRoleForm.getId());
try {
CommonUtil.copyObjProperties(smtRole,smtRoleForm);
Map currentUser = jwtConfig.getCurrentUser();
smtRole.setEdtbyuserid(currentUser.get("id").toString());
Date date =new Date();
smtRole.setEdttime(date);
this.smtRoleService.update(smtRole);
// //记录操作日志-----------
// String syslogRes = this.hqtStatisticService.setSyslog(jwtConfig.getCurrentUser().get("id").toString(),"SmtRole",request.getRemoteAddr(),
// "修改【"+smtRoleForm.getRolename()+"】", request.getHeader("User-Agent"));
// if (!syslogRes.equals("")){
// return ResultUtil.error(ResultEnum.SYSTEM_ERROR.getCode(),syslogRes);
// }
// //---------------------
JSONObject resData = new JSONObject();
resData.put("edttime",date);
return ResultUtil.success(resData);
}catch (Exception e) {
JSONObject resData = new JSONObject();
resData.put("edttime",null);
return ResultUtil.error(ResultEnum.SYSTEM_ERROR.getCode(),ResultEnum.SYSTEM_ERROR.getMsg()+e.getMessage(),resData);
}
}
/**
* 通过主键新增单条数据
** @param smtRoleForm
* @return 更新反馈
*/
@ApiOperation(value = "新增角色信息")
@PostMapping("create")
public Result create(@RequestBody SmtRoleForm smtRoleForm, HttpServletRequest request) {
SmtRole smtRole = new SmtRole();
try {
CommonUtil.copyObjProperties(smtRole,smtRoleForm);
smtRole.setId(UUID.randomUUID().toString());
smtRole.setRoletype(2);
Map currentUser = jwtConfig.getCurrentUser();
smtRole.setEdtbyuserid(currentUser.get("id").toString());
Date date =new Date();
smtRole.setEdttime(date);
this.smtRoleService.insert(smtRole);
// //记录操作日志-----------
// String syslogRes = this.hqtStatisticService.setSyslog(jwtConfig.getCurrentUser().get("id").toString(),"SmtRole",request.getRemoteAddr(),
// "新增【"+smtRoleForm.getRolename()+"】", request.getHeader("User-Agent"));
// if (!syslogRes.equals("")){
// return ResultUtil.error(ResultEnum.SYSTEM_ERROR.getCode(),syslogRes);
// }
// //---------------------
JSONObject resData = new JSONObject();
resData.put("edttime",date);
return ResultUtil.success(resData);
}catch (Exception e) {
JSONObject resData = new JSONObject();
resData.put("edttime",null);
return ResultUtil.error(ResultEnum.SYSTEM_ERROR.getCode(),ResultEnum.SYSTEM_ERROR.getMsg()+e.getMessage(),resData);
}
}
/**
* 批量删除数据
** @param roleIds
* @return 更新反馈
*/
@ApiOperation(value = "删除角色信息")
@PostMapping("delete")
public Result delete(@RequestBody List<String> roleIds, HttpServletRequest request) {
try {
for (String roleId:roleIds) {
SmtRole smtRole = this.smtRoleService.queryById(roleId);
this.smtRoleService.deleteById(roleId);
// //记录操作日志-----------
// String syslogRes = this.hqtStatisticService.setSyslog(jwtConfig.getCurrentUser().get("id").toString(),"SmtRole",request.getRemoteAddr(),
// "删除【"+smtRole.getRolename()+"】", request.getHeader("User-Agent"));
// if (!syslogRes.equals("")){
// return ResultUtil.error(ResultEnum.SYSTEM_ERROR.getCode(),syslogRes);
// }
// //---------------------
}
return ResultUtil.success();
}catch (Exception e) {
return ResultUtil.error(ResultEnum.SYSTEM_ERROR.getCode(),ResultEnum.SYSTEM_ERROR.getMsg()+e.getMessage());
}
}
(2)获取和设置用户权限接口
/**
* 获取角色菜单权限
** @param roleId
* @return 数据列表
*/
@GetMapping("getRight")
public Result getRight(String roleId) {
SmtMenu smtMenuParam = new SmtMenu();
smtMenuParam.setParentid("###");
try {
List<SmtMenu> smtMenus = this.smtMenuService.queryAll(smtMenuParam);
smtMenus.sort(Comparator.comparing(SmtMenu::getOrderid));
List<SmtMenuRightForm> smtMenuRightForms = new ArrayList<>();
for (SmtMenu smtMenu: smtMenus) {
SmtMenuRightForm smtMenuRightForm = new SmtMenuRightForm();
smtMenuRightForm.setParentid(smtMenu.getParentid());
smtMenuRightForm.setId(smtMenu.getId()); smtMenuRightForm.setMenuname(smtMenu.getMenuuname());
smtMenuRightForm.setRightvalue(getMenuRightByRole(roleId,smtMenu.getId()));
smtMenuRightForm.setSmtMenuRightitems(getMenuRightItem(smtMenu.getId(),smtMenuRightForm.getRightvalue()));
smtMenuRightForms.add(smtMenuRightForm);
SmtMenu smtChildMenuParam = new SmtMenu();
smtChildMenuParam.setParentid(smtMenu.getId());
List<SmtMenu> smtChildMenus = this.smtMenuService.queryAll(smtChildMenuParam);
smtChildMenus.sort(Comparator.comparing(SmtMenu::getOrderid));
for (SmtMenu smtChildMenu: smtChildMenus) {
SmtMenuRightForm smtMenuChildRightForm = new SmtMenuRightForm();
smtMenuChildRightForm.setParentid(smtChildMenu.getParentid());
smtMenuChildRightForm.setId(smtChildMenu.getId()); smtMenuChildRightForm.setMenuname(smtChildMenu.getMenuuname());
smtMenuChildRightForm.setRightvalue(getMenuRightByRole(roleId,smtChildMenu.getId()));
smtMenuChildRightForm.setSmtMenuRightitems(getMenuRightItem(smtChildMenu.getId(),smtMenuChildRightForm.getRightvalue()));
smtMenuRightForms.add(smtMenuChildRightForm);
}
}
JSONObject resData = new JSONObject();
resData.put("is_allright",false);
resData.put("data",smtMenuRightForms);
return ResultUtil.success(resData);
}catch (Exception e) {
JSONObject resData = new JSONObject();
resData.put("is_allright",false);
resData.put("data",null);
return ResultUtil.error(ResultEnum.SYSTEM_ERROR.getCode(),"获取角色权限出错!"+e.getMessage(), resData);
}
}
private String getMenuRightByRole(String roleId, String menuId) {
SmtRoleright smtRolerightParam = new SmtRoleright();
smtRolerightParam.setRoleid(roleId);
smtRolerightParam.setMenuid(menuId); //smtRolerightParam.setRightvalue("");
List<SmtRoleright> smtRolerights = smtRolerightService.queryAll(smtRolerightParam);
if (smtRolerights.size() == 0) return "";
SmtRoleright smtRoleright = smtRolerights.get(0);
return smtRoleright.getRightvalue();
}
private List<SmtMenuRightitemForm> getMenuRightItem(String menuId, String rightValue) {
SmtMenuRightitem Rightitem = new SmtMenuRightitem();
Rightitem.setMenuid(menuId);
List<SmtMenuRightitem> smtMenuRightitems = smtMenuRightitemService.queryAll(Rightitem);
smtMenuRightitems.sort(Comparator.comparing(SmtMenuRightitem::getItemid));
List<SmtMenuRightitemForm> smtMenuRightitemForms = new ArrayList<>();
for (SmtMenuRightitem smtMenuRightitem:smtMenuRightitems) {
SmtMenuRightitemForm smtMenuRightitemForm = new SmtMenuRightitemForm();
smtMenuRightitemForm.setMenuid(smtMenuRightitem.getMenuid());
smtMenuRightitemForm.setItemid(smtMenuRightitem.getItemid());
smtMenuRightitemForm.setItemname(smtMenuRightitem.getItemname());
if (rightValue.equals("")) smtMenuRightitemForm.setIscheck(false);
else {
boolean isCheck = rightValue.substring(smtMenuRightitem.getItemid() - 1, smtMenuRightitem.getItemid()).equals("1");
smtMenuRightitemForm.setIscheck(isCheck);
}
smtMenuRightitemForms.add(smtMenuRightitemForm);
}
return smtMenuRightitemForms;
}
/**
* 设置角色菜单权限
* @param smtRolerights
* @return 数据列表
*/
@PostMapping("setRight")
public Result setRight(@RequestBody List<SmtRoleright> smtRolerights, HttpServletRequest request) {
try {
smtRolerightService.insertOrUpdateBatch(smtRolerights);
// //记录操作日志-----------
// SmtRole smtRole = this.smtRoleService.queryById(smtRolerights.get(0).getRoleid());
// String syslogRes = this.hqtStatisticService.setSyslog(jwtConfig.getCurrentUser().get("id").toString(),"SmtRole",request.getRemoteAddr(),
// "设置权限【"+smtRole.getRolename()+"】", request.getHeader("User-Agent"));
// if (!syslogRes.equals("")){
// return ResultUtil.error(ResultEnum.SYSTEM_ERROR.getCode(),syslogRes);
// }
// //---------------------
return ResultUtil.success();
}catch (Exception e) {
return ResultUtil.error(ResultEnum.SYSTEM_ERROR.getCode(),"保存角色权限出错!"+e.getMessage());
}
}