简体   繁体   English

Spring Web MVC Java配置 - 默认Servlet名称

[英]Spring Web MVC Java Configuration- Default Servlet Name

I wrote a small application to learn the java configuration in spring as I have been nagged by peers for a while now to upgrade our applications ;-), a simple todo list app, which has security and web mvc configuration, JPA for persistence, all through the java configuration. 我在春天写了一个小应用程序来学习java配置,因为我已经被同行唠叨了一段时间来升级我们的应用程序;-),一个简单的todo列表应用程序,它具有安全性和web mvc配置,JPA用于持久性,所有通过java配置。 I am facing an issue when trying the run the application. 我在尝试运行应用程序时遇到了问题。 The scurity config and JPA etc work fine but I get a null view after successful intercept of protected URLs scurity配置和JPA等工作正常但在成功拦截受保护的URL后我得到一个空视图

The main web app initializer class extends AbstractAnnotationConfigDispatcherServletInitializer 主Web应用程序初始化程序类扩展了AbstractAnnotationConfigDispatcherServletInitializer

public class WiggleWebApplicationInitializer extends
        AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class<?>[] { WiggleApplicationConfig.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {

        return new Class<?>[] { WiggleWebAppConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }

    @Override
    protected void registerDispatcherServlet(ServletContext servletContext) {
        super.registerDispatcherServlet(servletContext);

        servletContext.addListener(new HttpSessionEventPublisher());

    }

    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceEncoding(true);

        return new Filter[] { characterEncodingFilter };
    }
}

the WiggleApplicationConfig imports security, JPA and social WiggleApplicationConfig导入安全性,JPA和社交

@Configuration
@ComponentScan(basePackages = { "wiggle.app.services.*" })
@Import({ WigglePersistenceConfig.class, WiggleSecurityConfig.class,
        WiggleSocialConfig.class })
public class WiggleApplicationConfig {

    @Bean
    public DateFormat dateFormat() {
        return new SimpleDateFormat("dd-MM-yyyy");
    }

}

The web config then adds default handler and the like 然后,Web配置添加默认处理程序等

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "wiggle.app.controllers.*" })
public class WiggleWebAppConfig extends WebMvcConfigurerAdapter {

    private static final String VIEW_RESOLVER_PREFIX = "/WEB-INF/jsp/";
    private static final String VIEW_RESOLVER_SUFFIX = ".jsp";

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations(
                "/static/");
    }

    @Override
    public void configureDefaultServletHandling(
            DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Bean
    public SimpleMappingExceptionResolver exceptionResolver() {
        SimpleMappingExceptionResolver exceptionResolver = new SimpleMappingExceptionResolver();

        Properties exceptionMappings = new Properties();

        exceptionMappings.put("java.lang.Exception", "error/error");
        exceptionMappings.put("java.lang.RuntimeException", "error/error");

        exceptionResolver.setExceptionMappings(exceptionMappings);

        Properties statusCodes = new Properties();

        statusCodes.put("error/404", "404");
        statusCodes.put("error/error", "500");

        exceptionResolver.setStatusCodes(statusCodes);

        return exceptionResolver;
    }

    @Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();

        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix(VIEW_RESOLVER_PREFIX);
        viewResolver.setSuffix(VIEW_RESOLVER_SUFFIX);

        return viewResolver;
    }

}

