1、 首先搭建spring+springMVC+MyBatis的配置
1.1、数据库的连接配置(jdbc.properties):
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://ip/instance?;useUnicode=true;characterEncoding=UTF-8;autoReconnect=true
username=root
password=123456
#定义初始连接数
initialSize=0
#定义最大连接数
maxActive=20
#定义最小空闲
minIdle=1
#定义最长等待时间
maxWait=60000
1.2、Mybatis(spring-mybatis.xml)的相关配置:
1.3、spring-mvc(spring-mvc.xml)的配置
1.4、shiro(spring-shiro-demo.xml)的配置
/index/goLogin = anon
/index/login = anon
/index/logout = logout
/user/** = authc
/** = anon
1.5、编写自己的Realm,继承AuthorizingRealm,重写doGetAuthorizationInfo和doGetAuthenticationInfo方法,当我们在登录方法中调用SecurityUtils.getSubject().login(token)时会间接调用我们指定Realm的doGetAuthenticationInfo方法来验证用户信息。
代码块:
package com.icinfo.relam;
import com.icinfo.model.User;
import com.icinfo.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import java.util.List;
/**
* @author fz
* @create 2019-01-08 下午 4:41
*/
public class MyShiroRealm extends AuthorizingRealm {
private UserService userService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
return null;
}
/**
* 获取验证信息
* @param token
* @return
* @throws AuthenticationException
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
if(StringUtils.isBlank(usernamePasswordToken.getUsername())){
return null;
}
/**
* 下面可以写自己的验证逻辑(因为是测试用例,简单验证下)
*/
User user = userService.findUserByUsername(usernamePasswordToken.getUsername());
if(user == null){
throw new AuthenticationException("用户信息认证失败");
}
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(usernamePasswordToken.getUsername(), user.getPassword(), getName());
return info;
}
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
}
1.6、web.xml需要添加的配置
shiroFilter
org.springframework.web.filter.DelegatingFilterProxy
targetFilterLifecycle
true
shiroFilter
/*
1.7、(IndexController)
package com.icinfo.controller;
import com.icinfo.dto.LoginDto;
import com.icinfo.framework.common.ajax.AjaxResult;
import com.icinfo.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author fz
* @create 2019-01-17 下午 5:46
*/
@Controller
@RequestMapping("/index")
public class IndexController {
@Autowired
UserService userService;
Logger logger = LoggerFactory.getLogger(IndexController.class);
@RequestMapping("/goLogin")
public ModelAndView goLogin(){
System.out.println("---------------访问主页面----------------");
ModelAndView mav = new ModelAndView("login");
return mav;
}
@RequestMapping("/login")
@ResponseBody
public AjaxResult login(HttpServletRequest request, HttpServletResponse response, LoginDto loginDto) throws Exception{
if(loginDto == null || StringUtils.isBlank(loginDto.getUsername()) || StringUtils.isBlank(loginDto.getPassword())){
return AjaxResult.error("用户名或密码不能为空");
}
UsernamePasswordToken token = new UsernamePasswordToken(loginDto.getUsername(),loginDto.getPassword().toCharArray());
Subject subject = SecurityUtils.getSubject();
try{
subject.login(token);
}catch (Exception e){
logger.info("登录失败,失败原因:[{}]", e.getMessage());
e.printStackTrace();
return AjaxResult.error("登录失败,请检查用户名和密码是否正确!");
}
return AjaxResult.success("success");
}
/**
* 首页
* @return
* @throws Exception
*/
@RequestMapping
public ModelAndView index() throws Exception{
ModelAndView mav = new ModelAndView("index");
return mav;
}
/**
* 登出
* @return
* @throws Exception
*/
@RequestMapping("logout")
public String logout() throws Exception{
Subject subject = SecurityUtils.getSubject();
if(subject.isAuthenticated()){
subject.logout();
}
return "redirect:/index/goLogin";
}
}
1.8、(UserController)
package com.icinfo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* 用户控制器
*
* @author fz
* @create 2019-01-28 上午 10:58
*/
@RequestMapping("/user")
@Controller
public class UserController {
@RequestMapping("/userAddPage")
public ModelAndView userAddPage() throws Exception{
ModelAndView mav = new ModelAndView("user_add");
return mav;
}
}
2、前台简单页面测试
2.1、登录页面(login.jsp)
<%@ page contentType="text/html;charset=UTF-8" trimDirectiveWhitespaces="true"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
登录页面
2.2、login.js
$(function () {
$("#submit").click(function () {
$.ajax({
url:'/index/login',
type:'post',
dataType: 'json',
data:$("#form").serializeObject(),
success: function (json) {
console.log(json);
if(json.status=="success"){
window.location.href = '/index';
}else{
alert(json.msg);
}
}
})
})
})
2.3、index.jsp
<%@ page contentType="text/html;charset=UTF-8" trimDirectiveWhitespaces="true"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
首页
登录成功。
2.4、user_add.jsp
<%@ page contentType="text/html;charset=UTF-8" trimDirectiveWhitespaces="true"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
首页
添加用户页面
3、测试阶段
3.1、验证未登录情况下跳转到login.jsp
3.1.1、输入新增用户页面地址
3.1.2、跳转到用户登录页面
3.1.3、输入错误的用户名密码
3.1.4、提示用户名或密码错误
3.1.5、输入正确的用户名和密码
3.1.6、登录成功,跳转到首页
3.1.7 这时可以打开新增用户页面
到这一个简单的用户登录的例子就做完了,作者水平有限,写的不对的地方请留言,轻喷!!!!!