【问题标题】:Get Application context URL in SimpleMappingExceptionResolver在 SimpleMappingExceptionResolver 中获取应用程序上下文 URL
【发布时间】:2015-07-07 01:51:18
【问题描述】:

我使用SimpleMappingExceptionResolver 重定向到 URI,以防我的一些自定义异常。

这个问题是重定向不尊重应用程序上下文(我很容易在 JSP 中使用 <c:url value="/" /> 获得)。 问题是我如何在 Spring 配置 XML 中获取它

context.xml -

<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" p:defaultErrorView="errorView">
    <property name="exceptionMappings">
        <props>
            <prop key=".MyCustomException">redirect:/error</prop>
        </props>
    </property>
    <property name="exceptionAttribute"><null/></property>
</bean>

【问题讨论】:

    标签: java spring spring-mvc exception-handling


    【解决方案1】:

    其实还有更好的办法。

    像这样声明你的SimpleMappingExceptionResolver

    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> 
    <property name="exceptionMappings">
        <props>
            <prop key="com.example.MyCustomException">error</prop>
        </props>
    </property>
    </bean>
    

    这将配置 Spring MVC 以在抛出 MyCustomException 时将客户端重定向到错误视图。

    然后,您像这样配置ViewResolver

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

    因此,它将寻找“/WEB-INF/views/error.jsp”页面来呈现。您将不需要 url 或任何东西。春天会照顾好一切。

    参考:http://www.codejava.net/frameworks/spring/how-to-handle-exceptions-in-spring-mvc

    【讨论】:

    • 虽然我在某些情况下使用它,但并非在所有情况下都使用它。在某些情况下,我需要调用重定向,以便调用适当的拦截器堆栈,并且我可以修改响应(标头等)
    • 你能发布一些代码sn-ps来展示这个案例吗?
    猜你喜欢
    • 2011-10-31
    • 2010-09-12
    • 2017-03-17
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-26
    相关资源
    最近更新 更多