All of this resides in package wiggle.app.config , going by my configuration /** is protected and should redirect to /login, which is open for all, the security filter chain does work all right, I see Access Denied after which there is redirection to /wiggle/login how ever I get a 404 after that with following log entries when I access the home page ie http://localhost:8080/wiggle/ 所有这些都在wiggle.app.config包中,我的配置/**受保护,应该重定向到/ login,这对所有人开放,安全过滤器链确实可行,我看到Access Denied之后有重定向到/ wiggle / login当我访问主页时,如果我获得404以后的日志条目,即http://localhost:8080/wiggle/

Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken@6faeba70: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@fffbcba8: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 8A7C29831E56336A6FDF1A0E19200E70; Granted Authorities: ROLE_ANONYMOUS 
Voter: org.springframework.security.web.access.expression.WebExpressionVoter@c01ac1b, returned: 1 
Authorization successful 
RunAsManager did not change Authentication object 
/login reached end of additional filter chain; proceeding with original chain 
DispatcherServlet with name 'dispatcher' processing GET request for [/wiggle/login] 
Looking up handler method for path /login 
Did not find handler method for [/login] 
Matching patterns for request [/login] are [/**] 
URI Template variables for request [/login] are {} 
Mapping [/login] to HandlerExecutionChain with handler [org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler@688a42b5] and 1 interceptor 
Last-Modified value for [/wiggle/login] is: -1 
SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession. 
Null ModelAndView returned to DispatcherServlet with name 'dispatcher': assuming HandlerAdapter completed request handling 
Successfully completed request 
Chain processed normally 
SecurityContextHolder now cleared, as request processing completed 

I would usually put the following in an XML to take care of mappings 我通常会将以下内容放在XML中来处理映射

<beans:bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<!-- Enables annotated POJO @Controllers -->
<beans:bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">

and

 <!-- Scans within the base package of the application for @Components to configure as beans -->
 <context:component-scan base-package="com.code.controller" />

I am not able to find out what am I doing missing to enable similar behaviour with Java Configuration. 我无法找到我缺少的东西,以启用Java配置的类似行为。

Turns out I missed an important piece of documentation wrt this configuration, section 16.16.8 mvc:default-servlet-handler from the Spring Framework Docs 原来我错过了这个配置的重要文档, 16.16.8 mvc: Spring Framework Docs中的 default-servlet-handler

The caveat to overriding the "/" Servlet mapping is that the RequestDispatcher for the default Servlet must be retrieved by name rather than by path. 覆盖“/”Servlet映射的警告是,必须通过名称而不是路径来检索默认Servlet的RequestDispatcher。 The DefaultServletHttpRequestHandler will attempt to auto-detect the default Servlet for the container at startup time, using a list of known names for most of the major Servlet containers (including Tomcat, Jetty, GlassFish, JBoss, Resin, WebLogic, and WebSphere). DefaultServletHttpRequestHandler将尝试使用大多数主要Servlet容器(包括Tomcat,Jetty,GlassFish,JBoss,Resin,WebLogic和WebSphere)的已知名称列表,在启动时自动检测容器的默认Servlet。 If the default Servlet has been custom configured with a different name, or if a different Servlet container is being used where the default Servlet name is unknown, then the default Servlet's name must be explicitly provided as in the following example: 如果使用不同的名称自定义配置了默认Servlet,或者在默认Servlet名称未知的情况下使用了不同的Servlet容器,则必须显式提供默认的Servlet名称,如下例所示:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable("myCustomDefaultServlet");
   }

} }

hence I changed to this 因此我改变了这一点

@Override
public void configureDefaultServletHandling(
        DefaultServletHandlerConfigurer configurer) {
    configurer.enable("wiggleServlet");
}

There was another piece of misconfiguration 还有另一个错误配置

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "wiggle.app.controllers.*" })
public class WiggleWebAppConfig extends WebMvcConfigurerAdapter {

should be 应该

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "wiggle.app.controllers" })
public class WiggleWebAppConfig extends WebMvcConfigurerAdapter {

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 一个 Web 应用程序中的 Spring MVC 和 Spring WS 调度程序 servlet 配置 - Spring MVC and Spring WS dispatcher servlet configuration in one web application java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet spring mvc配置错误 - java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet Error in spring mvc configuration 将default-servlet-handler放在Spring MVC配置中的位置 - Where to put default-servlet-handler in Spring MVC configuration Spring MVC default-servlet-handler配置阻止JSTL视图 - Spring MVC default-servlet-handler configuration blocking JSTL view 基于Spring MVC Java的配置-未检测到servlet调度程序 - Spring MVC Java based configuration - Not detecting servlet dispatcher Spring MVC-配置:找不到元素[default-servlet-handler]的BeanDefinitionParser - Spring MVC - Configuration : Cannot locate BeanDefinitionParser for element [default-servlet-handler] 基于Spring注释的配置中的mvc:default-servlet-handler的等价物? - Equivalent of mvc:default-servlet-handler in Spring annotation-based configuration? 的意义是什么 <property> Web MVC的[servlet-name] -servlet.xml中添加标签? - What is the meaning of <property> tag in [servlet-name]-servlet.xml of Spring Web MVC? Spring MVC不含XML的配置异常:配置默认Servlet处理需要ServletContext - Spring MVC XML-less configuration exception : A ServletContext is required to configure default servlet handling Spring MVC:如何启动默认 servlet - Spring MVC : how to launch default servlet
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM