MD5加密类
package common;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5 {
public static String getMd5(String plainText,int length ) {
String result = "";
try {
MessageDigest md= MessageDigest.getInstance("MD5");
md.update(plainText.getBytes());
byte b[] = md.digest();
int i;
StringBuffer buf = new StringBuffer("");
for (int offset = 0; offset < b.length; offset++) {
i = b[offset];
if(i<0) i+= 256;
if(i<16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
if(length==32) {
//32位加密
result = buf.toString();
}else if(length==16) {
//16位加密
result = buf.toString().substring(8, 24);
}else if(length==6){
result = buf.toString().substring(0, 6);
}else {
return "";
}
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
redis数据库类
package service.serviceImpl;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class RedisAPI {
public JedisPool jedisPool;
public JedisPool getJedisPool() {
return jedisPool;
}
public void setJedisPool(JedisPool jedisPool) {
this.jedisPool = jedisPool;
}
public String get(String key){
Jedis jedis=jedisPool.getResource();
String value= jedis.get(key);
jedisPool.returnResource(jedis);
return value;
}
public String set(String key,String value){
Jedis jedis=jedisPool.getResource();
String result= jedis.set(key, value);
jedisPool.returnResource(jedis);
return result;
}
public String set(String key,int seconds,String value){
Jedis jedis=jedisPool.getResource();
String result=jedis.setex(key, seconds, value);
jedisPool.returnResource(jedis);
return value;
}
public boolean exists(String key){
Jedis jedis=jedisPool.getResource();
boolean result=jedis.exists(key);
jedisPool.returnResource(jedis);
return result;
}
public Long ttl(String key){
Jedis jedis=jedisPool.getResource();
Long result=jedis.ttl(key);
jedisPool.returnResource(jedis);
return result;
}
public Long dell(String key){
Jedis jedis=jedisPool.getResource();
Long result=jedis.del(key);
jedisPool.returnResource(jedis);
return result;
}
}
token的生成和保存接口类
package service;
import entity.User;
public interface TokenService {
//生成token
public String generateToken(String userAgent, User user) throws Exception;
//生成save
public void save(String token, User user) throws Exception;
public boolean validate(String userAgent,String token) throws Exception;}
token接口的实现类 token生成类型:PC-NAME-USERID-CREATIONDATE-RONDEM(6位)
既: PC-32位加密的用户名-用户id-年月日时分秒-6位随机数
package service.serviceImpl;
import com.alibaba.fastjson.JSON;
import common.MD5;
import entity.User;
import nl.bitwalker.useragentutils.UserAgent;
import org.springframework.stereotype.Service;
import service.TokenService;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
@Service("tokenService")
public class TokenServiceImpl implements TokenService {
@Resource
private RedisAPI redisAPI;
@Override
// pc-32位加密的用户名-用户id-年月日时分 秒-6位随机数
//前缀 PC-NAME-USERID-CREATIONDATE-RONDEM(6位)
// 生成token
public String generateToken(String userAgent, User user) throws Exception {
StringBuilder str=new StringBuilder();
str.append("token:");
//获取用户代理
UserAgent agent=UserAgent.parseUserAgentString(userAgent);
//判断是否是手机端还是电脑端
if(agent.getOperatingSystem().isMobileDevice()){
str.append("MOBILE-");
}else{
str.append("PC-");
}
str.append(MD5.getMd5(user.getName(),32)+"-");
str.append(user.getId().toString()+"-");
str.append(new SimpleDateFormat("yyyyMMddHHmmsss").format(new Date())+"-");
str.append(MD5.getMd5(userAgent,6));
return str.toString();
}
@Override
// 保存token信息
public void save(String token,User user) throws Exception {
if(token.startsWith("token:PC-")){
redisAPI.set(token, 2 * 60 * 60, JSON.toJSONString(user));
}else{
redisAPI.set(token, JSON.toJSONString(user));
}
}
@Override
public boolean validate(String userAgent, String token) throws Exception {
String agentMd5 = token.split("-")[4];
if(!redisAPI.exists(token)){
return false;
}else if(!MD5.getMd5(userAgent,6).equals(agentMd5)){
return false;
}
return true;
} }
用户service层
package service;
import entity.User;
public interface UserService {
public User login(String name, String password) throws Exception;
public User findUser(String name)throws Exception;
}
用户service层实现类
```
package service;
import entity.User;
public class UserServiceImpl implements UserService{
@Override
public User login(String name, String password) throws Exception {
User user=this.findUser(name);
if(user!=null && user.getPassword().equals(password)){
return user;
}
else
return null;
}
@Override
public User findUser(String name) throws Exception {
return null;
}
}
controller层
package Controller;
import common.MD5;
import entity.User;
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 service.TokenService;
import service.UserService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
@Controller
@RequestMapping("/api")
public class LoginController{
@Resource
private TokenService tokenService;
@Resource
private UserService userService;
@RequestMapping(value="/dologin",method =RequestMethod.POST,
produces = "application/json")
public void login(@RequestParam String name, @RequestParam String password,
HttpServletRequest request){
try {
User user=userService.login(name, MD5.getMd5(password,32));
if(user!=null && !user.equals("")){
String userAgent=request.getHeader("user-agent");
String token =tokenService.generateToken(userAgent,user);
tokenService.save(token,user);
}
} catch (Exception e) {
e.printStackTrace();
}
} }
感觉有帮助,就关注下吧。谢谢!