如何使用spring security验证用户?

时间:2014-04-21 08:50:26

标签: java spring spring-mvc spring-security

我想实现spring security登录并注销,所以我尝试了以下内容, 弹簧context.xml中:

<http auto-config="true">
        <intercept-url pattern="/**" access="isAuthenticated"/>  <!-- this  means all URL in this app will be checked if user is authenticated -->
        <form-login/> <!--  -->
        <logout logout-url="/logout" logout-success-url=""/>
 </http>
 <authentication-manager>
        <authentication-provider> 
            <user-service>
                <user name="sachin" password="sachin123" authorities="Admin"/>
            </user-service>
 </authentication-provider>

弹簧servlet.xml中:

<context:component-scan base-package="com.hrportal.controller" />
    </context:annotation-config>
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>

    <bean id="localeChangeInterceptor"
        class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
        <property name="paramName" value="lang" />
    </bean>

    <bean id="localeResolver"
        class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
        <property name="defaultLocale" value="en" />
    </bean>

    <bean id="handlerMapping"
        class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
        <property name="interceptors">
            <ref bean="localeChangeInterceptor" />
        </property>
            </bean>
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
    <mvc:resources mapping="/images/**"  location="/images/"/>
    <mvc:resources location="/css/**" mapping="/css/"/>
    <mvc:resources location="/css/**" mapping="/css/"/>
    <mvc:default-servlet-handler/>

我正在手动进行数据库连接和访问,这就是我无法使用spring security实现登录和注销的原因。

我使用以下类手动连接数据库:

private static Connection con = null;

public static Connection getConnection() {
    try {
        if (con == null) {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/portal",
                    "root", "root");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return con;
}

}

任何人都可以解释我解决这个问题。

1 个答案:

答案 0 :(得分:0)

尝试使用spring roo,这个rad工具可以帮助您自动生成代码并配置弹簧安全性。 http://docs.spring.io/spring-roo/reference/html/beginning.html