Spring 3.0中将拦截器集成到Web请求中

发布于 2024-10-18 16:32:42 字数 3109 浏览 5 评论 0原文

目前我正在开发一个 Web 项目,并使用 spring 3.0 和注释基控制器。

  1. 我正在尝试使用拦截来登录。
  2. 无法直接访问任何网址,只能使用拦截器登录。

我能够编写一个拦截器,在不提供登录所需参数的情况下,该拦截器不会让任何人进入网站。但问题是,剩下的页面也可以直接访问。

我正在与您分享我的 servlet.xml

我还想知道为什么我必须定义 URL 映射才能使拦截器工作,否则它会进入无限循环。

请帮助我解决这个问题,如果您有任何满足此要求的工作示例,请也分享。

先感谢您。

springmvc-servlet.xml

  <?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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan
        base-package="com.waqas.app.controller" />

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>



        <bean id="urlMapping"
        class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="urlMap">
            <map>
        <!--  -->   
            <entry key="contacts.htm"><ref bean="contactController" /></entry>
                    <entry key="users.htm"><ref bean="loginController" /></entry>

                            <entry key="hello.htm"><ref bean="helloController" /></entry>


            </map>
        </property>
    </bean>


    <bean name="contactController" class="com.waqas.app.controller.ContactController" />

        <bean name="helloController" class="com.waqas.app.controller.HelloWorldController" />


   <bean name="loginController" class="com.waqas.app.controller.LoginController" />



        <bean id="handlerMapping"
          class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="interceptors">
            <list>
                <ref bean="loginInterceptor"/>
            </list>
        </property>
          <property name="mappings">
            <value>

            *.htm=contactController

            </value>
        </property>

    </bean>



    <bean id="loginInterceptor"
          class="com.waqas.app.interceptor.LoginInterceptor">

    </bean>






</beans>

index.html

<%@ include file="/WEB-INF/jsp/include.jsp" %>
<jsp:forward page="contacts.htm"></jsp:forward>

我也想在特定的 URL/url 模式上应用这个拦截器。

期待你的答复。

亲切的问候, 卡西贝特

Currently I am working on a web project and using spring 3.0 with annotation bases controllers.

  1. I am trying to use intercept for login.
  2. No url can be directly hit but from login using interceptor.

I am able to write an interceptor which won't let pass anyone to move into website without giving required parameters for login. But problem is that, remaining pages can also be accessed directly.

I am sharing with you my servlet.xml

I am also wondering why I have to defien URL mappings to get interceptor working, otherwise it goes into a unlimited loop.

please help me out in solving this issue, if you have any working example for this requirement, then please share it too.

Thank you in advance.

springmvc-servlet.xml

  <?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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan
        base-package="com.waqas.app.controller" />

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>



        <bean id="urlMapping"
        class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="urlMap">
            <map>
        <!--  -->   
            <entry key="contacts.htm"><ref bean="contactController" /></entry>
                    <entry key="users.htm"><ref bean="loginController" /></entry>

                            <entry key="hello.htm"><ref bean="helloController" /></entry>


            </map>
        </property>
    </bean>


    <bean name="contactController" class="com.waqas.app.controller.ContactController" />

        <bean name="helloController" class="com.waqas.app.controller.HelloWorldController" />


   <bean name="loginController" class="com.waqas.app.controller.LoginController" />



        <bean id="handlerMapping"
          class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="interceptors">
            <list>
                <ref bean="loginInterceptor"/>
            </list>
        </property>
          <property name="mappings">
            <value>

            *.htm=contactController

            </value>
        </property>

    </bean>



    <bean id="loginInterceptor"
          class="com.waqas.app.interceptor.LoginInterceptor">

    </bean>






</beans>

index.html

<%@ include file="/WEB-INF/jsp/include.jsp" %>
<jsp:forward page="contacts.htm"></jsp:forward>

i also want to apply this interceptor on sepcific URLs/url pattern.

Looking forward to your reply.

Kind Regards,
qasibeat

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

北恋 2024-10-25 16:32:42

这是一个很常见的问题。 Scott Murphy 创建了一个很好的 spring 插件,允许根据 URL 在控制器上指定拦截器。您可以从 springplugins 下载它。

另请参阅 Spring Framework 基于注释的控制器拦截器配置

编辑: 对于版本 3.1 +,请参阅我对问题控制对控制器的访问的回答,以根据 URL 模式配置拦截器。

This is quite a common problem. Scott Murphy has created a nice spring plugin that allows to specify interceptor on a controller based on URLs. You can download it from springplugins.

Also see Spring Framework Annotation-based Controller Interceptor Configuration

EDIT: For version 3.1+, see my answer to the question Control Access to Controllers to configure interceptor based on URL patterns.

寂寞清仓 2024-10-25 16:32:42

性能监视器拦截器示例。每当请求花费超过 2 秒时就会记录。

public class PerformanceMonitorHandlerInterceptor implements HandlerInterceptor {

        private static Logger logger = Logger.getLogger( PerformanceMonitorHandlerInterceptor.class );

        /** Default to not active and 2 seconds. */
        private boolean active = true;

        /** The threshold. */
        private long threshold = 2000;

        /**
         * Starts the StopWatch to time request.
         * @param handler the handler
         * @param request the request
         * @param response the response
         * @return true, if pre handle
         * @throws Exception the exception
         * @see org.springframework.web.servlet.HandlerInterceptor#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
         *      java.lang.Object)
         */
        @SuppressWarnings("unused")
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                // Start Watch
                if ( this.active ) {
                        String name = this.createRequestTraceName( request );
                        StopWatch stopWatch = new StopWatch( name );
                        stopWatch.start( name );
                        StopWatchHolder.setStopWatch( stopWatch );
                }

