`
shiro.ini
[main]
# 没有登入的用户 跳转到 /login url
authc.loginUrl=/login
# 不是这个角色 或者权限所调整的页面
roles.unauthorizedUrl=page/err.jsp
perms.unauthorizedUrl=page/err.jsp
[users]
admin=123,admin,user
guan=123,user
tome=333,student
jocke=321,teacher
test=123
test1=123
[roles]
# admin 角色拥有 user , student , teacher 的操作权限
admin=user:*,student:*,teacher:*
# teacher 角色拥有student,teacher的角色所有操作权限
teacher=student:*,teacher:*
# student 角色拥有student 的所有操作权限
student:student:*
[urls]
#login 这个url 不需要身份认证
/login=anon
# 访问admin url 需要身份认证
/admin=authc
# ?匹配一个字符 /admin1 /adminx
/admin?=autch
# *匹配多个或者零个字符 lg : /admin1 /admin1as
/admin*
# /** 匹配多路径的url lg : /admin/a /admin/a/b
/admin/**
# 访问 student url 需要 teacher 这个角色才行
/student=roles[teacher]
# 访问teacher url 需要有 user 的create 这个权限才行
/teacher=perms["user:create"]
jsp
<strong>
登入成功~~
${username}
<!-- 查看是否拥有该角色 -->
<shiro:hasAnyRoles name="admin">
欢迎 你 admin 管理者 <shiro:principal/>
</shiro:hasAnyRoles>
<br>
<!-- 查看是否拥有该权限 -->
<shiro:hasPermission name="student:select">
拥有 student:select 查询权限的 用户 <shiro:principal/>
</shiro:hasPermission>
<br>
${info}
</strong>
servlet
package core.java.controller.servlet;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//doPost(req,resp);
System.out.println("doing do get");
req.getRequestDispatcher("page/login.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
System.out.println("doing do post ~~~");
String username = req.getParameter("userName");
String password = req.getParameter("password");
UsernamePasswordToken token = new UsernamePasswordToken(username,password);
Subject user = SecurityUtils.getSubject();
try{
user.login(token);
// 登入后可以获得到session
Session session = user.getSession();
System.out.println("Host:"+session.getHost());
System.out.println("sessionId:"+session.getId());
System.out.println("Timeout:"+session.getTimeout());
System.out.println("AttributeKeys:"+session.getAttributeKeys());
System.out.println("StartTimestamp:"+session.getStartTimestamp());
// 设置session 参数
session.setAttribute("info","session 专属参数");
req.setAttribute("username",username);
// resp.sendRedirect("page/success.jsp");
req.getRequestDispatcher("page/success.jsp").forward(req,resp);
}catch (Exception e){
e.printStackTrace();
req.getRequestDispatcher("page/login.jsp").forward(req,resp);
}
}
}
`