2015-08-13 35 views
-1

我正在創建一個基本的Spring MVC +存儲庫+安全配置。 我使用THIS GUIDE並獲得了我在下面報告的配置。 根據該配置,我希望有一些歡迎頁面出現在localhost:8080/HPLAN/welcome;輸入localhost:8080/HPLAN/後,我也被重定向到該URL,但我總是得到一個404錯誤。服務器日誌不會收到任何請求(服務器日誌不會顯示任何「無請求映射」)。在部署位置存在「HPLAN」文件夾。 我還需要提到的是數據庫表不會被創建。Spring的Java配置:正確部署但404錯誤

所以,我的配置是這樣的:

  1. 安全

    @Configuration 
    @EnableWebSecurity 
    public class SecurityConfig extends WebSecurityConfigurerAdapter { 
    @SuppressWarnings("unused") 
    @Autowired 
    private DataSource dataSource; 
    
    @Autowired 
    private CustomUserDetailsService customUserDetailsService; 
    
    @Override 
    protected void configure(AuthenticationManagerBuilder registry) throws Exception { 
        registry.userDetailsService(customUserDetailsService); 
    } 
    
    @Override 
    public void configure(WebSecurity web) throws Exception { 
        web.ignoring().antMatchers("/resources/**"); // #3 
    } 
    
    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
        http.csrf().disable().authorizeRequests().antMatchers("/login", "/login/form**", "/register", "/logout") 
          .permitAll() // #4 
          .antMatchers("/admin", "/admin/**").hasRole("ADMIN") // #6 
          .anyRequest().authenticated() // 7 
          .and().formLogin() // #8 
          .loginPage("/login/form") // #9 
          .loginProcessingUrl("/login").failureUrl("/login/form?error").permitAll(); // #5 
    } 
    

    }

  2. 持久

    @Configuration 
    @EnableTransactionManagement 
    @EnableJpaRepositories(basePackages = "com.tek4b.hplan.repositories") 
    public class PersistenceConfig { 
    
    @Autowired 
    private Environment env; 
    
    @Value("${init-db:false}") 
    private String initDatabase; 
    
    @Bean 
    public PlatformTransactionManager transactionManager() { 
        EntityManagerFactory factory = entityManagerFactory().getObject(); 
        return new JpaTransactionManager(factory); 
    } 
    
    @Bean 
    public LocalContainerEntityManagerFactoryBean entityManagerFactory() { 
        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); 
    
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); 
        vendorAdapter.setGenerateDdl(Boolean.TRUE); 
        vendorAdapter.setShowSql(Boolean.TRUE); 
    
        factory.setDataSource(dataSource()); 
        factory.setJpaVendorAdapter(vendorAdapter); 
        factory.setPackagesToScan("com.tek4b.hplan.entities"); 
    
        Properties jpaProperties = new Properties(); 
        jpaProperties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); 
        factory.setJpaProperties(jpaProperties); 
    
        factory.afterPropertiesSet(); 
        factory.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver()); 
        return factory; 
    } 
    
    @Bean 
    public HibernateExceptionTranslator hibernateExceptionTranslator() { 
        return new HibernateExceptionTranslator(); 
    } 
    
    @Bean 
    public DataSource dataSource() { 
        BasicDataSource dataSource = new BasicDataSource(); 
        dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName")); 
        dataSource.setUrl(env.getProperty("jdbc.url")); 
        dataSource.setUsername(env.getProperty("jdbc.username")); 
        dataSource.setPassword(env.getProperty("jdbc.password")); 
        return dataSource; 
    } 
    
    @Bean 
    public DataSourceInitializer dataSourceInitializer(DataSource dataSource) { 
        DataSourceInitializer dataSourceInitializer = new DataSourceInitializer(); 
        dataSourceInitializer.setDataSource(dataSource); 
        ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator(); 
        databasePopulator.addScript(new ClassPathResource("db.sql")); 
        dataSourceInitializer.setDatabasePopulator(databasePopulator); 
        dataSourceInitializer.setEnabled(Boolean.parseBoolean(initDatabase)); 
        return dataSourceInitializer; 
    } 
    

    }

  3. 的AppConfig

    @Configuration 
    @ComponentScan(basePackages = { 
        "com.tek4b.hplan" }, excludeFilters = @ComponentScan.Filter(type = FilterType.REGEX, pattern = { 
          "com.tek4b.hplan.web.*" })) 
    @PropertySource(value = { "classpath:application.properties" }) 
    @EnableScheduling 
    @EnableAspectJAutoProxy 
    @EnableCaching 
    public class AppConfig { 
    
    @Autowired 
    private Environment env; 
    
    @Bean 
    public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() { 
        return new PropertySourcesPlaceholderConfigurer(); 
    } 
    
    @Bean 
    public CacheManager cacheManager() { 
        return new ConcurrentMapCacheManager(); 
    } 
    

    }

  4. MVC:

    @Configuration 
    @ComponentScan(basePackages = { "com.tek4b.hplan.web" }) 
    @EnableWebMvc 
    public class WebMvcConfig extends WebMvcConfigurerAdapter { 
    
    @Override 
    public void addViewControllers(ViewControllerRegistry registry) { 
        super.addViewControllers(registry); 
        registry.addViewController("login/form").setViewName("login"); 
        registry.addViewController("welcome").setViewName("welcome"); 
        registry.addViewController("admin").setViewName("admin"); 
    } 
    
    @Bean 
    public ViewResolver resolver() { 
        InternalResourceViewResolver url = new InternalResourceViewResolver(); 
        url.setPrefix("/WEB-INF/jsp/"); 
        url.setSuffix(".jsp"); 
        return url; 
    } 
    
    @Override 
    public void addResourceHandlers(ResourceHandlerRegistry registry) { 
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); 
    } 
    
    @Override 
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { 
        configurer.enable(); 
    } 
    
    @Bean(name = "messageSource") 
    public MessageSource configureMessageSource() { 
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); 
        messageSource.setBasename("classpath:messages"); 
        messageSource.setCacheSeconds(5); 
        messageSource.setDefaultEncoding("UTF-8"); 
        return messageSource; 
    } 
    
    @Bean 
    public SimpleMappingExceptionResolver simpleMappingExceptionResolver() { 
        SimpleMappingExceptionResolver b = new SimpleMappingExceptionResolver(); 
        Properties mappings = new Properties(); 
        mappings.put("org.springframework.dao.DataAccessException", "error"); 
        b.setExceptionMappings(mappings); 
        return b; 
    } 
    

    }

  5. Web.xml中

    <?xml version="1.0" encoding="UTF-8"?> 
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
    version="3.0"> 
    <display-name>HPLAN</display-name> 
    

