信息正在提交中,请勿重复提交。
package com.hbsc.config;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by duyu on 2019/1/3.
* Token注解类
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Token {
/**
* 生成Token
* @return
*/
boolean save() default false;
/**
* 删除Token
* @return
*/
boolean remove() default false;
}
package com.hbsc.config;
import com.github.pagehelper.PageHelper;
import com.hbsc.interceptor.CostTimeInterceptor;
import com.hbsc.interceptor.LoginHandlerInterceptor;
import com.hbsc.interceptor.RightsHandlerInterceptor;
import com.hbsc.interceptor.TokenHandlerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
* Created by xudong on 2017-10-18.
*/
@Configuration
public class WebAppConfigurer implements WebMvcConfigurer {
@Bean
public RightsHandlerInterceptor rightsHandlerInterceptor() {
return new RightsHandlerInterceptor();
}
@Bean
public LoginHandlerInterceptor loginHandlerInterceptor(){ return new LoginHandlerInterceptor();}
@Bean
public CostTimeInterceptor costTimeInterceptor() {
return new CostTimeInterceptor();
}
/**
* token拦截器
* @return
*/
@Bean
public TokenHandlerInterceptor tokenHandlerInterceptor(){return new TokenHandlerInterceptor();}
public static List allPowerList;
@Override
public void addInterceptors(InterceptorRegistry registry) {
List allPowerList= addInterceptorRoad();
registry.addInterceptor(loginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/changeSessionLanauage","/","/analysis/**","/checkInterface/**","/error","/indexUser/UpdatePassword","/login/getVerify","/login/index","/login/login","/login/login1","/login/out","/common/**","/pdf/**","/css/**","/js/**","/lib/**","/fonts/**","/img/**","/login/403","/drsoOriOrder/testBatchInsert/**");
registry.addInterceptor(rightsHandlerInterceptor()).addPathPatterns(allPowerList);
registry.addInterceptor(costTimeInterceptor()).addPathPatterns("/**").excludePathPatterns("/css/**","/js/**","/lib/**","/fonts/**","/img/**");
registry.addInterceptor(tokenHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/changeSessionLanauage?**","/analysis/**","/checkInterface/**","/error","/login/getVerify","/login/index","/login/login","/login/login1","/login/out","/common/**","/pdf/**","/css/**","/js/**","/lib/**","/fonts/**","/img/**","/login/403","/drsoOriOrder/testBatchInsert/**","/resources/i18n/**");
}
@Bean
public PageHelper pageHelper(){
PageHelper pageHelper = new PageHelper();
Properties properties = new Properties();
properties.setProperty("offsetAsPageNum","true");
properties.setProperty("rowBoundsWithCount","true");
properties.setProperty("reasonable","true");
properties.setProperty("dialect","mysql");
pageHelper.setProperties(properties);
return pageHelper;
}
private List addInterceptorRoad(){
allPowerList.add("/orgManage/deleteOrg");
//抽音管理
allPowerList.add("/drawSoundRule/init");
allPowerList.add("/drawSoundRule/editDrawSoundRule");
allPowerList.add("/drsoLog/init");
// 原始录音、订单
allPowerList.add("/recordings/init");
allPowerList.add("/drsoOriOrder/init");
// 质检模板
allPowerList.add("/qcTemplate/init");
// 初检任务
allPowerList.add("/qcTask/init");
allPowerList.add("/qcTask/toDetailPg");
// 复检任务
allPowerList.add("/qcSecTask/init");
allPowerList.add("/qcSecTask/toDetailPg");
// 流程管理
allPowerList.add("/manageProcess/init");
allPowerList.add("/manageProcess/add");
allPowerList.add("/manageProcess/edit");
//待复议
allPowerList.add("/reconsideration/init");
// 我的复议
allPowerList.add("/reconsideration/goMyReconsideration");
/* // 我的评分
allPowerList.add("/qcScoreHistory/init");*/
return allPowerList;
}
}
package com.hbsc.interceptor;
import com.alibaba.fastjson.JSON;
import com.hbsc.config.Token;
import com.hbsc.domain.IndexUserVo;
import com.hbsc.domain.common.ReturnMsg;
import com.hbsc.util.RedisUtil;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import redis.clients.jedis.Jedis;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.UUID;
/**
* token拦截器
*/
public class TokenHandlerInterceptor implements HandlerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(TokenHandlerInterceptor.class);
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
logger.debug(">>>TokenHandlerInterceptor>>>>>>>QC-CHECK");
// 获取要访问的URL地址
IndexUserVo indexUserVo = (IndexUserVo) request.getSession().getAttribute("user");
String url = request.getRequestURL().toString();
String path=url.substring(url.lastIndexOf("/")+1);
if(handler instanceof HandlerMethod){
HandlerMethod handlerMethod=(HandlerMethod)handler;
Method method=handlerMethod.getMethod();
Token annotation=method.getAnnotation(Token.class);
if(annotation !=null){
boolean saveSession=annotation.save();
if(saveSession){
String token="T"+UUID.randomUUID().toString().replaceAll("-","").trim();
Jedis jedis = RedisUtil.getJedis();
jedis.set("token"+path+indexUserVo.getUserName(),token);
jedis.close();
String s="token"+path+indexUserVo.getUserName()+"-"+token;
//加密tokenKey和值
String en64=new String(Base64.encodeBase64(s.getBytes("UTF-8")),"UTF-8");
request.setAttribute("token",en64);
logger.info("请求地址:{}获取的Token:{}",url,token);
}
boolean removeSession=annotation.remove();
if(removeSession){
if(isRequestSubmit(request,path)){
boolean isAjaxRequest = false;
if(!StringUtils.isBlank(request.getHeader("x-requested-with")) && request.getHeader("x-requested-with").equals("XMLHttpRequest")){
isAjaxRequest = true;
}
if(isAjaxRequest){
ReturnMsg returnMsg = new ReturnMsg();
returnMsg.setFail("请勿重复提交");
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter out = null;
try {
out = response.getWriter();
out.append(JSON.toJSONString(returnMsg));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
}else{
response.sendRedirect("/login/chongfu");
}
return false;
}
}
}
return true;
}else {
return false;
}
}
/**
* 比较页面token与设置的token是否一致
* @param request
* @param path
* @return
*/
private boolean isRequestSubmit(HttpServletRequest request,String path)throws Exception{
String requestToken=request.getParameter("token");//获取页面传入的token
//解密token
String de64=new String(Base64.decodeBase64(requestToken.getBytes("UTF-8")),"UTF-8");
String [] tokenArray=de64.split("-");
Jedis jedis = RedisUtil.getJedis();
String saveToken= jedis.get(tokenArray[0]);
logger.info("请求地址:{}请求设置的Token:{}",path,saveToken);
if(saveToken == null){
jedis.close();
return true;
}
logger.info("请求地址:{}页面获取的Token:{}",path,requestToken);
logger.info("请求地址:{}页面解密后的Token:{}",path,de64);
if(!StringUtils.equals(saveToken,tokenArray[1])){
jedis.close();
return true;
}
jedis.del(tokenArray[0]);
jedis.close();
return false;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
<%--
Created by IntelliJ IDEA.
User: duyu
Date: 2019/1/7
Time: 10:47
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
重复提交
信息正在提交中,请勿重复提交。
关闭
*在需要生成token的controller上增加@Token(save=true),
*而在需要检查重复提交的controller上添加@Token(remove=true)就可以了
package com.hbsc.controller;
import com.alibaba.fastjson.JSON;
import com.hbsc.common.NoConvertReturnMsg;
import com.hbsc.config.LogInterface;
import com.hbsc.config.Token;
import com.hbsc.domain.*;
import com.hbsc.domain.common.PageInfo;
import com.hbsc.service.IndexRoleService;
import com.hbsc.service.IndexUserService;
import com.hbsc.service.OrganizationService;
import com.hbsc.util.DateUtil;
import com.hbsc.util.MD5Digest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Class Name : IndexUserController.
* Description : 用户表Controller.
* Created by Jhony Zhang on 2018-01-06.
*/
@Controller
@RequestMapping("/indexUser")
public class IndexUserController {
private static final Logger logger = LoggerFactory.getLogger(IndexUserController.class);
private final OrganizationService organizationService;
/**
* 注入用户表service
*/
private final IndexUserService indexUserService;
/**
* 注入角色service
*/
private final IndexRoleService indexRoleService;
@Autowired
public IndexUserController(IndexUserService indexUserService, IndexRoleService indexRoleService,OrganizationService organizationService) {
this.indexUserService = indexUserService;
this.indexRoleService = indexRoleService;
this.organizationService = organizationService;
}
/*
* 引入application-dve配值的重置密码
* */
@Value("${resetPassword}")
private String resetPassword;
/**
* 进入用户表首页
*
* @return 返回用户首页地址
*/
@RequestMapping("/init")
public String init(){
return "indexUser/indexUserList";
}
/**
* 异步请求list数据
*
* @param bo 传入参数
* @return 返回封装列表及分页查询实体类
*/
//至用户首页
@RequestMapping("/indexUserList")
@ResponseBody
public PageInfo indexUserList(IndexUserBo bo) {
return indexUserService.queryIndexUserListMenu(bo);
}
/**
* 跳转至新增用户页面
* @param bo 用户信息参数
* @param model 返回数据
* @return 返回新增界面地址
*/
@RequestMapping(value = "/editIndexUser", method = RequestMethod.GET)
@Token(save = true)
public String editIndexUser(IndexUserBo bo, Model model) {
//获取所有角色信息
model.addAttribute("allRole",indexRoleService.selectAllRole());
IndexUserVo indexUserVo = null;
if (StringUtils.isNotBlank(bo.getOper()) && "edit".equals(bo.getOper())) {
//获取需要修改的用户的角色信息
model.addAttribute("sRole",indexRoleService.selectRoleByUid(bo.getUserId()));
bo.setSidx("xu.USER_ID");
bo.setSord("ASC");
PageInfo pageInfo = indexUserService.queryIndexUserListMenu(bo);
List indexUserVosList = pageInfo.getList();
//查询需要修改的用户信息
indexUserVo = indexUserVosList.get(0);
if (indexUserVo == null) {
logger.info("数据不存在");
}
}
model.addAttribute("indexUserVo", indexUserVo);
model.addAttribute("indexUserBo", bo);
return "indexUser/indexUserEdit";
}
/**
* 添加或修改用户
* @param bo 用户信息
* @param request 请求request
* @return 返回用户首页地址
* @throws UnsupportedEncodingException 不支持的用户编码
* @throws NoSuchAlgorithmException 不支持的算法异常
*/
@RequestMapping(value = "/editIndexUser",method = RequestMethod.POST)
@LogInterface(value = "用户添加/修改")
@Token(remove = true)
public String editIndexUser(IndexUserBo bo, HttpServletRequest request) throws UnsupportedEncodingException, NoSuchAlgorithmException {
HttpSession session=request.getSession();
if (StringUtils.isBlank(bo.getEntryTime())) { //如果为空串则置空,否则插入时报错;
bo.setEntryTime(null);
}
if (StringUtils.isNotBlank(bo.getOper()) && "add".equals(bo.getOper())) {
//加密密码
String newpswd= MD5Digest.getnewstr(bo.getPassword());
bo.setPassword(newpswd);
//添加创建人 创建时间
IndexUserVo bo1=(IndexUserVo)session.getAttribute("user");
String name=bo1.getUserName();
Date date=new Date();
bo.setCreater(name);
bo.setCreaterDate(DateUtil.toStringInYearMonthDayHourMinSecondPattern(date));
bo.setState("1"); //设置员工为在职
bo.setIsValid("Y"); //设置员工为可用
bo.setIsDeleted("N"); //设置员工为未删除
indexUserService.addIndexUser(bo);
/*//根据用户名获取详细信息
IndexUserVo uvo=indexUserService.selectIndexUserByName(bo.getUserName());
//给用户添加角色
String[] roles=request.getParameterValues("roleId");
for(String roleid:roles){
indexUserService.insertRoleToUser(uvo.getUserId(),roleid);
}*/
} else if (StringUtils.isNotBlank(bo.getOper()) && "edit".equals(bo.getOper())) {
IndexUserVo indexUserVo = indexUserService.indexUserDetail(bo.getUserId());
if (StringUtils.equals(bo.getType(),"0")){
//判断密码是否改变 如果改变加密密码
if(!bo.getPassword().equals(indexUserVo.getPassword())){
String newpswd= MD5Digest.getnewstr(bo.getPassword());
bo.setPassword(newpswd);
}
}else{
IndexUserBo pBo = new IndexUserBo();
pBo.setSidx("xu.USER_ID");
pBo.setSord("ASC");
PageInfo pageInfo = indexUserService.queryIndexUserListMenu(pBo);
List indexUserVosList = pageInfo.getList();
IndexUserVo indexUserVo1 = indexUserVosList.get(0);
logger.info("用户真实姓名,[{}]",indexUserVo1.getRealName());
}
//添加修改人 修改时间
IndexUserVo bo1=(IndexUserVo)session.getAttribute("user");
String name=bo1.getUserName();
Date date=new Date();
bo.setReviser(name);
bo.setReviserDate(DateUtil.toStringInYearMonthDayHourMinSecondPattern(date));
indexUserService.updateAllIndexUser(bo);
}
return "redirect:init";
}
/**
* 跳转至用户详情页面
* @param userId 用户id
* @param model 返回数据
* @return 返回用户详情界面地址
*/
@RequestMapping(value = "/indexUserDetail",method = RequestMethod.GET)
public String indexUserDetail(String userId, Model model) {
IndexUserVo indexUserVo = indexUserService.indexUserDetail(userId);
if (indexUserVo == null) {
logger.info("数据不存在");
}
model.addAttribute("indexUserVo", indexUserVo);
//添加用户的角色信息
model.addAttribute("detailURole",indexRoleService.selectRoleByUid(userId));
return "indexUser/indexUserDetail";
}
/**
* 判断用户名是否重复
* @param indexUserVo 用户信息
* @return 返回用户详情界面地址
*/
@RequestMapping(value = "/checkUserName",method = RequestMethod.POST)
@ResponseBody
public String checkUserName(IndexUserVo indexUserVo) {
NoConvertReturnMsg returnMsg = new NoConvertReturnMsg();
IndexUserVo vo = indexUserService.selectIndexUserByName(indexUserVo.getUserName());
if (vo != null) {
returnMsg.setFail("用户名已存在");
}else {
returnMsg.setSuccess("用户名不存在");
}
return JSON.toJSONString(returnMsg);
}
/**
* 跳转至用户详情页面
* @param userId 用户id
* @param model 返回数据
*/
@RequestMapping(value = "/indexUserDetail2")
public void indexUserDetail2(String userId, Model model) {
model.addAttribute("role",indexRoleService.selectRoleByUid(userId));
model.addAttribute("roles",indexRoleService.selectAllRole());
}
/**
* 删除用户
* @param userId 用户id
* @return 返回用户界面首页
*/
@RequestMapping(value = "/delIndexUser",method = RequestMethod.GET)
@LogInterface(value = "删除用户")
public String delIndexUser(String userId) {
//删除用户的角色依赖关系
indexUserService.deleteRoleByUid(userId);
IndexUserBo bo = new IndexUserBo();
bo.setUserId(userId);
bo.setIsDeleted("Y");
indexUserService.deleteIndexUser(userId);
// indexUserService.updateIndexUser(bo);
return "indexUser/indexUserList";
}
/**
* 添加用户角色关系
* @param userId 用户id
* @param list 角色id数据list
* @param session session
* @return 返回true
*/
@RequestMapping(value="/addUserRole")
@ResponseBody
public Boolean addUserRole(String userId,String[] list,HttpSession session){
indexUserService.deleteRoleByUid(userId);
for (String aList : list) {
if (!StringUtils.equals("0", aList)) {
indexUserService.insertRoleToUser(userId, aList);
}
}
IndexUserBo bo=new IndexUserBo();
//添加修改人 修改时间
IndexUserVo bo1=(IndexUserVo)session.getAttribute("user");
String name=bo1.getUserName();
Date date=new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
bo.setReviser(name);
bo.setReviserDate(sdf.format(date));
bo.setUserId(userId);
indexUserService.updateIndexUser(bo);
return true;
}
/**
* 将当前用户所属角色展示出来
* @param id 角色id
* @return 返回当前用户所属角色的json数据
*/
@RequestMapping("/selectRole")
@ResponseBody
public String selectRole(String id){
List list=indexRoleService.selectRoleByUid(id);
List list2=indexRoleService.selectAllRole();
List
7.logincontroller.java
添加
/**
* 跳到重复提交页面
* @return 跳到重复提交页面
*/
@RequestMapping(value = "/chongfu")
public String chongfu(){
return "chongfu";
}