- 字符串解析
- 密码加密
- MD5加密
- 邮件发送
- json转换
- IP获取
- 数据校验
- 分页查询
- spring上下文
- 监听工具
- 请求holder
- 异常处理
- 参数异常类
- 自定义异常
- 登录过滤器
- 权限拦截
- 接收参数
字符串解析
package com.mmall.util;
import com.google.common.base.Splitter;
import java.util.List;
import java.util.stream.Collectors;
/**
* 字符串解析工具
* @author Administrator
*
*/
public class StringUtil {
public static List<Integer> splitToListInt(String str) {
List<String> strList = Splitter.on(",").trimResults().omitEmptyStrings().splitToList(str);
return strList.stream().map(strItem -> Integer.parseInt(strItem)).collect(Collectors.toList());
}
}
密码加密
package com.mmall.util;
import com.mmall.model.SysUser;
import java.util.Date;
import java.util.Random;
/**
* 密码处理工具类
* @author Administrator
*
*/
public class PasswordUtil {
public final static String[] word = {
"a", "b", "c", "d", "e", "f", "g",
"h", "j", "k", "m", "n",
"p", "q", "r", "s", "t",
"u", "v", "w", "x", "y", "z",
"A", "B", "C", "D", "E", "F", "G",
"H", "J", "K", "M", "N",
"P", "Q", "R", "S", "T",
"U", "V", "W", "X", "Y", "Z"
};
public final static String[] num = {
"2", "3", "4", "5", "6", "7", "8", "9"
};
/**
* 随机生成密码
* @return
*/
public static String randomPassword() {
StringBuffer stringBuffer = new StringBuffer();
//根据时间戳生成随机规则
Random random = new Random(new Date().getTime());
boolean flag = false;
int length = random.nextInt(3) + 8;//密码长度在8到10字符之间
for (int i = 0; i < length; i++) {
if (flag) {
stringBuffer.append(num[random.nextInt(num.length)]);
} else {
stringBuffer.append(word[random.nextInt(word.length)]);
}
flag = !flag;
}
return stringBuffer.toString();
}
public static void main(String[] args) throws Exception {
System.out.println(randomPassword());
Thread.sleep(100);
System.out.println(randomPassword());
Thread.sleep(100);
System.out.println(randomPassword());
}
}
MD5加密
package com.mmall.util;
import lombok.extern.slf4j.Slf4j;
import java.security.MessageDigest;
/**
* MD5密码加密工具
* @author Administrator
*
*/
@Slf4j
public class MD5Util {
public final static String encrypt(String s) {
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
try {
byte[] btInput = s.getBytes();
// 获得MD5摘要算法的 MessageDigest 对象
MessageDigest mdInst = MessageDigest.getInstance("MD5");
// 使用指定的字节更新摘要
mdInst.update(btInput);
// 获得密文
byte[] md = mdInst.digest();
// 把密文转换成十六进制的字符串形式
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
log.error("generate md5 error, {}", s, e);
return null;
}
}
}
邮件发送
package com.mmall.util;
import com.mmall.beans.Mail;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
/**
* 发送邮件工具类
* @author Administrator
*
*/
@Slf4j
public class MailUtil {
public static boolean send(Mail mail) {
// TODO
String from = "";
int port = 25;
String host = "";
String pass = "";
String nickname = "";
HtmlEmail email = new HtmlEmail();
try {
email.setHostName(host);
email.setCharset("UTF-8");
for (String str : mail.getReceivers()) {
email.addTo(str);
}
email.setFrom(from, nickname);
email.setSmtpPort(port);
email.setAuthentication(from, pass);
email.setSubject(mail.getSubject());
email.setMsg(mail.getMessage());
email.send();
log.info("{} 发送邮件到 {}", from, StringUtils.join(mail.getReceivers(), ","));
return true;
} catch (EmailException e) {
log.error(from + "发送邮件到" + StringUtils.join(mail.getReceivers(), ",") + "失败", e);
return false;
}
}
}
json转换
package com.mmall.util;
import lombok.extern.slf4j.Slf4j;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;
import org.codehaus.jackson.type.TypeReference;
/**
* json转换工具,类和json的转换
* @author Administrator
*
*/
@Slf4j
public class JsonMapper {
private static ObjectMapper objectMapper = new ObjectMapper();
static {
// config
objectMapper.disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
objectMapper.setFilters(new SimpleFilterProvider().setFailOnUnknownId(false));
objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);
}
/**
* 对象转字符串
* @param src
* @return
*/
public static <T> String obj2String(T src) {
if (src == null) {
return null;
}
try {
//如果是字符串,直接输出,否则转换为字符串
return src instanceof String ? (String) src : objectMapper.writeValueAsString(src);
} catch (Exception e) {
log.warn("parse object to String exception, error:{}", e);
return null;
}
}
/**
* 字符串转换为对象
* @param src
* @param typeReference
* @return
*/
public static <T> T string2Obj(String src, TypeReference<T> typeReference) {
if (src == null || typeReference == null) {
return null;
}
try {
return (T) (typeReference.getType().equals(String.class) ? src : objectMapper.readValue(src, typeReference));
} catch (Exception e) {
log.warn("parse String to Object exception, String:{}, TypeReference<T>:{}, error:{}", src, typeReference.getType(), e);
return null;
}
}
}
package com.mmall.common;
import lombok.Getter;
import lombok.Setter;
import java.util.HashMap;
import java.util.Map;
/**
* json数据返回
* @author Administrator
*
*/
@Getter
@Setter
public class JsonData {
private boolean ret;//结果
private String msg;//消息
private Object data;//数据
public JsonData(boolean ret) {
this.ret = ret;
}
public static JsonData success(Object object, String msg) {
JsonData jsonData = new JsonData(true);
jsonData.data = object;
jsonData.msg = msg;
return jsonData;
}
public static JsonData success(Object object) {
JsonData jsonData = new JsonData(true);
jsonData.data = object;
return jsonData;
}
public static JsonData success() {
return new JsonData(true);
}
public static JsonData fail(String msg) {
JsonData jsonData = new JsonData(false);
jsonData.msg = msg;
return jsonData;
}
public Map<String, Object> toMap() {
HashMap<String, Object> result = new HashMap<String, Object>();
result.put("ret", ret);
result.put("msg", msg);
result.put("data", data);
return result;
}
}
IP获取
package com.mmall.util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* IP获取工具类,不同服务器有差别
* @author Administrator
*
*/
@Slf4j
public class IpUtil {
public final static String ERROR_IP = "127.0.0.1";
public final static Pattern pattern = Pattern.
compile("(2[5][0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})");
/**
* 取外网IP
*
* @param request
* @return
*/
public static String getRemoteIp(HttpServletRequest request) {
String ip = request.getHeader("x-real-ip");
if (ip == null) {
ip = request.getRemoteAddr();
}
//过滤反向代理的ip
String[] stemps = ip.split(",");
if (stemps != null && stemps.length >= 1) {
//得到第一个IP,即客户端真实IP
ip = stemps[0];
}
ip = ip.trim();
if (ip.length() > 23) {
ip = ip.substring(0, 23);
}
return ip;
}
/**
* 获取用户的真实ip
*
* @param request
* @return
*/
public static String getUserIP(HttpServletRequest request) {
// 优先取X-Real-IP
String ip = request.getHeader("X-Real-IP");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("x-forwarded-for");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
if ("0:0:0:0:0:0:0:1".equals(ip)) {
ip = ERROR_IP;
}
}
if ("unknown".equalsIgnoreCase(ip)) {
ip = ERROR_IP;
return ip;
}
int pos = ip.indexOf(',');
if (pos >= 0) {
ip = ip.substring(0, pos);
}
return ip;
}
public static String getLastIpSegment(HttpServletRequest request) {
String ip = getUserIP(request);
if (ip != null) {
ip = ip.substring(ip.lastIndexOf('.') + 1);
} else {
ip = "0";
}
return ip;
}
public static boolean isValidIP(HttpServletRequest request) {
String ip = getUserIP(request);
return isValidIP(ip);
}
/**
* 判断我们获取的ip是否是一个符合规则ip
*
* @param ip
* @return
*/
public static boolean isValidIP(String ip) {
if (StringUtils.isEmpty(ip)) {
log.debug("ip is null. valid result is false");
return false;
}
Matcher matcher = pattern.matcher(ip);
boolean isValid = matcher.matches();
log.debug("valid ip:" + ip + " result is: " + isValid);
return isValid;
}
public static String getLastServerIpSegment() {
String ip = getServerIP();
if (ip != null) {
ip = ip.substring(ip.lastIndexOf('.') + 1);
} else {
ip = "0";
}
return ip;
}
public static String getServerIP() {
InetAddress inet;
try {
inet = InetAddress.getLocalHost();
String hostAddress = inet.getHostAddress();
return hostAddress;
} catch (UnknownHostException e) {
e.printStackTrace();
}
return "127.0.0.1";
}
}
数据校验
package com.mmall.util;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.mmall.exception.ParamException;
import org.apache.commons.collections.MapUtils;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
/**
* 数据校验(实体类,基于注解)
* @author Administrator
*
*/
public class BeanValidator {
//全局校验工厂
private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
//校验方法,单个类
public static <T> Map<String, String> validate(T t, Class... groups) {
Validator validator = validatorFactory.getValidator();
//获取校验结果
Set validateResult = validator.validate(t, groups);
if (validateResult.isEmpty()) {
return Collections.emptyMap();//没有错误信息返回空map
} else {
LinkedHashMap errors = Maps.newLinkedHashMap();
Iterator iterator = validateResult.iterator();
while (iterator.hasNext()) {
ConstraintViolation violation = (ConstraintViolation)iterator.next();
//封装有问题的字段和错误信息
errors.put(violation.getPropertyPath().toString(), violation.getMessage());
}
return errors;
}
}
//校验集合
public static Map<String, String> validateList(Collection<?> collection) {
//判断集合是否为空
Preconditions.checkNotNull(collection);
//迭代器
Iterator iterator = collection.iterator();
Map errors;
do {
if (!iterator.hasNext()) {
return Collections.emptyMap();//没有值,返回空集合
}
Object object = iterator.next();//否则获取当前数据
errors = validate(object, new Class[0]);//调用校验单个方法
} while (errors.isEmpty());
return errors;
}
//校验任何对象
public static Map<String, String> validateObject(Object first, Object... objects) {
if (objects != null && objects.length > 0) {
return validateList(Lists.asList(first, objects));
} else {
return validate(first, new Class[0]);
}
}
/**
* 只判断是否有异常
* @param param
* @throws ParamException,抛出自定义的参数异常com.mmall.exception.ParamException
*/
public static void check(Object param) throws ParamException {
Map<String, String> map = BeanValidator.validateObject(param);
if (MapUtils.isNotEmpty(map)) {
throw new ParamException(map.toString());
}
}
}
分页查询
package com.mmall.beans;
import lombok.Getter;
import lombok.Setter;
import javax.validation.constraints.Min;
/**
* 分页查询封装类
* @author Administrator
*
*/
public class PageQuery {
@Getter
@Setter
@Min(value = 1, message = "当前页码不合法")
private int pageNo = 1;
@Getter
@Setter
@Min(value = 1, message = "每页展示数量不合法")
private int pageSize = 10;
@Setter
private int offset;
public int getOffset() {
return (pageNo - 1) * pageSize;
}
}
package com.mmall.beans;
import com.google.common.collect.Lists;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
/**
* 分页结果
* @author Administrator
*
* @param <T>
*/
@Getter
@Setter
@ToString
@Builder
public class PageResult<T> {
private List<T> data = Lists.newArrayList();
private int total = 0;
}
spring上下文
package com.mmall.common;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* 获取spring上下文工具类
* @author Administrator
*
*/
@Component("applicationContextHelper")//被spring管理
public class ApplicationContextHelper implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext context) throws BeansException {
applicationContext = context;
}
/**
* 从applicationContext中取spring上下文的bean
* @param clazz
* @return
*/
public static <T> T popBean(Class<T> clazz) {
if (applicationContext == null) {
return null;
}
return applicationContext.getBean(clazz);
}
public static <T> T popBean(String name, Class<T> clazz) {
if (applicationContext == null) {
return null;
}
return applicationContext.getBean(name, clazz);
}
}
监听工具
package com.mmall.common;
import com.mmall.util.JsonMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
/**
* Http请求前后监听工具
* @author Administrator
*
*/
@Slf4j
public class HttpInterceptor extends HandlerInterceptorAdapter {
private static final String START_TIME = "requestStartTime";
/**
* 请求处理之前调用执行
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//获取当前请求路径
String url = request.getRequestURI().toString();
//获取请求参数
Map parameterMap = request.getParameterMap();
log.info("request start. url:{}, params:{}", url, JsonMapper.obj2String(parameterMap));
//记录请求相应时间,开始
long start = System.currentTimeMillis();
request.setAttribute(START_TIME, start);
return true;
}
/**
* 请求处理完之后执行,只执行正常请求
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// String url = request.getRequestURI().toString();
// long start = (Long) request.getAttribute(START_TIME);
// long end = System.currentTimeMillis();
// log.info("request finished. url:{}, cost:{}", url, end - start);
removeThreadLocalInfo();
}
/**
* 请求处理完之后执行,任何请求,包括出现异常后也执行
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
String url = request.getRequestURI().toString();
long start = (Long) request.getAttribute(START_TIME);
long end = System.currentTimeMillis();
log.info("request completed. url:{}, cost:{}毫秒", url, end - start);
removeThreadLocalInfo();
}
/**
* 移除当前线程的信息
*/
public void removeThreadLocalInfo() {
RequestHolder.remove();;
}
}
请求holder
package com.mmall.common;
import com.mmall.model.SysUser;
import javax.servlet.http.HttpServletRequest;
/**
* 请求holder,解决高并发,登录成功后把对象存入,可在任意地方取出使用
* @author Administrator
*
*/
public class RequestHolder {
private static final ThreadLocal<SysUser> userHolder = new ThreadLocal<SysUser>();
private static final ThreadLocal<HttpServletRequest> requestHolder = new ThreadLocal<HttpServletRequest>();
public static void add(SysUser sysUser) {
userHolder.set(sysUser);
}
public static void add(HttpServletRequest request) {
requestHolder.set(request);
}
public static SysUser getCurrentUser() {
return userHolder.get();
}
public static HttpServletRequest getCurrentRequest() {
return requestHolder.get();
}
public static void remove() {
userHolder.remove();
requestHolder.remove();
}
}
异常处理
package com.mmall.common;
import com.mmall.exception.ParamException;
import com.mmall.exception.PermissionException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 全局异常处理类
* @author Administrator
*
*/
@Slf4j
public class SpringExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
String url = request.getRequestURL().toString();
ModelAndView mv;
String defaultMsg = "System error";
// 这里我们要求项目中所有请求json数据,都使用.json结尾,接收前台数据先校验是否符合实体类要求
if (url.endsWith(".json")) {
if (ex instanceof PermissionException || ex instanceof ParamException) {
JsonData result = JsonData.fail(ex.getMessage());
mv = new ModelAndView("jsonView", result.toMap());
} else {
log.error("unknown json exception, url:" + url, ex);
JsonData result = JsonData.fail(defaultMsg);
mv = new ModelAndView("jsonView", result.toMap());
}
} else if (url.endsWith(".page")){ // 这里我们要求项目中所有请求page页面,都使用.page结尾
log.error("unknown page exception, url:" + url, ex);
JsonData result = JsonData.fail(defaultMsg);
mv = new ModelAndView("exception", result.toMap());
} else {
log.error("unknow exception, url:" + url, ex);
JsonData result = JsonData.fail(defaultMsg);
mv = new ModelAndView("jsonView", result.toMap());
}
return mv;
}
}
参数异常类
package com.mmall.exception;
/**
* 参数异常类
* @author Administrator
*
*/
public class ParamException extends RuntimeException {
public ParamException() {
super();
}
public ParamException(String message) {
super(message);
}
public ParamException(String message, Throwable cause) {
super(message, cause);
}
public ParamException(Throwable cause) {
super(cause);
}
protected ParamException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
自定义异常
package com.mmall.exception;
/**
* 自定义异常类
* @author Administrator
*
*/
public class PermissionException extends RuntimeException {
public PermissionException() {
super();
}
public PermissionException(String message) {
super(message);
}
public PermissionException(String message, Throwable cause) {
super(message, cause);
}
public PermissionException(Throwable cause) {
super(cause);
}
protected PermissionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
登录过滤器
package com.mmall.filter;
import com.mmall.common.RequestHolder;
import com.mmall.model.SysUser;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 登录过滤器
* @author Administrator
*
*/
@Slf4j
public class LoginFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) servletRequest;
HttpServletResponse resp = (HttpServletResponse) servletResponse;
SysUser sysUser = (SysUser)req.getSession().getAttribute("user");
if (sysUser == null) {
String path = "/signin.jsp";
resp.sendRedirect(path);
return;
}
//如果登陆成功把用户信息放到RequestHolder中,使用的时候再取出来
RequestHolder.add(sysUser);
RequestHolder.add(req);
filterChain.doFilter(servletRequest, servletResponse);
return;
}
public void destroy() {
}
}
权限拦截
package com.mmall.filter;
import com.google.common.base.Splitter;
import com.google.common.collect.Sets;
import com.mmall.common.ApplicationContextHelper;
import com.mmall.common.JsonData;
import com.mmall.common.RequestHolder;
import com.mmall.model.SysUser;
import com.mmall.service.SysCoreService;
import com.mmall.util.JsonMapper;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 权限拦截
* @author Administrator
*
*/
@Slf4j
public class AclControlFilter implements Filter {
private static Set<String> exclusionUrlSet = Sets.newConcurrentHashSet();
//无权限访问页面URL
private final static String noAuthUrl = "/sys/user/noAuth.page";
@Override
public void init(FilterConfig filterConfig) throws ServletException {
//定义白名单
String exclusionUrls = filterConfig.getInitParameter("exclusionUrls");
List<String> exclusionUrlList = Splitter.on(",").trimResults().omitEmptyStrings().splitToList(exclusionUrls);
exclusionUrlSet = Sets.newConcurrentHashSet(exclusionUrlList);
exclusionUrlSet.add(noAuthUrl);
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String servletPath = request.getServletPath();
Map requestMap = request.getParameterMap();
//请求在白名单内则不拦截
if (exclusionUrlSet.contains(servletPath)) {
filterChain.doFilter(servletRequest, servletResponse);
return;
}
//取出当前登录用户
SysUser sysUser = RequestHolder.getCurrentUser();
//如果没有登录就访问权限,执行无权限方法
if (sysUser == null) {
log.info("someone visit {}, but no login, parameter:{}", servletPath, JsonMapper.obj2String(requestMap));
noAuth(request, response);
return;
}
SysCoreService sysCoreService = ApplicationContextHelper.popBean(SysCoreService.class);
//是否有权限访问URL
if (!sysCoreService.hasUrlAcl(servletPath)) {
log.info("{} visit {}, but no login, parameter:{}", JsonMapper.obj2String(sysUser), servletPath, JsonMapper.obj2String(requestMap));
noAuth(request, response);
return;
}
filterChain.doFilter(servletRequest, servletResponse);
return;
}
/**
* 无权限访问方法
* @param request
* @param response
* @throws IOException
*/
private void noAuth(HttpServletRequest request, HttpServletResponse response) throws IOException {
String servletPath = request.getServletPath();
if (servletPath.endsWith(".json")) {
JsonData jsonData = JsonData.fail("没有访问权限,如需要访问,请联系管理员");
response.setHeader("Content-Type", "application/json");
response.getWriter().print(JsonMapper.obj2String(jsonData));
return;
} else {
clientRedirect(noAuthUrl, response);
return;
}
}
/**
* 无权限,跳转无权限页面
* @param url
* @param response
* @throws IOException
*/
private void clientRedirect(String url, HttpServletResponse response) throws IOException{
response.setHeader("Content-Type", "text/html");
response.getWriter().print("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n"
+ "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" + "<head>\n" + "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\"/>\n"
+ "<title>跳转中...</title>\n" + "</head>\n" + "<body>\n" + "跳转中,请稍候...\n" + "<script type=\"text/javascript\">//<![CDATA[\n"
+ "window.location.href='" + url + "?ret='+encodeURIComponent(window.location.href);\n" + "//]]></script>\n" + "</body>\n" + "</html>\n");
}
@Override
public void destroy() {
}
}
接收参数
package com.mmall.param;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
/**
* 用户参数
* @author Administrator
*
*/
@Getter
@Setter
public class UserParam {
private Integer id;
@NotBlank(message = "用户名不可以为空")
@Length(min = 1, max = 20, message = "用户名长度需要在20个字以内")
private String username;
@NotBlank(message = "电话不可以为空")
@Length(min = 1, max = 13, message = "电话长度需要在13个字以内")
private String telephone;
@NotBlank(message = "邮箱不允许为空")
@Length(min = 5, max = 50, message = "邮箱长度需要在50个字符以内")
private String mail;
@NotNull(message = "必须提供用户所在的部门")
private Integer deptId;
@NotNull(message = "必须指定用户的状态")
@Min(value = 0, message = "用户状态不合法")
@Max(value = 2, message = "用户状态不合法")
private Integer status;
@Length(min = 0, max = 200, message = "备注长度需要在200个字以内")
private String remark = "";
}