ps:这里我们需要用到shrio的权限控制和登录验证。
1、创建好表之后,需要对原始密码进行处理然后存到数据库。这里用到md5加密算法:
import org.apache.shiro.crypto.hash.Md5Hash;
public class md5Util {
public static String md5(String str,String salt){
return new Md5Hash(str,salt).toString();
}
}
2、自定义登录验证规则,验证成功则返回当前用户信息
package com.hxm.realm;
import javax.annotation.Resource;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import com.hxm.entity.Blogger;
import com.hxm.service.BloggerService;
/**
* 自定义Realm
* @author Administrator
*
*/
public class MyRealm extends AuthorizingRealm{
@Resource
private BloggerService bloggerService;
/**
* 为当前的登录的用户角色和权限
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
return null;
}
/**
* 验证当前登录的用户
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String userName=(String) token.getPrincipal();
Blogger blogger=bloggerService.getByUserName(userName);
if(blogger!=null){
SecurityUtils.getSubject().getSession().setAttribute("currentUser", blogger); // 把当前用户信息存到session中
AuthenticationInfo authcInfo=new SimpleAuthenticationInfo(blogger.getUserName(), blogger.getPassword(), "xxx");
return authcInfo;
}else{
return null;
}
}
}
3、controller实现用户登录package com.hxm.controller;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.hxm.entity.Blogger;
import com.hxm.service.BloggerService;
import com.hxm.util.CryptographyUtil;
/**
* Controller层
* @author Administrator
*
*/
@Controller
@RequestMapping("/blogger")
public class BloggerController {
@Resource
private BloggerService bloggerService;
@RequestMapping("/login")
public String login(Blogger blogger,HttpServletRequest request){
Subject subject=SecurityUtils.getSubject();
UsernamePasswordToken token=new UsernamePasswordToken(blogger.getUserName(), CryptographyUtil.md5(blogger.getPassword(), "123"));
try{
subject.login(token); // 登录验证,验证通过则跳转到主页面
return "redirect:/admin/main.jsp";
}catch(Exception e){
e.printStackTrace();
request.setAttribute("blogger", blogger);
request.setAttribute("errorInfo", "用户名或者密码错误,请重新输入。");
return "login";
}
}
}
至此,一个简单的用户登录验证就实现了。