代码下载 http://download.youkuaiyun.com/download/knight_black_bob/9698729
代码已上传 ,
其中 springmvc +hibernate 封装的非常好用,大家可以学习下
实例解析 :
首先访问 http://localhost:8083/springmvchibernate/web/user/showallusers
然后没有登陆
http://localhost:8083/springmvchibernate/web/user/tologin
登陆过后
http://localhost:8083/springmvchibernate/web/user/showallusers
可以 访问 前提我是有 这个权限的
如果没有该权限 就进不去
@Entity
@Table(name = "t_user")
public class User extends BaseEntity implements Serializable{
/**
*
*/
private static final long serialVersionUID = -1461963356403533227L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name = "user_name")
private String userName;
@Column(name = "password")
private String password;
@Column(name = "tel")
private String tel;
@Column(name = "sex")
private String sex;
@Column(name = "description")
private String description;
@ManyToMany(cascade = CascadeType.PERSIST)
@JoinTable(name = "t_user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private List<Role> roles;
@Transient
private long[] rightSum;
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public String getUserName() {
return userName;
}
public String getPassword() {
return password;
}
public String getTel() {
return tel;
}
public String getSex() {
return sex;
}
public String getDescription() {
return description;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setPassword(String password) {
this.password = password;
}
public void setTel(String tel) {
this.tel = tel;
}
public void setSex(String sex) {
this.sex = sex;
}
public void setDescription(String description) {
this.description = description;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "User [id=" + id + ", userName=" + userName + ", password=" + password + ", tel="
+ tel + ", sex=" + sex + ", description=" + description + "]";
}
public void calculateRightSum() {
int pos = 0;
long code = 0;
for(Role role: roles){
if("-1".equals(role.getRoleValue())){
roles = null;
return;
}
for(Right right: role.getRights()){
pos = right.getRightPos();
code = right.getRightCode();
rightSum[pos] = rightSum[pos] | code;
}
}
roles = null;
}
public boolean hasRight(Right r){
int pos = r.getRightPos();
long code = r.getRightCode();
return !((rightSum[pos] & code) == 0);
}
}
@Entity
@Table(name = "t_role")
public class Role extends BaseEntity implements Serializable{
/**
*
*/
private static final long serialVersionUID = -3249248953909188737L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name = "role_name")
private String roleName;
@Column(name = "role_value")
private String roleValue;
@Column(name = "role_desc")
private String roleDesc;
@ManyToMany(mappedBy = "roles")
@Basic(fetch = FetchType.LAZY)
private List<User> users;
@ManyToMany(cascade={CascadeType.PERSIST,CascadeType.REFRESH,CascadeType.MERGE}, fetch = FetchType.LAZY)
@JoinTable(name = "t_role_right", joinColumns = @JoinColumn(name = "role_id"), inverseJoinColumns = @JoinColumn(name = "right_id"))
private List<Right> rights;
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public int getId() {
return id;
}
public String getRoleName() {
return roleName;
}
public String getRoleValue() {
return roleValue;
}
public String getRoleDesc() {
return roleDesc;
}
public List<Right> getRights() {
return rights;
}
public void setId(int id) {
this.id = id;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public void setRoleValue(String roleValue) {
this.roleValue = roleValue;
}
public void setRoleDesc(String roleDesc) {
this.roleDesc = roleDesc;
}
public void setRights(List<Right> rights) {
this.rights = rights;
}
@Override
public String toString() {
return "Role [id=" + id + ", roleName=" + roleName + ", roleValue=" + roleValue
+ ", roleDesc=" + roleDesc + "]";
}
}
@Entity
@Table(name = "t_right")
public class Right extends BaseEntity implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1444825234975317847L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name = "right_name")
private String rightName = "";
@Column(name = "right_url")
private String rightUrl;
@Column(name = "right_desc")
private String rightDesc;
@Column(name = "right_code")
private long rightCode;
@Column(name = "right_pos")
private int rightPos;
@Column(name = "common")
private boolean common ;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "rights")
private List<Role> roles;
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public int getId() {
return id;
}
public String getRightName() {
return rightName;
}
public String getRightUrl() {
return rightUrl;
}
public String getRightDesc() {
return rightDesc;
}
public long getRightCode() {
return rightCode;
}
public int getRightPos() {
return rightPos;
}
public boolean isCommon() {
return common;
}
public void setId(int id) {
this.id = id;
}
public void setRightName(String rightName) {
this.rightName = rightName;
}
public void setRightUrl(String rightUrl) {
this.rightUrl = rightUrl;
}
public void setRightDesc(String rightDesc) {
this.rightDesc = rightDesc;
}
public void setRightCode(long rightCode) {
this.rightCode = rightCode;
}
public void setRightPos(int rightPos) {
this.rightPos = rightPos;
}
public void setCommon(boolean common) {
this.common = common;
}
@Override
public String toString() {
return "Right [id=" + id + ", rightName=" + rightName + ", rightUrl=" + rightUrl
+ ", rightDesc=" + rightDesc + ", rightCode=" + rightCode + ", rightPos=" + rightPos
+ ", common=" + common + "]";
}
}
@Controller
@RequestMapping("/web/user")
public class UserAciton extends BaseAction {
protected static final Logger logger = LoggerFactory.getLogger(UserAciton.class);
@Resource
private UserService userService;
@RequestMapping(value = "/tologin")
public String toLogin(HttpServletRequest request){
logger.debug("================");
return "/web/user/login";
}
@RequestMapping(value = "/login" ,method=RequestMethod.POST)
public String login(User currUser,HttpServletRequest request){
logger.debug("======login==========");
// String code = (String) session.getAttribute("validateCode");
// String submitCode = WebUtils.getCleanParam(request, "validateCode");
Subject user = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(currUser.getUserName(),currUser.getPassword());
token.setRememberMe(true);
try {
user.login(token);
logger.debug("======login success==========");
return "/web/user/new";
}catch (AuthenticationException e) {
token.clear();
logger.debug("======login error==========");
return "/web/user/tologin";
}
}
@RequestMapping(value = "/new")
public String newForm(HttpServletRequest request){
logger.debug("================");
return "/web/user/new";
}
@RequestMapping(value = "/showallusers")
public String showAllUsers(HttpServletRequest request){
logger.debug("================");
Subject currentUser = SecurityUtils.getSubject();
if(currentUser.isPermitted("/web/user/showallusers")){
return "/web/user/showallusers";
}else{
return "/web/user/new";
}
}
@Transactional
@RequestMapping(value = "/save", method = RequestMethod.POST)
public void add(User user,HttpServletRequest request){
logger.debug("================"+user.toString());
//userService.save(user);
logger.debug("================");
}
@RequestMapping(value = "/test")
public String test(HttpServletRequest request){
User user = new User();
user.setPassword("123456");
user.setSex("1");
user.setTel("15010666051");
user.setUserName("包优");
user.setDescription("test");
//userService.save(user);
logger.debug("================");
return "/web/user/new";
}
}
@Service
public class SysRealm extends AuthorizingRealm implements InitializingBean{
public static Map<String,Right> map = new HashMap<String,Right>();
@Resource
UserService userService;
@Resource
RightService rightService;
@Resource
RoleService roleService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String userName = (String)super.getAvailablePrincipal(principals);
List<String> roleList = new ArrayList<String>();
List<String> permissionList = new ArrayList<String>();
//从数据库中获取当前登录用户的详细信息
User user = userService.find("userName", userName);
if(null != user){
//实体类User中包含有用户角色的实体类信息
if(null!=user.getRoles() && user.getRoles().size()>0){
//获取当前登录用户的角色
for(Role role : user.getRoles()){
roleList.add(role.getRoleName());
//实体类Role中包含有角色权限的实体类信息
if(null!=role.getRights() && role.getRights().size()>0){
//获取权限
for(Right right : role.getRights()){
if(!StringUtils.isEmpty(right.getRightUrl())){
permissionList.add(right.getRightUrl());
}
}
}
/*List<Right> rights= rightService.findByRoleId(role.getId());
if(null!=rights && rights.size()>0){
//获取权限
for(Right right : role.getRights()){
if(!StringUtils.isEmpty(right.getRightUrl())){
permissionList.add(right.getRightUrl());
}
}
}*/
}
}
}else{
}
//为当前用户设置角色和权限
SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
simpleAuthorInfo.addRoles(roleList);
simpleAuthorInfo.addStringPermissions(permissionList);
return simpleAuthorInfo;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
User user = userService.find("userName", token.getUsername());
if (user != null) {
return new SimpleAuthenticationInfo(user.getUserName(), user
.getPassword(), user.getUserName());
} else {
return null;
}
}
@Override
public void afterPropertiesSet() throws Exception {
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:jms="http://www.springframework.org/schema/jms" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:oxm="http://www.springframework.org/schema/oxm"
xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/tool http://www.springframework.org/schema/tool/spring-tool.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"
default-autowire="byName">
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="sysRealm" />
</bean>
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager" />
<property name="loginUrl" value="/web/user/tologin" />
<property name="successUrl" value="/web/user/tologin" />
<property name="unauthorizedUrl" value="/web/user/error" />
<property name="filterChainDefinitions">
<value>
/web/user/error = anon
/web/user/new = anon
/web/user/tologin = anon
/web/user/login = anon
/web/** = authc
</value>
</property>
</bean>
<!-- <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor" />
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager" />
</bean>
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
-->
</beans>
打开 注释,就可以使用注解的方式 进行拦截,不用 url 去 一个个 匹配了
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor" />
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager" />
</bean>
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>3</load-on-startup>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<servlet-name>springmvc</servlet-name>
</filter-mapping>
捐助开发者
在兴趣的驱动下,写一个免费
的东西,有欣喜,也还有汗水,希望你喜欢我的作品,同时也能支持一下。 当然,有钱捧个钱场(右上角的爱心标志,支持支付宝和PayPal捐助),没钱捧个人场,谢谢各位。
谢谢您的赞助,我会做的更好!