spring mvc里的验证码
来源:互联网 发布:java的clone方法 编辑:程序博客网 时间:2024/05/18 00:31
如图效果:
ImageServlet 类:
package com.szllt.pingshan.entity.info;
/*** @author liangxiaolei
* @version 创建时间:2016年6月28日 上午10:26:30
* 类说明:
*/
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ImageServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
//样式1
/* BufferedImage bi = new BufferedImage(68,22,BufferedImage.TYPE_INT_RGB);
Graphics g = bi.getGraphics();
Color c = new Color(200,150,255);
g.setColor(c);
g.fillRect(0, 0, 68, 22);
char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
Random r = new Random();
int len=ch.length,index;
StringBuffer sb = new StringBuffer();
for(int i=0; i<4; i++){
index = r.nextInt(len);
g.setColor(new Color(r.nextInt(88),r.nextInt(188),r.nextInt(255)));
g.drawString(ch[index]+"", (i*15)+3, 18);
sb.append(ch[index]);
}
request.getSession().setAttribute("piccode", sb.toString());
ImageIO.write(bi, "JPG", response.getOutputStream());*/
//样式2
//在内存中创建图象
int width = 60, height = 20;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//获取图形上下文
Graphics g = image.getGraphics();
//生成随机类
Random random = new Random();
//设定背景色
g.setColor(getRandColor(220, 250));
g.fillRect(0, 0, width, height);
//设定字体
g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
//画边框
//g.drawRect(0,0,width-1,height-1);
g.draw3DRect(0,0,width-1,height-1,true);
//随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 155; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x, y, x + xl, y + yl);
}
// 取随机产生的认证码(6位数字)
String sRand = "";
String s = "012345678901234567890123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ012345678901234567890123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (int i = 0; i < 4; i++) {
char rand =s.charAt(random.nextInt(s.length()));
sRand += rand;
// 将认证码显示到图象中
g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
//调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
g.drawString(String.valueOf(rand), 13 * i + 6, 16);
}
g.drawOval(0,12,60,11);
// 将认证码存入SESSION
request.getSession().setAttribute("rand", sRand);
// 图象生效
g.dispose();
ServletOutputStream output = null;
try {
output = response.getOutputStream();
// 输出图象到页面
ImageIO.write(image, "JPEG", output);
request.getSession().setAttribute("image",image);
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
}
web.xml里的配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>pingshanWeb</display-name>
<description>Shenzhen Pingshan Water Resource and Defence Project</description>
<listener>
<listener-class>com.szllt.common.filter.UserSessionListener</listener-class>
</listener>
<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Spring MVC 转发器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/spring-*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>ImageServlet</servlet-name>
<servlet-class>com.szllt.pingshan.entity.info.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImageServlet</servlet-name>
<url-pattern>/servlet/ImageServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
index.jsp:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%-- <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> --%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!doctype html>
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户登陆</title>
<link type="text/css" rel="stylesheet" href="/style/login.css">
<link href="./style/jquery-ui-1.10.4.custom.min.css" rel="stylesheet"/>
<link rel="Shortcut Icon" href="./images/favicon.ico" />
<style type="text/css">
body {
margin-left: 0px;
margin-top: 0px;
margin-right: 0px;
margin-bottom: 0px;
}
#logdiv #form1 table tr td {
color: #039;
font-size: 14px;
}
.copyright {
font-size: 12px;
color: #999;
}
.header { font-size: 36px;
}
</style>
<script type="text/javascript" src="./jQuery/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="./jQuery/jquery-ui-1.10.4.custom.min.js"></script>
<script type="text/javascript" src="./jQuery/layer/layer.min.js"></script>
<script type="text/javascript">
function setNextFocus(str){
var keyCode = event.keyCode ? event.keyCode
: event.which ? event.which : event.charCode;
if(keyCode==13){
if(str=="account" && document.getElementById("account").value!=""){
document.getElementById("password").focus();
}else if(str=="password" && document.getElementById("password").value!=""){
login();
}
}
}
window.onload = function() {
$("#account").focus();
};
function login() {
var username = $("#account");
var password = $("#password");
var authcode= $("#authcode");
if (username.val() == null || username.val() == "") {
layer.msg("请输入用户名!", 2, 1);
layer.shift('top',500);
username.focus();
return false;
}
if (password.val() == null || password.val() == "") {
layer.msg("请输入密码!", 2, 1);
layer.shift('top',500);
password.focus();
return false;
}
if (authcode.val() == null || authcode.val() == "") {
layer.msg("请输入验证码!", 2, 1);
layer.shift('top',500);
authcode.focus();
return false;
}
$("#loginForm").submit();
}
</script>
<script type="text/javascript">
//看不清时更换验证码:
function reloadCode(){
var time = new Date().getTime();
document.getElementById("imagecode").src="<%=request.getContextPath() %>/servlet/ImageServlet?d="+time;
}
</script>
</head>
<body style="margin:0; padding:0; background-color: #05496c; background-image:url(./images/background.jpg); background-repeat:repeat-x;">
<%--提示信息--%>
<input type="hidden" id="tips" value="${tips}"/>
<c:if test="${flag==true}">
<script type="text/javascript">
layer.msg($("#tips").val(), 2, 1);
layer.shift('top',500);
</script>
</c:if>
<c:if test="${flag==false}">
<script type="text/javascript">
layer.msg($("#tips").val(), 2, 5);
layer.shift('top',500);
</script>
</c:if>
<table style="margin:0 auto; border-collapse:collapse; width:100%;">
<tr>
<td style="background:url(./images/back_left.jpg); padding:0;"> </td>
<td style="width:1278px; padding:0;">
<table style="width:1278px; height:764px; margin:0 auto; border-collapse:collapse; background:url(./images/login_shadow.jpg);font-size: 40px; color: #FFF;">
<tr>
<td height="68" colspan="3" align="center"><span class="header"><img src="./images/logo.png" width="60" height="62" alt="psxq">深圳市坪山新区水务及三防信息化系统</span></td>
</tr>
<tr>
<td width="248" height="561"> </td>
<td width="765" height="561" align="center" valign="middle"><div id="logdiv">
<form id="loginForm" action="./login.do" method="post">
<table style="width:397px; height:160px; font-size: 14px; color: #264EBD; font-family: Arial, Helvetica, sans-serif;">
<tr height="80">
<td width="68"> </td>
<td width="89"> </td>
<td><span style="color:red;font-size:12px;"></span> </td>
</tr>
<tr>
<td> </td>
<td align="right">用户名:</td>
<td><label for="account"></label> <input
name="account" type="text" id="account" style="width:160px;hight:20px;vertical-align:middle;" onKeyPress="setNextFocus(this.id);"/></td>
</tr>
<tr>
<td> </td>
<td align="right">密 码:</td>
<td><label for="password"></label> <input name="password" type="password" id="password"
style="width:160px;hight:20px;vertical-align:middle;" onKeyPress="setNextFocus(this.id);"/></td>
</tr>
<tr>
<td> </td>
<td align="right">验证码:</td>
<td ><label for="authcode"></label>
<input name="authcode" type="text"id="authcode" style="width:90px;hight:20px;vertical-align:middle;" onKeyPress="setNextFocus(this.id);"/>
<img alt="验证码" style="width:65px;hight:18px;vertical-align:middle;" id="imagecode"src="<%=request.getContextPath() %>/servlet/ImageServlet"/>
<a href="javascript: reloadCode();" style="color:#264EBD;">看不清楚</a>
</tr>
</table>
<div
style="width: 240px; height: 50px; margin-left: 20px; margin-top: 40px;">
<div
style="margin: 3px; width: 80px; height: 40px; display: inline-block; cursor: pointer;"
onclick="login();"></div>
<div style="display: inline-block; width: 40px;"></div>
<div
style="margin: 3px; width: 80px; height: 40px; display: inline-block; cursor: pointer;"
onclick="loginForm.reset();"></div>
</div>
</form>
</div></td>
<td width="267" height="561"> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td colspan="3" align="center"><br /> <span class="copyright">CopyRight
© 2001 - 2013 深圳市路路通网络通信有限公司</span> </td>
</tr>
</table>
</td>
<td background="./images/background.jpg"> </td>
</tr>
</table>
</body>
</html>
login.jsp:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户登陆</title>
<link type="text/css" rel="stylesheet" href="/style/login.css">
<link href="./style/jquery-ui-1.10.4.custom.min.css" rel="stylesheet"/>
<link rel="Shortcut Icon" href="./images/favicon.ico" />
<style type="text/css">
body {
margin-left: 0px;
margin-top: 0px;
margin-right: 0px;
margin-bottom: 0px;
}
#logdiv #form1 table tr td {
color: #039;
font-size: 14px;
}
.copyright {
font-size: 12px;
color: #999;
}
.header {font-size: 36px;
}
</style>
<script type="text/javascript" src="./jQuery/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="./jQuery/jquery-ui-1.10.4.custom.min.js"></script>
<script type="text/javascript" src="./jQuery/layer/layer.min.js"></script>
<script type="text/javascript">
function setNextFocus(str){
var keyCode = event.keyCode ? event.keyCode
: event.which ? event.which : event.charCode;
if(keyCode==13){
if(str=="account" && document.getElementById("account").value!=""){
document.getElementById("password").focus();
}else if(str=="password" && document.getElementById("password").value!=""){
login();
}
}
}
window.onload = function() {
$("#account").focus();
};
function login() {
var username = $("#account");
var password = $("#password");
var authcode = $("#authcode");
if (username.val() == null || username.val() == "") {
layer.msg("请输入用户名!", 2, 1);
layer.shift('top',500);
username.focus();
return false;
}
if (password.val() == null || password.val() == "") {
layer.msg("请输入密码!", 2, 1);
layer.shift('top',500);
password.focus();
return false;
}
if (authcode.val() == null || authcode.val() == "") {
layer.msg("请输入验证码!", 2, 1);
layer.shift('top',500);
authcode.focus();
return false;
}
$("#loginForm").submit();
}
</script>
<script type="text/javascript">
function reloadCode(){
var time = new Date().getTime();
document.getElementById("imagecode").src="<%=request.getContextPath() %>/servlet/ImageServlet?d="+time;
}
</script>
</head>
<body style="margin:0; padding:0; background-color: #05496c; background-image:url(./images/background.jpg); background-repeat:repeat-x;">
<%--提示信息--%>
<input type="hidden" id="tips" value="${tips}"/>
<c:if test="${flag==true}">
<script type="text/javascript">
layer.msg(decodeURI($("#tips").val()), 2, 1);
layer.shift('top',500);
</script>
</c:if>
<c:if test="${flag==false}">
<script type="text/javascript">
layer.msg(decodeURI($("#tips").val()), 2, 5);
layer.shift('top',500);
</script>
</c:if>
<table style="margin:0 auto; border-collapse:collapse; width:100%;">
<tr>
<td style="background:url(./images/back_left.jpg); padding:0;"> </td>
<td style="width:1278px; padding:0;">
<table style="width:1278px; height:764px; margin:0 auto; border-collapse:collapse; background:url(./images/login_shadow.jpg);font-size: 40px; color: #FFF;">
<tr>
<td height="68" colspan="3" align="center"><span class="header"><img src="./images/logo.png" width="60" height="62" alt="psxq">深圳市坪山新区水务及三防信息化系统</span></td>
</tr>
<tr>
<td width="248" height="561"> </td>
<td width="765" height="561" align="center" valign="middle"><div id="logdiv">
<form id="loginForm" action="./login.do" method="post">
<table style="width:397px; height:160px; font-size: 14px; color: #264EBD; font-family: Arial, Helvetica, sans-serif;">
<tr height="80">
<td width="68"> </td>
<td width="89"> </td>
<td><span style="color:red;font-size:12px;"></span> </td>
</tr>
<tr>
<td> </td>
<td align="right">用户名:</td>
<td><label for="account"></label> <input
name="account" type="text" id="account" style="width:160px;hight:18px;vertical-align:middle;" onKeyPress="setNextFocus(this.id);"/></td>
</tr>
<tr>
<td> </td>
<td align="right">密 码:</td>
<td><label for="password"></label> <input name="password" type="password" id="password"
style="width:160px;hight:18px;vertical-align:middle;" onKeyPress="setNextFocus(this.id);"/></td>
</tr>
<tr>
<td> </td>
<td align="right">验证码:</td>
<td ><label for="authcode"></label>
<input name="authcode" type="text"id="authcode"style="width:90px;hight:20px;vertical-align:middle;" onKeyPress="setNextFocus(this.id);"/>
<img alt="验证码" style="width:65px;hight:18px;vertical-align:middle;" id="imagecode"src="<%=request.getContextPath() %>/servlet/ImageServlet"/>
<a href="javascript:reloadCode();" style="color:#264EBD;">看不清楚</a>
</tr>
</table>
<div
style="width: 240px; height: 50px; margin-left: 20px; margin-top: 40px;">
<div
style="margin: 3px; width: 80px; height: 40px; display: inline-block; cursor: pointer;"
onclick="login();"></div>
<div style="display: inline-block; width: 40px;"></div>
<div
style="margin: 3px; width: 80px; height: 40px; display: inline-block; cursor: pointer;"
onclick="loginForm.reset();"></div>
</div>
</form>
</div></td>
<td width="267" height="561"> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td colspan="3" align="center"><br /> <span class="copyright">CopyRight
© 2001 - 2013 深圳市路路通网络通信有限公司</span> </td>
</tr>
</table>
</td>
<td background="./images/background.jpg"> </td>
</tr>
</table>
</body>
</html>
UserController:
package com.szllt.pingshan.controller;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import com.szllt.common.entity.Menu;
import com.szllt.common.entity.Operate;
import com.szllt.common.entity.Role;
import com.szllt.common.entity.User;
import com.szllt.common.pager.PageInfo;
import com.szllt.common.pager.PageUtils;
import com.szllt.common.util.Constant;
import com.szllt.common.util.EncodeFilter;
import com.szllt.common.util.SecurityUtil;
import com.szllt.common.util.SessionUtils;
import com.szllt.pingshan.service.info.UserService;
/**
* 用户管理Controller
* @author zhangjh
*
*/
@Controller
public class UserController {
private static Logger logger = LoggerFactory.getLogger(UserController.class);
@Autowired
private UserService userService;
/**
* 查询数据库中是否已经有相同的账号
* @param account
* @param request
* @param response
*/
@RequestMapping("/findUser")
public void findUser(
@RequestParam(value = "userId", required = false, defaultValue = "0") String userId,
@RequestParam(value = "account", defaultValue = "") String account,
HttpServletRequest request, HttpServletResponse response) {
HashMap queryParams = new HashMap();
queryParams.put("account", account);
JSONObject json = new JSONObject();
User user = userService.findUser(queryParams);
//当前操作的用户ID
int id = 0;
if (userId != null && !"".equals(userId.trim()) && !"undefined".endsWith(userId)) {
try {
id = Integer.parseInt(userId);
} catch (NumberFormatException e) {
logger.info(e.getLocalizedMessage());
}
}
//排除当前操作的用户ID
if (user != null && user.getUserId() != id) {
json.put("data", "1");
} else {
json.put("data", "0");
}
try {
response.setCharacterEncoding("utf-8");
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
json.put("status", "1");
json.put("info", "查询成功!");
out.write(json.toString());
} catch (IOException e) {
logger.error(e.getLocalizedMessage());
}
return;
}
/**
* 用户登录
* @param account
* @param password
* @return
* @throws IOException
*/
@RequestMapping(value = "login", method = RequestMethod.POST)
public ModelAndView login(
@RequestParam(value = "account", required = false, defaultValue = "") String account,
@RequestParam(value = "password", required = false, defaultValue = "") String password,
@RequestParam(value = "authcode", required = false, defaultValue = "") String authcode,
HttpServletRequest request, HttpServletResponse response) throws IOException {
HashMap queryParams = new HashMap();
try {
account = EncodeFilter.encode(URLDecoder.decode(account, "utf-8"));
password = URLDecoder.decode(password, "utf-8");
authcode = EncodeFilter.encode(URLDecoder.decode(authcode, "utf-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
queryParams.put("account", account);
if (!account.equals("")) {
User user = userService.findUser(queryParams);
if (user != null) {
String currPass = SecurityUtil.EncryptECB(Constant.SECURITY_KEY, password);
if (currPass.equals(user.getPassword())) {
String authcodes=(String) request.getSession().getAttribute("rand");//获取生成的验证码
//toLowerCase大写转换为小写
if(authcode.toLowerCase().equals(authcodes.toLowerCase())){
//authcode为前台传过来的验证码
logger.info("user " + user.getAccount() + " login");
// 设置权限和菜单
setOperAndMenu(user);
request.getSession().setAttribute("user",user);
SessionUtils.saveLoginUser(account);// 做个标记
SessionUtils.saveSessionAttribute(Constant.USER, user);
// 查询所有的菜单信息
SessionUtils.saveSessionAttribute(Constant.MENUS, userService.queryMenu(null));
/*SessionUtils.saveSessionAttribute(ADDV,informationService.getAddv());
SessionUtils.saveSessionAttribute(VALLEY,informationService.getValley());
SessionUtils.saveSessionAttribute(PROJECT_TYPE,informationService.getProjectType());
SessionUtils.saveSessionAttribute(PROJECT_GRADE,informationService.getProjectGrade());
SessionUtils.saveSessionAttribute(MANAGE_COM,informationService.getManageCom());
SessionUtils.saveSessionAttribute(PROJECT_NAME,informationService.getProjectName());*/
return new ModelAndView("main",null);
}else{
queryParams.put("msg", URLEncoder.encode("验证码错误!","utf-8"));
queryParams.put("flag", false);
return new ModelAndView("login", queryParams);
}
} else {
queryParams.put("msg", "密码错误!");
queryParams.put("flag", false);
return new ModelAndView("login", queryParams);
}
} else {
logger.info("user " + account + " not exists");
queryParams.put("msg", "用户名" + account + "不存在!");
queryParams.put("flag", false);
return new ModelAndView("login", queryParams);
}
} else {
return new ModelAndView(new RedirectView("index.do"), queryParams);
}
}
/**
* 生成随机颜色
*/
private Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
/**
* 用户注销
* @throws UnsupportedEncodingException
*
*/
@RequestMapping(value="logout")
public ModelAndView logout() throws UnsupportedEncodingException{
SessionUtils.removeSessionAllAttribute();
Map<String, Object> model = new HashMap<String, Object>();
model.put("flag", true);
model.put("tips", URLEncoder.encode("您已成功退出系统。","utf-8"));
return new ModelAndView("login", model);
}
/**
* url过滤
* @return
*/
@RequestMapping(value = "index")
public ModelAndView index() {
return new ModelAndView("login");
}
/**
* 查询用户
* @param account
* @param user_name
* @param pageIndex
* @return
*/
@RequestMapping(value = "user")
public ModelAndView user(@RequestParam(value = "account",required = false,defaultValue = "") String account,
@RequestParam(value = "user_name",required = false,defaultValue = "") String user_name,
@RequestParam(value = "pageIndex",required = false,defaultValue = "0") Integer pageIndex) {
PageInfo pageInfo=new PageInfo();
pageInfo.setStartPageIndex(pageIndex);
HashMap queryParams=new HashMap();
queryParams.put("account",account);
queryParams.put("user_name",user_name);
queryParams.put("pageInfo",pageInfo);
//增加分页处理
int totalRow = userService.queryUserCount(queryParams);
int pageSize = pageInfo.getPageSize();
pageInfo.setTotalRow(totalRow);
pageInfo.setTotalPageSize((int)Math.ceil(totalRow*1.0/pageSize));
pageInfo.setResult(userService.queryUser(queryParams));
PageUtils.set(pageInfo,"user.do",queryParams);
queryParams.put("pageInfo",pageInfo);
//查询所有的角色信息
queryParams.put("user_roles",userService.queryRole(null));
return new ModelAndView("user",queryParams);
}
/**
* 添加用户
* @param add_user_name
* @param add_account
* @param add_password
* @param add_user_status
* @param add_user_role
* @return
*/
@RequestMapping(value="addUser")
public ModelAndView addUser(@RequestParam(value = "add_user_name") String add_user_name,
@RequestParam(value = "add_account") String add_account,
@RequestParam(value = "add_password") String add_password,
@RequestParam(value = "add_user_status") String add_user_status,
@RequestParam(value = "add_user_role") Integer[] add_user_role){
HashMap model=new HashMap();
try {
User user=new User();
user.setUserName(add_user_name);
user.setAccount(add_account);
user.setPassword(SecurityUtil.EncryptECB(Constant.SECURITY_KEY,add_password));
user.setUserStatus(add_user_status);
if(add_user_role!=null){
List<Role> roleList=new ArrayList<Role>();
for(Integer id:add_user_role){
Role role=new Role();
role.setRoleId(id);
roleList.add(role);
}
user.setUserRoles(roleList);
}
userService.addUser(user);
model.put("tips", URLEncoder.encode("添加成功","utf-8"));
model.put("flag",true);
}catch (Exception e){
logger.error("exception:",e);
model.put("tips", URLEncoder.encode("添加异常,请联系管理员","utf-8"));
model.put("flag",false);
}finally {
return new ModelAndView(new RedirectView("user.do"),model);
}
}
/**
* 删除用户
* @param delete_user_id
* @return
*/
@RequestMapping(value="deleteUser",method = RequestMethod.POST)
public ModelAndView deleteUser(@RequestParam(value = "delete_user_id") Integer delete_user_id){
HashMap model=new HashMap();
try {
User user=new User();
user.setUserId(delete_user_id);
userService.deleteUser(user);
model.put("tips", URLEncoder.encode("删除成功","utf-8"));
model.put("flag",true);
}catch (Exception e){
logger.error("exception:",e);
model.put("tips", URLEncoder.encode("删除异常,请联系管理员","utf-8"));
model.put("flag",false);
}finally {
return new ModelAndView(new RedirectView("user.do"),model);
}
}
/**
* 修改用户
* @param edit_user_id
* @param edit_user_name
* @param edit_account
* @param edit_password
* @param edit_user_status
* @param edit_user_role
* @return
*/
@RequestMapping(value="editUser")
public ModelAndView editUser(@RequestParam(value = "edit_user_id") Integer edit_user_id,
@RequestParam(value = "edit_user_name",required = false,defaultValue = "") String edit_user_name,
@RequestParam(value = "edit_account") String edit_account,
@RequestParam(value = "edit_password") String edit_password,
@RequestParam(value = "edit_user_status") String edit_user_status,
@RequestParam(value = "edit_user_role",required = false,defaultValue = "") Integer[] edit_user_role){
HashMap model=new HashMap();
try {
User user=new User();
user.setUserId(edit_user_id);
user.setUserName(edit_user_name);
user.setAccount(edit_account);
user.setPassword(SecurityUtil.EncryptECB(Constant.SECURITY_KEY, edit_password));
user.setUserStatus(edit_user_status);
if(edit_user_role!=null){
List<Role> roleList=new ArrayList<Role>();
for(Integer id:edit_user_role){
Role role=new Role();
role.setRoleId(id);
roleList.add(role);
}
user.setUserRoles(roleList);
}
userService.editUser(user);
model.put("tips", URLEncoder.encode("修改成功","utf-8"));
model.put("flag",true);
}catch (Exception e){
logger.error("exception:",e);
model.put("tips", URLEncoder.encode("修改异常,请联系管理员","utf-8"));
model.put("flag",false);
}finally {
return new ModelAndView(new RedirectView("user.do"),model);
}
}
/**
* 过滤各级菜单,避免不同角色的同样的菜单重复添加
* @param user
*/
private void setOperAndMenu(User user){
List<Menu> parentMenu_1 = new ArrayList<Menu>();//一级菜单
List<Menu> parentMenu_2 = new ArrayList<Menu>();//二级菜单
List<Menu> menus = new ArrayList<Menu>();//三级菜单
Map<String, List<Operate>> operates = new HashMap<String, List<Operate>>();//权限
Map<String, Menu> filterParentMenu_1 = new HashMap<String, Menu>();//过滤一级菜单
Map<String, Menu> filterParentMenu_2 = new HashMap<String, Menu>();//过滤二级菜单
Map<String, Menu> filterParentMenu_3 = new HashMap<String, Menu>();//过滤三级菜单
for (Role role : user.getUserRoles()) {
String menuId = null;
for (Menu tempMenu : role.getRoleMenus()) {
menuId = String.valueOf(tempMenu.getMenuId());
//一级菜单过滤
if (tempMenu.getMenuLevel()==1) {
//判断是否存在,不存在则加入到数组中
if (!filterParentMenu_1.containsKey(menuId)) {
parentMenu_1.add(tempMenu);
filterParentMenu_1.put(menuId, tempMenu);
}
}
//二级菜单过滤
if(tempMenu.getMenuLevel()==2){
if(!filterParentMenu_2.containsKey(menuId)){
parentMenu_2.add(tempMenu);
filterParentMenu_2.put(menuId,tempMenu);
}
}
//三级菜单过滤
if(tempMenu.getMenuLevel()==3){
//判断是否已添加此菜单,没有的话将菜单和权限都加入集合
if(!filterParentMenu_3.containsKey(menuId)){
menus.add(tempMenu);
operates.put(tempMenu.getMenuUrl(),tempMenu.getMenuOper());
filterParentMenu_3.put(menuId,tempMenu);
}else {
//如果已添加了此菜单,则取出此菜单的权限进行过滤
List<Operate> filterOper = operates.get(tempMenu.getMenuUrl());
if(null != tempMenu.getMenuOper()){
if(null == filterOper){
//如果该菜单的权限不为空,而权限过滤集合为空,则直接将权限加进去
operates.put(tempMenu.getMenuUrl(),tempMenu.getMenuOper());
}else{
//如果该菜单的权限不为空,权限过滤集合也不为空,则将权限进行比较,再添加进去
for(Operate operate:tempMenu.getMenuOper()){
boolean exist=false;
for(Operate filteroperate:filterOper){
if(filteroperate.getOperateType().equals(operate.getOperateType())){
exist=true;
}
}
if(!exist){
filterOper.add(operate);
}
}
operates.put(tempMenu.getMenuUrl(), filterOper);
}
}
}
}
}
}
//一级菜单排序
Collections.sort(parentMenu_1, new Comparator<Menu>() {
@Override
public int compare(Menu menu1, Menu menu2) {
//return menu1.getMenuTurn() == menu2.getMenuTurn() ? 0 : (menu1.getMenuTurn() > menu2.getMenuTurn() ? 1 : -1);
return menu1.getMenuTurn() - menu2.getMenuTurn();
}
});
//二级菜单排序
Collections.sort(parentMenu_2, new Comparator<Menu>() {
@Override
public int compare(Menu menu1, Menu menu2) {
//return menu1.getMenuTurn() == menu2.getMenuTurn() ? 0 : (menu1.getMenuTurn() > menu2.getMenuTurn() ? 1 : -1);
return menu1.getMenuParent().getMenuTurn()*10+menu1.getMenuTurn() - (menu2.getMenuParent().getMenuTurn()*10+menu2.getMenuTurn());
}
});
//三级菜单排序
Collections.sort(menus, new Comparator<Menu>() {
@Override
public int compare(Menu menu1, Menu menu2) {
//return menu1.getMenuTurn() == menu2.getMenuTurn() ? 0 : (menu1.getMenuTurn() > menu2.getMenuTurn() ? 1 : -1);
return menu1.getMenuParent().getMenuParent().getMenuTurn()*100 + menu1.getMenuParent().getMenuTurn()*10+menu1.getMenuTurn()
- (menu2.getMenuParent().getMenuParent().getMenuTurn()*100 + menu2.getMenuParent().getMenuTurn()*10+menu2.getMenuTurn());
}
});
SessionUtils.saveSessionAttribute(Constant.MENU_LEVEL1,parentMenu_1);
SessionUtils.saveSessionAttribute(Constant.MENU_LEVEL2,parentMenu_2);
SessionUtils.saveSessionAttribute(Constant.MENU_LEVEL3,menus);
SessionUtils.saveSessionAttribute(Constant.OPERATES,operates);
}
}
- spring mvc里的验证码
- Spring MVC 验证码
- spring mvc的服务器端图形验证码
- 基于spring MVC 的验证码生成
- freemarker+spring mvc 的验证
- Spring mvc登陆验证码
- Spring MVC 图片验证码
- Spring MVC生成验证码
- spring mvc 验证码功能
- spring mvc 图形验证码
- Spring Mvc添加验证码
- Spring mvc实现验证码
- Spring MVC 生成验证码
- Spring MVC验证码实现
- patchca整合Spring MVC生成超炫的验证码
- spring-mvc 运用 kaptcha实现验证码的生成
- patchca整合Spring MVC生成超炫的验证码
- 基于spring mvc的图片验证码实现
- Java并发编程:深入剖析ThreadLocal
- bit、Byte、bps、Bps、pps、Gbps的详细说明及换算
- 转载-------GLIBC内存分配机制引发的“内存泄露”
- Android冷启动白屏解析,带你一步步分析和解决问题
- 音频驱动程序
- spring mvc里的验证码
- redis-JedisPoolConfig配置
- 1号店交易系统架构如何向「高并发高可用」演进
- 51 NOD 1024 矩阵中不重复的元素(技巧)
- Sublime text 3 如何格式化CSS代码
- 自定义一个Framework包 dyld: Library not loaded
- Java Web集成第三方登录
- 本地代码推送到github的命令
- 使用consul实现服务的注册和发现