Getting 404 status spring 4 mvc with tomcat - java

I am doing little project using Spring+Hibernate. When I deploy my war and get 404 status all the time. I have checked some answers about it, but I didnt find my mistake. I tried to switch between / and /*, it didnt help. Tomcat doesnt show any errors in logs. Thanks in advance.
My WebConfig class
#Configuration
#EnableWebMvc
#ComponentScan({"controller", "dao"})
#EnableTransactionManagement
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public DataSource dataSource() {
SimpleDriverDataSource ds =
new SimpleDriverDataSource(org.h2.Driver.load(), "jdbc:h2:~/testdb", "sa", "sa");
return ds;
}
#Bean
#DependsOn("dataSource")
public LocalSessionFactoryBean sessionFactoryBean() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan("entity");
sessionFactoryBean.setHibernateProperties(hibernateProperties());
return sessionFactoryBean;
}
private Properties hibernateProperties() {
Properties p = new Properties();
p.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
p.setProperty("hibernate.hbm2ddl.auto", "update");
p.setProperty("hibernate.hbm2ddl.import_files_sql_extractor", "org.hibernate.tool.hbm2ddl.MultipleLinesSqlCommandExtractor");
p.setProperty("hibernate.show_sql", "true");
p.setProperty("hibernate.format_sql", "true");
return p;
}
#Bean
#DependsOn("sessionFactoryBean")
public PlatformTransactionManager transactionManager() {
SessionFactory sessionFactory = sessionFactoryBean().getObject();
HibernateTransactionManager tm = new HibernateTransactionManager(sessionFactory);
return tm;
}
#Bean(name = "viewResolver")
public InternalResourceViewResolver getViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/pages/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
My WebAppInitializer class
public class SpringWebAppInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.register(WebConfig.class);
ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
"SpringDispatcher", new DispatcherServlet(appContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");
}
}
My Controller class
#Controller
public class MainController {
#Autowired
IDisksDao d;
#RequestMapping("/")
#Transactional
#ResponseBody
public String hello() {
return "hi";
}
#RequestMapping("disks/")
#Transactional
#ResponseBody
public ModelAndView getDisks() {
ModelAndView model = new ModelAndView("disks");
model.addObject("disks", d.getAllDisks() );
return model;
}
#RequestMapping("u/disks/{id}")
#Transactional
#ResponseBody
public List<Disk> getUserDisks(#PathVariable int id) {
return d.getAllUserDisks(id);
}
}
My project structure

Related

Spring web application giving 404 error tomcat

I wanted to make REST Api using Spring.
I have added Tomcat in Run/Debug Configurations.
Here is my Config class
#Configuration
#ComponentScan("com.dashkindima.blog.mvc")
#EnableWebMvc
#EnableTransactionManagement
public class MyConfig {
#Bean
public DataSource dataSource() {
ComboPooledDataSource dataSource = new ComboPooledDataSource();
try {
dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/reeve?autoReconnect=true&allowMultiQueries=true&useSSL=false&useUnicode=true&amp&characterEncoding=UTF8");
dataSource.setUser("root");
dataSource.setPassword("1234");
} catch (PropertyVetoException e) {
e.printStackTrace();
}
return dataSource;
}
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan("com.dashkindima.blog.mvc.hibernatetest.entity");
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
hibernateProperties.setProperty("hibernate.show_sql", "true");
sessionFactory.setHibernateProperties(hibernateProperties);
return sessionFactory;
}
#Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
}
I have also defined WebInitializer class
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{MyConfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[]{"/*"};
}
}
I have tried almost all urls in #RequestMapping like /api , /{app_name}/api but nothing happens.
#RestController
#RequestMapping("/blog/api")
public class MyRESTController {
#Autowired
private LivingComplexService livingComplexService;
#GetMapping("/living")
public List<LivingComplex> showAllLivingComplexes(){
List<LivingComplex> allComplexes = livingComplexService.getAllComplexes();
return allComplexes;
}
}
You can be sure that Service will return livingComplexes. So the problem is in Tomcat.

Why are WebMvcConfigurer override methods not working?

I created a project with Spring Boot. I am configuring the basic config, but there is a problem in implementing WebMvcConfigurer.
addInterceptors works well, but addViewControllers and addResourceHandlers don't work. There are no errors, but these two methods don't apply.
I think I set it all right, but I can not find the cause. Can I see why?
[Project Structure]
java
--me
----eastglow
------sample
--------controller
----------SampleController.java
------config
--------RootContextConfig.java
--------Application.java
--------DispatcherServletConfig.java
[RootContextConfig.java]
#Configuration
#ComponentScan(
basePackages = {"me.eastglow.*"},
excludeFilters = {#Filter(Controller.class)}
)
public class RootContextConfig {
}
[Application.java]
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
#Override
public void onStartup(ServletContext container) throws ServletException {
// Create the 'root' Spring application context
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(RootContextConfig.class);
// Manage the lifecycle of the root application context
container.addListener(new ContextLoaderListener(rootContext));
// Create the dispatcher servlet's Spring application context
AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext();
dispatcherServlet.register(DispatcherServletConfig.class);
// Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher = container.addServlet("appServlet", new DispatcherServlet(dispatcherServlet));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("*.json");
dispatcher.addMapping("*.do");
}
}
[DispatcherServletConfig.java]
#Configuration
#ComponentScan(
basePackages={"me.eastglow.*"},
useDefaultFilters = false,
includeFilters={#Filter(Controller.class)},
excludeFilters={#Filter(Service.class), #Filter(Repository.class)}
)
#EnableWebMvc
#PropertySource(
value={"classpath:application-${spring.profiles.active}.properties", "classpath:log4jdbc.log4j2.properties"},
ignoreResourceNotFound = true)
public class DispatcherServletConfig implements WebMvcConfigurer {
private final static String[] RESOURCE_HANDLER_PATH = {"/favicon.ico"
, "/image/**"
, "/js/**"};
private final static String[] RESOURCE_HANDLER_LOCATION = {"/resources/favicon.ico"
, "/resources/image/"
, "/resources/js/"};
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
CacheControl cacheControl = CacheControl.empty().cachePrivate();
registry.addResourceHandler(RESOURCE_HANDLER_PATH).addResourceLocations(RESOURCE_HANDLER_LOCATION).setCacheControl(cacheControl);
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("redirect:/member/login.do");
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new BusinessInterceptor()).addPathPatterns("/**");
}
#Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
List<ViewResolver> resolvers = new ArrayList<>();
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
internalResourceViewResolver.setViewClass(JstlView.class);
internalResourceViewResolver.setPrefix("/WEB-INF/views/");
internalResourceViewResolver.setSuffix(".jsp");
resolvers.add(internalResourceViewResolver);
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setViewResolvers(resolvers);
resolver.setContentNegotiationManager(manager);
return resolver;
}
}
[Updated]
public class DispatcherServletConfig implements WebMvcConfigurer {
private final static String[] RESOURCE_HANDLER_PATH = {"/favicon.ico"
, "/image/**"
, "/js/**"};
private final static String[] RESOURCE_HANDLER_LOCATION = {"/resources/favicon.ico"
, "/resources/image/"
, "/resources/js/"};
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
CacheControl cacheControl = CacheControl.empty().cachePrivate();
registry.addResourceHandler(RESOURCE_HANDLER_PATH).addResourceLocations(RESOURCE_HANDLER_LOCATION).setCacheControl(cacheControl);
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("redirect:/member/login.do");
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new BusinessInterceptor()).addPathPatterns("/**");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new FormHttpMessageConverter());
converters.add(jacksonMessageConverter()); //Json Message Converter
converters.add(new StringHttpMessageConverter());
converters.add(new ResourceHttpMessageConverter()); // File Transfer Message Converter
}
#Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
List<ViewResolver> resolvers = new ArrayList<>();
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
internalResourceViewResolver.setViewClass(JstlView.class);
internalResourceViewResolver.setPrefix("/WEB-INF/views/");
internalResourceViewResolver.setSuffix(".jsp");
internalResourceViewResolver.setOrder(2);
resolvers.add(internalResourceViewResolver);
JsonViewResolver jsonViewResolver = new JsonViewResolver();
resolvers.add(jsonViewResolver);
resolvers.add(beanNameViewResolver());
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setViewResolvers(resolvers);
resolver.setContentNegotiationManager(manager);
return resolver;
}
#Bean
public TilesConfigurer tilesConfigurer() {
TilesConfigurer configurer = new TilesConfigurer();
configurer.setDefinitions(new String[]{"/WEB-INF/tiles/tiles.xml"});
configurer.setCheckRefresh(true);
return configurer;
}
#Bean
public TilesViewResolver tilesViewResolver() {
TilesViewResolver viewResolver = new TilesViewResolver();
viewResolver.setOrder(1);
return viewResolver;
}
class JsonViewResolver implements ViewResolver {
#Override
public View resolveViewName(String viewName, Locale locale) {
MappingJackson2JsonView view = new MappingJackson2JsonView();
view.setPrettyPrint(true);
view.setContentType("application/json;charset=UTF-8");
view.setDisableCaching(true);
return view;
}
}
#Bean(name="beanNameViewResolver")
public BeanNameViewResolver beanNameViewResolver(){
BeanNameViewResolver beanNameViewResolver = new BeanNameViewResolver();
beanNameViewResolver.setOrder(0);
return beanNameViewResolver;
}
#Bean(name="jacksonMessageConverter")
public MappingJackson2HttpMessageConverter jacksonMessageConverter(){
return new MappingJackson2HttpMessageConverter();
}
#Bean
public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
You are working around Spring Boot instead of using it.
For starters remove the onStartup method of your Application class. Spring Boot takes care of all of that.
Next ditch your RootContextConfig.
2 cleanup your DispatcherServletConfig
#Configuration
#PropertySource(
value={"classpath:log4jdbc.log4j2.properties"},
ignoreResourceNotFound = true)
public class DispatcherServletConfig implements WebMvcConfigurer {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("redirect:/member/login.do");
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new BusinessInterceptor());
}
}
Now in your application.properties (or create one) add the following
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
spring.resources.cache.cache-private=true
The mappings should work by default else place your js and images inside src/main/resources/static or src/main/resources/public.
This is all you need if you properly use Spring Boot (instead of working around it).

Inherit Spring configuration from another WAR

We have a SpringMVC project called "Framework" in Eclipse and a "New project" that must inherit from the "Framework" configuration.
Both Spring projects are not using .xml configuration files.
The "Framework" contains all business classes, datasource configuration and ContextListener default behavior that we don't want to rewrite each time we start a new project.
The "Framework" is loaded as a Maven overlay in the second project.
As you can see below, it is a very basic sample SpringMVC configuration.
Framework
-- main
-- java
-- config
- AppConfig.class (implements WebMvcConfigurer)
- AppInit.class (implements WebApplicationInitializer)
AppConfig.class
#EnableAspectJAutoProxy
#EnableWebMvc
#ComponentScan(basePackages="main.java")
public class AppConfig implements WebMvcConfigurer {
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new ControllerLoggingInterceptor()).addPathPatterns("/*");
}
#Bean
public ViewResolver getViewResolver(){
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/jsp/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
registry.addResourceHandler("/images/**").addResourceLocations("/resources/images");
}
#Bean
public ReloadableResourceBundleMessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasenames("classpath:messages","classpath:/framework/messages");
return messageSource;
}
#Bean
public javax.validation.Validator localValidatorFactoryBean() {
return new LocalValidatorFactoryBean();
}
#Bean
public MultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(838860800);
return multipartResolver;
}
}
AppInit.class
public class AppInit implements WebApplicationInitializer {
#Autowired
MapperInfosDB mapperUserBD;
#Override
public void onStartup(ServletContext container) {
AnnotationConfigWebApplicationContext appContext = new AnnotationConfigWebApplicationContext();
appContext.register(AppConfig.class);
container.addListener(new ContextLoaderListener(appContext));
AnnotationConfigWebApplicationContext dispatcherContext =
new AnnotationConfigWebApplicationContext();
dispatcherContext.register(AppConfig.class);
ServletRegistration.Dynamic dispatcher =
container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
dispatcher.addMapping("/");
FilterRegistration.Dynamic fr = container.addFilter("encodingFilter", new CharacterEncodingFilter());
fr.setInitParameter("encoding", "UTF-8");
fr.setInitParameter("forceEncoding", "true");
fr.addMappingForUrlPatterns(null, false, "/*");
fr = container.addFilter("RequestLoggingFilter", new RequestLoggingFilter());
fr.addMappingForUrlPatterns(null, true, "/*");
}
}
In the second project, I import the "Framework" application context successfully, but yet haven't managed to import the WebApplicationContext as it leads to a NullPointerException.
New project
-- main
-- java
-- config
- ApplicationContextConfiguration.class (extends ContextLoaderListener implements WebMvcConfigurer)
- WebConfiguration.class (implements WebApplicationInitializer)
ApplicationContextConfiguration.class
#Configuration
#EnableWebMvc
#EnableAspectJAutoProxy
public class ApplicationContextConfiguration extends ContextLoaderListener implements WebMvcConfigurer {
#Override
protected ApplicationContext loadParentContext(ServletContext servletContext) {
ApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);
// Do some stuff on applicationContext inherited from Framework
return ac;
}
}
WebConfiguration.class
#Configuration
public class WebConfiguration implements WebApplicationInitializer {
private static final String[] BASE_PACKAGE = { "main.java", "new.project.packages" };
#Override
public void onStartup(ServletContext container) {
AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
dispatcherContext.scan(BASE_PACKAGE);
dispatcherContext.register(AppConfig.class);
dispatcherContext.register(AppInit.class);
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
dispatcher.addMapping("/");
dispatcher.setLoadOnStartup(1);
FilterRegistration.Dynamic fr = container.addFilter("encodingFilter", new CharacterEncodingFilter());
fr.setInitParameter("encoding", "UTF-8");
fr.setInitParameter("forceEncoding", "true");
fr.addMappingForUrlPatterns(null, false, "/*");
fr.addMappingForUrlPatterns(null, true, "/*");
}
}
The StackTrace shows :
Caused by: java.lang.NullPointerException
at main.java.config.AppInit.onStartup(AppInit.java:50)
at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:172)
You will have to import Config classes in your current config:
import org.springframework.context.annotation.*;
#EnableAspectJAutoProxy
#EnableWebMvc
#ComponentScan(basePackages="main.java")
#Import({WebConfiguration.class, ApplicationContextConfiguration.class })
public class AppConfig implements WebMvcConfigurer {
//Your current configuration
}

Spring application can't retrieve data from property source

I'm trying to retrieve data from application.properties file using Environment in my Spring Application but it's not working. I cant get the data bound correctly by Environment. I only can get this working if I use local variables as shown below:
AppConfig.class now!
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories("com.victommasi.eshop.dao")
#PropertySource("classpath:application.properties")
public class AppConfig {
private static final String driverClass = "com.mysql.jdbc.Driver";
private static final String url = "jdbc:mysql://localhost/eshop";
private static final String username = "root";
private static final String password = "root";
private static final String dialect = "org.hibernate.dialect.MySQL5Dialect";
private static final String showSql = "true";
private static final String formatSql = "true";
private static final String hbm2dllAuto = "update";
private static final String packageToScan = "com.victommasi.eshop.model";
#Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driverClass);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", dialect);
properties.put("hibernate.show_sql", showSql);
properties.put("hibernate.format_sql", formatSql);
properties.put("hibernate.hbm2ddl.auto", hbm2dllAuto);
return properties;
}
#Bean
public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPersistenceProvider(new HibernatePersistenceProvider());
entityManagerFactoryBean.setPackagesToScan(packageToScan);
entityManagerFactoryBean.setJpaProperties(hibernateProperties());
return entityManagerFactoryBean;
}
}
AppConfig.class as I want
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories("com.victommasi.eshop.dao")
#PropertySource("classpath:application.properties")
public class AppConfig {
#Autowired
private Environment env;
#Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClass"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.username"));
dataSource.setPassword(env.getProperty("jdbc.password"));
return dataSource;
}
private Properties hibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
properties.put("hibernate.format_sql", env.getProperty("hibernate.format_sql"));
properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
return properties;
}
#Bean
public JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPersistenceProvider(new HibernatePersistenceProvider());
entityManagerFactoryBean.setPackagesToScan(env.getProperty("packages.to.scan"));
entityManagerFactoryBean.setJpaProperties(hibernateProperties());
return entityManagerFactoryBean;
}
Other classes:
WebConfig.class
#EnableWebMvc
#Configuration
#ComponentScan(basePackages = { "com.victommasi.eshop" })
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public InternalResourceViewResolver internalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setContentType("text/html;charset=UTF-8");
resolver.setSuffix(".jsp");
return resolver;
}
#Bean(name = "filterMultipartResolver")
public CommonsMultipartResolver getMultipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(1048576);
multipartResolver.setMaxInMemorySize(1048576);
return multipartResolver;
}
}
WebAppInitializer.class
public class WebAppInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(WebConfig.class, AppConfig.class, SecurityConfig.class);
container.addListener(new ContextLoaderListener(rootContext));
AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext();
dispatcherServlet.register(WebConfig.class);
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherServlet));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
I know it seems to be a very easy, I have also followed this tutorial, but cant get this done.
I didn't go through it all but it seems like you're missing the PropertySourcesPlaceholderConfigurer bean
Since Spring 3.1 introduced the new #PropertySource annotation, as a
convenient mechanism of adding property sources to the environment.
This annotation is to be used in conjunction with Java based
configuration and the #Configuration annotation:
#Configuration
#PropertySource("classpath:application.properties")
public class AppConfig {
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
With that, you can now start injecting a property with the #Value annotation is straightforward:
#Value( "${jdbc.url}" )
private String jdbcUrl;
On the other note, consider/look into spring-boot , you'll get all the above (including all the code you have shared)and much more out for free i.e with zero line of code
After reading a comment I took a look at console and found that data in 'application.properties' file were binded to AppConfig.class by Environment with blank spaces.
Stacktrace:
Caused by: java.sql.SQLException: Access denied for user 'root '#'localhost'
I assume it was the reason the binding wasn't working. My application is now working as I wanted. Thanks.

My Spring Application is running but css, js, and images are not being loaded

I have a problem with my Spring app that i'm deploying at OpenShift. Everything seems to be working except my static resource files (css, js, images). I'm getting the following error:
2015-12-11 12:46:31,302 WARN [org.springframework.web.servlet.PageNotFound] (de
fault task-2) No mapping found for HTTP request with URI [/resource/js/jquery-1.
11.3.min.js] in DispatcherServlet with name 'springDispatcher'
2015-12-11 12:46:31,395 WARN [org.springframework.web.servlet.PageNotFound] (de
fault task-3) No mapping found for HTTP request with URI [/resource/js/example.j
s] in DispatcherServlet with name 'springDispatcher'
2015-12-11 12:46:31,419 WARN [org.springframework.web.servlet.PageNotFound] (de
fault task-4) No mapping found for HTTP request with URI [/resource/css/example.
css] in DispatcherServlet with name 'springDispatcher'
This is my Code:
#Order(1)
public class FrameworkBootstrap implements WebApplicationInitializer
{
private static final Logger log = LogManager.getLogger();
#Override
public void onStartup(ServletContext container) throws ServletException
{
log.info("Executing framework bootstrap.");
AnnotationConfigWebApplicationContext rootContext =
new AnnotationConfigWebApplicationContext();
rootContext.register(RootContextConfiguration.class);
container.addListener(new ContextLoaderListener(rootContext));
AnnotationConfigWebApplicationContext servletContext =
new AnnotationConfigWebApplicationContext();
servletContext.register(ServletContextConfiguration.class);
ServletRegistration.Dynamic dispatcher = container.addServlet(
"springDispatcher", new DispatcherServlet(servletContext)
);
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
FilterRegistration.Dynamic registration = container.addFilter(
"preSecurityLoggingFilter", new PreSecurityLoggingFilter()
);
registration.addMappingForUrlPatterns(null, false, "/*");
}
}
And the config...
#Configuration
#EnableWebMvc
#ComponentScan(
basePackages = "com.example.site",
useDefaultFilters = false,
includeFilters = #ComponentScan.Filter(Controller.class)
)
public class ServletContextConfiguration extends WebMvcConfigurerAdapter {
private static final Logger log = LogManager.getLogger();
#Inject ApplicationContext applicationContext;
#Inject ObjectMapper objectMapper;
#Inject Marshaller marshaller;
#Inject Unmarshaller unmarshaller;
#Inject SpringValidatorAdapter validator;
#Bean
public MultipartResolver multipartResolver() {
return new StandardServletMultipartResolver();
}
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/WEB-INF/jsp/view/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
log.info("Adding Resource Handlers");
registry.addResourceHandler("/resource/**").addResourceLocations("/resource/");
registry.setOrder(Integer.MAX_VALUE);
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void configureMessageConverters(
List<HttpMessageConverter<?>> converters
) {
converters.add(new ByteArrayHttpMessageConverter());
converters.add(new StringHttpMessageConverter());
converters.add(new FormHttpMessageConverter());
converters.add(new SourceHttpMessageConverter<>());
MarshallingHttpMessageConverter xmlConverter
= new MarshallingHttpMessageConverter();
xmlConverter.setSupportedMediaTypes(Arrays.asList(
new MediaType("application", "xml"),
new MediaType("text", "xml")
));
xmlConverter.setMarshaller(this.marshaller);
xmlConverter.setUnmarshaller(this.unmarshaller);
converters.add(xmlConverter);
MappingJackson2HttpMessageConverter jsonConverter
= new MappingJackson2HttpMessageConverter();
jsonConverter.setSupportedMediaTypes(Arrays.asList(
new MediaType("application", "json"),
new MediaType("text", "json")
));
jsonConverter.setObjectMapper(this.objectMapper);
converters.add(jsonConverter);
}
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(true).favorParameter(false)
.parameterName("mediaType").ignoreAcceptHeader(false)
.useJaf(false).defaultContentType(MediaType.APPLICATION_XML)
.mediaType("xml", MediaType.APPLICATION_XML)
.mediaType("json", MediaType.APPLICATION_JSON);
}
#Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers)
{
Sort defaultSort = new Sort(new Sort.Order(Sort.Direction.ASC, "id"));
Pageable defaultPageable = new PageRequest(0, 10, defaultSort);
SortHandlerMethodArgumentResolver sortResolver =
new SortHandlerMethodArgumentResolver();
sortResolver.setSortParameter("paging.sort");
sortResolver.setFallbackSort(defaultSort);
PageableHandlerMethodArgumentResolver pageableResolver =
new PageableHandlerMethodArgumentResolver(sortResolver);
pageableResolver.setMaxPageSize(100);
pageableResolver.setOneIndexedParameters(true);
pageableResolver.setPrefix("paging.");
pageableResolver.setFallbackPageable(defaultPageable);
resolvers.add(sortResolver);
resolvers.add(pageableResolver);
}
#Override
public void addFormatters(FormatterRegistry registry)
{
if(!(registry instanceof FormattingConversionService))
{
log.warn("Unable to register Spring Data JPA converter.");
return;
}
DomainClassConverter<FormattingConversionService> converter =
new DomainClassConverter<>((FormattingConversionService)registry);
converter.setApplicationContext(this.applicationContext);
}
#Override
public Validator getValidator()
{
return this.validator;
}
#Override
public void addInterceptors(InterceptorRegistry registry)
{
super.addInterceptors(registry);
registry.addInterceptor(new LocaleChangeInterceptor());
}
#Bean
public LocaleResolver localeResolver() {
return new SessionLocaleResolver();
}
#Bean
public RequestToViewNameTranslator viewNameTranslator() {
return new DefaultRequestToViewNameTranslator();
}
}
The application is running, i'm just can't reach the files which are on the server in the following path.
src > main > webapp > resource > css > file.css
I can't find out what is wrong... Please Help!

Categories