快速添加spring security模块

本文介绍如何快速使用Spring Security为应用程序添加认证功能。通过简单的步骤,实现基于数据库的用户名密码验证,以及对不同资源的访问控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如果你只是听说了spring security的大名,但是知之甚少,但是又希望马上把验证功能添加到自己的程序中的人,那么就继续阅读吧,5分钟之内,如果上帝保佑,并且你复制粘贴得够快。
最终的效果是这样的,用户名和密码都保存在数据库中;属于表单提交的登录;并且采用spring自带的j_spring_security_check来验证。如果结尾您觉得太简陋了,那就自行改进,要知道,5分钟,我也不可能带你走很远。因为写文章前半个小时,我刚刚走通这一步。
首先,页面上是这样的:

<form action="j_spring_security_check">
<input type="text" name="j_username" >
<input type="password" name="j_password">
<input type="submit" value="login" > <input type="reset" value="reset">
</form>

当然,我去掉了样式。注意input的name都是固定的名字,因为我们用的是默认的[quote]j_spring_security_check[/quote]。

然后需要改变web.xml。

<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

这个要放在struts的filter之前,如果您的web.xml文件中有的话。

然后是applicationContext.xml文件,这个文件里面要配置两项,第一是配置数据源,
如果现有的数据库中用户表叫做[quote]users[/quote],并且其中包含了username,password,authorities三项,那么authorities-by-username-query这个属性就不用写了,我这里写是因为我的数据库中,用户表叫做usertable,

<security:authentication-provider>
<security:password-encoder hash="md5"/>
<security:jdbc-user-service data-source-ref="dataSource" authorities-by-username-query="select username,authority from usertable where username=?"/>
</security:authentication-provider>

然后需要设置哪些资源要被保护起来,访问的权限,登录成功后展示的页面,访问被拒绝的展示页面等。

<security:http auto-config="true" access-denied-page="/accessDenied.jsp">
<security:intercept-url pattern="/login.html" filters="none"/>
<security:intercept-url pattern="/img/*.*" filters="none"/>
<security:intercept-url pattern="/styles/*.*" filters="none"/>
<security:intercept-url pattern="/**" access="ROLE_ADMIN" />
<security:form-login login-page='/login.html' authentication-failure-url="/login.html" default-target-url="/main.jsp"
/>
<security:logout logout-success-url="/login.html"/>
</security:http>

好了,一切都结束了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值