权限控制 Shiro采用JdbcRealm(JNDI)
1.在web.xml中添加过滤器
<filter>
<filter-name>ShiroFilter</filter-name>
<filter-class>org.apache.shiro.web.servlet.IniShiroFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ShiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
注意:此段代码的放置位置也是需要注意的,比如我就将其放置在web.xml中最前的位置。否则,shiro可能不会起到效果,甚至会造成其它未知错误。
2.在项目的classpath路径(和java文件同一目录下 src 下)下添加 shiro.ini文件
注意:此处采用oracle数据库(其它数据库配置形式相同,比较简单,倒是oracle配置略有差别)
[main]
ds = oracle.jdbc.pool.OracleDataSource
ds.driverType=thin
ds.networkProtocol=tcp
ds.serverName=192.168.32.13
ds.databaseName = orcl
ds.portNumber=1521
ds.user = lanwan
ds.password = ustclanwan
jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm
jdbcRealm.permissionsLookupEnabled = true
jdbcRealm.authenticationQuery = select login_pwd from sys_c_ul where worker_code=?
jdbcRealm.userRolesQuery = select role_id from sys_j_ur where worker_id=?
jdbcRealm.permissionsQuery=select file_id from sys_j_rrs where role_id in(select role_id from sys_j_ur where worker_id=?)
jdbcRealm.dataSource = $ds
[filters]
authc.loginUrl = index.jsp
[urls]
/index.jsp = anon
其中:
jdbcRealm.authenticationQuery =
jdbcRealm.userRolesQuery =
jdbcRealm.permissionsQuery=
可以根据需要自定义。
另附上采用JNDI数据源的用法:
[main]
ds = org.apache.shiro.jndi.JndiObjectFactory
ds.resourceName = java:jboss/datasources/IPSST
ds.requiredType = javax.sql.DataSource
jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm
jdbcRealm.permissionsLookupEnabled = true
jdbcRealm.authenticationQuery = select login_pwd from hr_j_emp_info where emp_name=?
jdbcRealm.dataSource = $ds
[filters]
authc.loginUrl = index.jsp
3、在java文件中进行登录操作(非本文重点,本文只是想记录使用jndi的用法),只是做了登录,角色、权限可产考其它文章。
String loginAccount=request.getParameter("userCode");
String pwd=request.getParameter("pwd");
Subject subject = SecurityUtils.getSubject();
String MD5Str=
SecurityManager.GetMD5Str32(SecurityManager.GetMD5Str32(pwd));
UsernamePasswordToken token =
new UsernamePasswordToken(loginAccount,MD5Str);
try {
subject.login(token);
token.setRememberMe(true);
} catch (UnknownAccountException uae) {
return loginFailed();
} catch (IncorrectCredentialsException ice) {
return loginFailed();
} catch (LockedAccountException lae) {
return loginFailed();
} catch (AuthenticationException ae){
return loginFailed();
}