0

I have controller which handles request to / and returns corresponding jsp. After switching to annotation based configuration and adding Spring security I got HTTP 404 when log in is successful. It seems to me like all config is in place. What's wrong?

AppConfig

@EnableWebMvc
@Configuration
@ComponentScan({"app.controller.*"})
@Import({SecurityConfig.class})
@PreAuthorize("hasRole('ROLE_ADMIN')")
public class AppConfig {

    @Bean
    public InternalResourceViewResolver viewResolver(){
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/pages");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
    public void addResourceHandlers(ResourceHandlerRegistry registry){
        registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/");
    }

SecurityConfig

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
        auth.inMemoryAuthentication().withUser("admin").password("admin").roles("ADMIN");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http.authorizeRequests()
                    .antMatchers("/**").access("hasRole('ROLE_ADMIN')")
                .and().formLogin();
    }
}

SpringMvcInitializer

public class SpringMvcInitializer extends
        AbstractAnnotationConfigDispatcherServletInitializer {

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

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }

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

Controller

@Controller
@RequestMapping("/")
public class AppController {

 @RequestMapping(value = "/", method= RequestMethod.GET)
    public String getRequestPage(Model model){ .....}
}

UPDATE

changing in SpringMvcInitializer to following code didn't help:

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

UPDATE2:

for some reason IntelliJ shows that it cannot autowire bean AuthenticationManager in SecurityConfig class

UPDATE3

I removed any Deployment descriptors in Facets (it still suggests to create web.xml but I think I don't need it since I configure Spring only by code). Right?

J.Olufsen
  • 13,415
  • 44
  • 120
  • 185
  • `setPrefix("/WEB-INF/pages")` ... couldn't this be the problem? Typically the prefix ends with a slash so if you don't return the view name with leading slash from the controller that could be causing the 404 as the view would be resolved to for example `/WEB-INF/pageshome.jsp`. But without knowing what you return from your controller this is just a wild guess :) – Bohuslav Burghardt Nov 17 '14 at 12:59
  • I return name of jsp page without leading slash and jsp suffix. – J.Olufsen Nov 17 '14 at 13:07
  • Then that could be the problem I mentioned in my comment. Try setting your prefix to `/WEB-INF/pages/` (notice the trailing slash). – Bohuslav Burghardt Nov 17 '14 at 13:09
  • I did it with no success. Also I cannot access any resources for example `/resources/css/bootstrap.css` returns `404` – J.Olufsen Nov 17 '14 at 13:12
  • Could you show what was your xml based config ? It could be easier to determine was is not in current java config. – Serge Ballesta Nov 17 '14 at 13:23
  • I switched to code based config. I don't have anymore xml – J.Olufsen Nov 17 '14 at 13:24

1 Answers1

0

I can see that in your SpringMvcInitializer you set dispatcher servlet mapping to /. AFAIK, you cannot map a controller to / with this mapping. Disclaimer : I really do not know why but I gave more details on that in this other post.

IMHO, you should map the servlet to /* if there are not side effects, because I do not know any way to declare a welcome-file-list except with a web.xml. But you can always try to let only the <welcome-file-list> in the web.xml file, all remaining configuration being migrated to annotations and java config. A 3.0+ servlet container should correctly process both.

Edit :

Looked further in your configuration and I found unusual pieces of config :

  • AppConfig seems to configure servlet part (scans controller package and declares resource handling) but it is declared as root application context. IMHO it would be better declared as a dispatcher servlet application context.
  • I never used not saw a PreAuthorize annotation in a configuration file - you should try to remove it
Community
  • 1
  • 1
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • Could you say it the 404 is caused by the controller not being hitted of the view not being found ? (putting spring log at debug level can help to find that) – Serge Ballesta Nov 17 '14 at 13:33
  • I put `log4j.logger.org.springframework=DEBUG` to `log4j.properties` but logger is not working although I have included all dependencies to `pom.xml`. How to make it work? – J.Olufsen Nov 17 '14 at 13:44
  • @RCola I'm afraid that having logging in a spring MVC application is a different question ... and anyway I really cannot guess what happens (too many poosibilities :-( ) – Serge Ballesta Nov 17 '14 at 14:00
  • `log4j: DocumentBuilderFactory is: com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl log4j: debug attribute= "null". log4j: Ignoring debug attribute. log4j: reset attribute= "false". log4j: Threshold ="null". log4j: Level value for root is [debug]. log4j: root level set to DEBUG log4j: Class name: [com.pyx4j.log4j.MavenLogAppender] log4j: Parsing layout of class: "org.apache.log4j.PatternLayout" log4j: Setting property [conversionPattern] to [%m]. log4j: Adding appender named [MavenLogAppender] to category [root].` – J.Olufsen Nov 17 '14 at 14:12