我的項目結構:

enter image description here

我創建的數據庫和服務器似乎正常啓動:

Aug 13, 2015 7:26:11 PM org.apache.catalina.core.AprLifecycleListener init 
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: <hidden by me>;. 
Aug 13, 2015 7:26:11 PM org.apache.tomcat.util.digester.SetPropertiesRule begin 
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:HPLAN' did not find a matching property. 
Aug 13, 2015 7:26:11 PM org.apache.coyote.AbstractProtocol init 
INFO: Initializing ProtocolHandler ["http-bio-8080"] 
Aug 13, 2015 7:26:11 PM org.apache.coyote.AbstractProtocol init 
INFO: Initializing ProtocolHandler ["ajp-bio-8009"] 
Aug 13, 2015 7:26:11 PM org.apache.catalina.startup.Catalina load 
INFO: Initialization processed in 694 ms 
Aug 13, 2015 7:26:11 PM org.apache.catalina.core.StandardService startInternal 
INFO: Starting service Catalina 
Aug 13, 2015 7:26:11 PM org.apache.catalina.core.StandardEngine startInternal 
INFO: Starting Servlet Engine: Apache Tomcat/7.0.47 
Aug 13, 2015 7:26:12 PM org.apache.catalina.util.SessionIdGenerator createSecureRandom 
INFO: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [281] milliseconds. 
Aug 13, 2015 7:26:14 PM org.apache.catalina.core.ApplicationContext log 
INFO: No Spring WebApplicationInitializer types detected on classpath 
Aug 13, 2015 7:26:14 PM org.apache.coyote.AbstractProtocol start 
INFO: Starting ProtocolHandler ["http-bio-8080"] 
Aug 13, 2015 7:26:14 PM org.apache.coyote.AbstractProtocol start 
INFO: Starting ProtocolHandler ["ajp-bio-8009"] 
Aug 13, 2015 7:26:14 PM org.apache.catalina.startup.Catalina start 
INFO: Server startup in 2767 ms 

然後不顧我的請求的代表一樣, 。 它有什麼問題?

============ UPDATE 6 AppInitializer類:

public class SpringWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { 

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

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

    @Override 
    protected String[] getServletMappings() { 

     return new String[] { "/" }; 
    } 

    @Override 
    protected Filter[] getServletFilters() { 
     return new Filter[] { new DelegatingFilterProxy("springSecurityFilterChain"), 
       new OpenEntityManagerInViewFilter() }; 
    } 

} 
+0

難道ü檢查您的應用程序部署或不? –

+0

@SubodhJoshi它實際上以其正確名稱(HPLAN)部署在tomcat部署文件夾中。我更新了我的OT。 – Manu

+0

正如你所提到的,你使用Tomcat進行部署,所以它必須顯示你部署了哪個戰爭?有時我也面臨在eclipse + Tomcat或Eclipse + Jboss服務器啓動,但項目nt部署 –

回答

-1

您的項目不具備 「動態理論Web項目」 小面。

右鍵單擊該項目,然後選擇「屬性」。然後點擊「Project Facet」。選擇「動態Web項目」並繼續下一步。

UPDATE 如果沒問題,請檢查Project Properties選項卡中的「Deployment Assembly」。源文件夾應該具有「WEB-INF/classes」的目標,其他這些與部署有關。

如果這樣也行,那麼您需要轉到「服務器」視圖,並從那裏刪除服務器。重新啓動Eclipse。然後添加一個新的服務器。

+0

它實際上,模塊v3.0。 – Manu

+1

如果它不會通過web項目,然後右鍵點擊項目不應該顯示'在服務器上運行' –

+1

添加了更新。我認爲這應該解決這個問題。我不認爲這是春天相關的。這一切關於Eclipse和WTP的東西。 – Mecon