简单又好用的Tomcat 页面权限控制

2 篇文章 0 订阅
不废话,就2个配置文件,直接上代码。
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<!--
<resource-ref>
<res-ref-name>jdbc/mt</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
<security-role>
<role-name>R_CASE_IT</role-name>
</security-role>
-->

<security-constraint>
<display-name>web</display-name>
<web-resource-collection>
<url-pattern>/index.jsp</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>R_CASE_IT</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/login.jsp</form-login-page>
<form-error-page>/error.jsp</form-error-page>
</form-login-config>
</login-config>
<error-page>
<error-code>403</error-code>
<location>/403.jsp</location>
</error-page>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>


tomcat中的context.xml

<?xml version="1.0" encoding="UTF-8"?>
<Context path="/web">
<Resource auth="Container"
driverClassName="oracle.jdbc.OracleDriver"
maxActive="10"
maxIdle="4"
maxWait="5000"
name="jdbc/mt"
password=""
type="javax.sql.DataSource"
url=""
username="" />
<!--
-->
<Realm className="org.apache.catalina.realm.DataSourceRealm"
localDataSource="true"
dataSourceName="jdbc/mt"
roleNameCol="role_id"
userCredCol="password"
userNameCol="user_id"
userRoleTable="rsms_user_in_roles"
userTable="rsms_users" />
</Context>

登录页面login.jsp

<form action="j_security_check" method="post">
Username<input type="text" name="j_username" /><br />
Password<input type="password" name="j_password" /><br />
<input type="submit" />
</form>


在配置中遇到的问题:
在登录的时候报这个:name jdbc is not bound in this context
解决办法,在realm配置中加上 localDataSource="true",否则会在tomcat中定义的realm中找dataSource,即(针对tomcat-user.xml定义的UserDataSource),原因看下面的源代码。
在org.apache.catalina.realm.DataSourceRealm中打开数据库连接的源代码:

Context context = null;
if (localDataSource) {
context = ContextBindings.getClassLoader();
context = (Context) context.lookup("comp/env");
} else {
context =
((StandardServer)getServer()).getGlobalNamingContext();
}
DataSource dataSource = (DataSource)context.lookup(dataSourceName);


如果要自定义用户验证方式,将realm中的DataSourceRealm换成自定义的类(继承RealmBase或实现Realm接口,实现其验证方法)即可
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值