                // Continue with request
                return true;
        }

        /**
         * Warn if method takes longer than threshold milliseconds.
         * @param handler the handler
         * @param request the request
         * @param modelAndView the model and view
         * @param response the response
         * @throws Exception the exception
         * @see org.springframework.web.servlet.HandlerInterceptor#postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
         *      java.lang.Object, org.springframework.web.servlet.ModelAndView)
         */
        @SuppressWarnings("unused")
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
                if ( this.active ) {
                        // Stop Watch
                        StopWatch stopWatch = StopWatchHolder.getStopWatch();
                        stopWatch.stop();

                        // Check threshold and log if over
                        if ( stopWatch.getLastTaskTimeMillis() >= this.threshold ) {
                                logger.warn( stopWatch.shortSummary() );
                        }

                        // Set ThreadLocal to null
                        StopWatchHolder.clear();
                }
        }

        /**
         * Not implemented.
         * @param handler the handler
         * @param exception the exception
         * @param request the request
         * @param response the response
         * @throws Exception the exception
         * @see org.springframework.web.servlet.HandlerInterceptor#afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
         *      java.lang.Object, java.lang.Exception)
         */
        @SuppressWarnings("unused")
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception {
        // not implemented
        }

        /**
         * Creates the request trace name.
         * @param request the request
         * @return trace name
         */
        protected String createRequestTraceName(HttpServletRequest request) {
                StringBuilder sb = new StringBuilder();
                sb.append( "url: [" );
                sb.append( request.getRequestURL() );
                sb.append( "]" );
                sb.append( "  query: [" );
                sb.append( request.getQueryString() );
                sb.append( "]" );
                return sb.toString();
        }

        /**
         * Sets the threshold.
         * @param threshold The threshold to set.
         */
        public void setThreshold(long threshold) {
                this.threshold = threshold;
        }

        /**
         * Sets the active.
         * @param active The active to set.
         */
        public void setActive(boolean active) {
                this.active = active;
        }
}

然后将 bean 插入到您的 bean 名称 url 映射中:

    <bean id="handlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">
            <property name="interceptors">
            <list>
                    <ref bean="performanceMonitorHandlerInterceptor" />
                    </list>
            </property>
    </bean>

A Performance Monitor Interceptor Example. It logs whenever a request takes over 2seconds.

public class PerformanceMonitorHandlerInterceptor implements HandlerInterceptor {

        private static Logger logger = Logger.getLogger( PerformanceMonitorHandlerInterceptor.class );

        /** Default to not active and 2 seconds. */
        private boolean active = true;

        /** The threshold. */
        private long threshold = 2000;

        /**
         * Starts the StopWatch to time request.
         * @param handler the handler
         * @param request the request
         * @param response the response
         * @return true, if pre handle
         * @throws Exception the exception
         * @see org.springframework.web.servlet.HandlerInterceptor#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
         *      java.lang.Object)
         */
        @SuppressWarnings("unused")
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                // Start Watch
                if ( this.active ) {
                        String name = this.createRequestTraceName( request );
                        StopWatch stopWatch = new StopWatch( name );
                        stopWatch.start( name );
                        StopWatchHolder.setStopWatch( stopWatch );
                }

                // Continue with request
                return true;
        }

        /**
         * Warn if method takes longer than threshold milliseconds.
         * @param handler the handler
         * @param request the request
         * @param modelAndView the model and view
         * @param response the response
         * @throws Exception the exception
         * @see org.springframework.web.servlet.HandlerInterceptor#postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
         *      java.lang.Object, org.springframework.web.servlet.ModelAndView)
         */
        @SuppressWarnings("unused")
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
                if ( this.active ) {
                        // Stop Watch
                        StopWatch stopWatch = StopWatchHolder.getStopWatch();
                        stopWatch.stop();

                        // Check threshold and log if over
                        if ( stopWatch.getLastTaskTimeMillis() >= this.threshold ) {
                                logger.warn( stopWatch.shortSummary() );
                        }

                        // Set ThreadLocal to null
                        StopWatchHolder.clear();
                }
        }

        /**
         * Not implemented.
         * @param handler the handler
         * @param exception the exception
         * @param request the request
         * @param response the response
         * @throws Exception the exception
         * @see org.springframework.web.servlet.HandlerInterceptor#afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse,
         *      java.lang.Object, java.lang.Exception)
         */
        @SuppressWarnings("unused")
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) throws Exception {
        // not implemented
        }

        /**
         * Creates the request trace name.
         * @param request the request
         * @return trace name
         */
        protected String createRequestTraceName(HttpServletRequest request) {
                StringBuilder sb = new StringBuilder();
                sb.append( "url: [" );
                sb.append( request.getRequestURL() );
                sb.append( "]" );
                sb.append( "  query: [" );
                sb.append( request.getQueryString() );
                sb.append( "]" );
                return sb.toString();
        }

        /**
         * Sets the threshold.
         * @param threshold The threshold to set.
         */
        public void setThreshold(long threshold) {
                this.threshold = threshold;
        }

        /**
         * Sets the active.
         * @param active The active to set.
         */
        public void setActive(boolean active) {
                this.active = active;
        }
}

Then plug the bean into your bean name url mapping:

    <bean id="handlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">
            <property name="interceptors">
            <list>
                    <ref bean="performanceMonitorHandlerInterceptor" />
                    </list>
            </property>
    </bean>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文