Spring rest MultiPart file upload with Java configuration without Spring boot - java

I am trying to implement a rest web service that uses MultipartFile to upload a file using Spring, with java configuration. I do not use Spring Boot and I have commons-fileupload library in my classpath.
I read Spring documentation that says:
you need to mark the DispatcherServlet with a "multipart-config" section in web.xml, or with a javax.servlet.MultipartConfigElement in programmatic Servlet registration, or in case of a custom Servlet class possibly with a javax.servlet.annotation.MultipartConfig annotation on your Servlet class ... Once Servlet 3.0 multipart parsing has been enabled in one of the above mentioned ways you can add the StandardServletMultipartResolver to your Spring configuration
Hence I added this bean to my AppConfig class:
#Bean
public StandardServletMultipartResolver multipartResolver() {
return new StandardServletMultipartResolver();
}
and annotated the class with MultipartConfig:
#EnableWebMvc
#MultipartConfig(maxFileSize = 5120)
public class AppConfig extends WebMvcConfigurerAdapter{
...
}
but I get this exception when I call the service:
Caused by: org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is java.lang.UnsupportedOperationException: SRVE8020E: Servlet does not accept multipart request
at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.parseRequest(StandardMultipartHttpServletRequest.java:111)
at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.<init>(StandardMultipartHttpServletRequest.java:85)
at org.springframework.web.multipart.support.StandardServletMultipartResolver.resolveMultipart(StandardServletMultipartResolver.java:76)
at org.springframework.web.multipart.support.MultipartFilter.doFilterInternal(MultipartFilter.java:112)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:207)
at [internal classes]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at com.ibm.ws.webcontainer.filter.FilterInstanceWrapper.doFilter(FilterInstanceWrapper.java:207)
... 1 more
Caused by: java.lang.UnsupportedOperationException: SRVE8020E: Servlet does not accept multipart request
at com.ibm.ws.webcontainer.srt.SRTServletRequest.prepareMultipart(SRTServletRequest.java:3657)
at [internal classes]
at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest.parseRequest(StandardMultipartHttpServletRequest.java:92)
If I use CommonsMultipartResolver instead of StandardServletMultipartResolver I get the same error.
This is how I initialize my application:
public class AppInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(AppConfig.class);
context.setServletContext(servletContext);
servletContext.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcherServlet", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);
EnumSet<DispatcherType> dispatcherTypes = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD);
FilterRegistration.Dynamic characterEncoding = servletContext.addFilter("CharacterEncodingFilter", characterEncodingFilter);
characterEncoding.addMappingForUrlPatterns(dispatcherTypes, true, "/*");
}
}
I also tried add a MultipartFilter but with no luck.
MultipartFilter multipartFilter = new MultipartFilter();
FilterRegistration.Dynamic multipart = servletContext.addFilter("multipartFilter", multipartFilter);
multipart.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
Is this necessary? What am I doing wrong? I think I read the whole internet searching for a solution but they all use spring boot with MultipartConfigElement and MultipartConfigFactory. Maybe the problem is the way I consume the service?
This is my controller method:
#RequestMapping(value = "/upload", method = RequestMethod.POST, consumes = "multipart/form-data" )
public Long uploadAttachment(#RequestParam("cn") String callerName, #RequestParam("cs") String callerService, #RequestParam("file") MultipartFile file)
and this is how i consume it:
File file = new File("C:\\Users\\cte0289\\Documents\\Email\\document.docx");
RestTemplate rest = new RestTemplate();
LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
map.add("cn", callerName);
map.add("cs", callerService);
map.add("file", file);
Long response = rest.postForObject(url + "/upload", map, Long.class);
Please help I don't know what else to do.

I think you might want to try something like this:
public class AppInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(AppConfig.class);
context.setServletContext(servletContext);
servletContext.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcherServlet", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
dispatcher.setMultipartConfig(getMultipartConfigElement());
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);
EnumSet<DispatcherType> dispatcherTypes = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD);
FilterRegistration.Dynamic characterEncoding = servletContext.addFilter("CharacterEncodingFilter", characterEncodingFilter);
characterEncoding.addMappingForUrlPatterns(dispatcherTypes, true, "/*");
}
private MultipartConfigElement getMultipartConfigElement(){
MultipartConfigElement multipartConfigElement = new MultipartConfigElement("C:/tmp", 1024*1024*5, 1024*1024*5*5, 1024*1024);
return multipartConfigElement;
}
}

The correct way to configure Spring project to handle file upload with java configuration is this:
If you want to configure it with Commons FileUpload library you have only to include this bean in your Configuration class and add the jar in your classpath
#Bean
public CommonsMultipartResolver multipartResolver(){
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setMaxUploadSize(5242880); // set the size limit
return resolver;
}
if you want to configure the project with Servlet 3.0, as #AlieneilA said you have to set the MultipartConfig element in dispatcher servlet:
dispatcher.setMultipartConfig(new MultipartConfigElement("C:/tmp", 1024*1024*5, 1024*1024*5*5, 1024*1024));
and include this bean in configuration class (AppConfig in my case):
#Bean
public StandardServletMultipartResolver multipartResolver() {
return new StandardServletMultipartResolver();
}
I was wrong in the way i inserted the file into the LinkedMultiValueMap. I had to use a FileSystemResource:
File file = new File("C:\\document.doc");
RestTemplate rest = new RestTemplate();
LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
map.add("param1", param1);
map.add("param2", param2);
map.add("file", new FileSystemResource(file));
Long response = rest.postForObject(url, map, Long.class);
or a MockMultipartFile as suggested by this answer: https://stackoverflow.com/a/38270420/6503002
In this case include spring mock as dependency:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-mock</artifactId>
<version>2.0.8</version>
</dependency>

In case anyone is extending AbstractAnnotationConfigDispatcherServletInitializer class for web application initialization configuration, below simple configuration will enable MultiPart Feature -
import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletRegistration.Dynamic;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class WebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { AppConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
#Override
protected void customizeRegistration(Dynamic registration) {
MultipartConfigElement multiPart = new MultipartConfigElement("C:/temp/",
1024 * 1024 * 5, 1024 * 1024 * 10, 1024 * 1024 * 3);
registration.setMultipartConfig(multiPart);
}
}

Related

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
}

Problems with controller mapping in Spring MVC

There are similar topics, but they all use xml configuration files. The reason why I'm writing this question is that I'm using annotations.
I experience problems running my app:
getting “WARN org.springframework.web.servlet.PageNotFound - No
mapping found for HTTP request with URI …” when trying to setup
Spring servlet
getting error 404 when trying to run it on server
Here is my code (package and imports are skipped):
1) initializer
public class WebInitializer implements WebApplicationInitializer{
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx =
new AnnotationConfigWebApplicationContext();
ctx.register(AppConfig.class);
ctx.setServletContext(servletContext);
ServletRegistration.Dynamic servlet =
servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
}
2) app config
#Configuration
#ComponentScan("ua.kiev.prog")
#EnableWebMvc
public class AppConfig {
#Bean
public EntityManager entityManager() {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("AdvJPA");
return emf.createEntityManager();
}
#Bean
public AdvDAO advDAO() {
return new AdvDAOImpl();
}
#Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
resolver.setOrder(1);
return resolver;
}
#Bean
public CommonsMultipartResolver multipartResolver() {
return new CommonsMultipartResolver();
}
}
3) controller
#Controller
#RequestMapping("/Advertisement")
public class MainController {
#Autowired
private AdvDAO advDAO;
#RequestMapping("/")
public ModelAndView listAdvs() {
return new ModelAndView("index", "advs", advDAO.list());
}
#RequestMapping(value = "/add_page", method = RequestMethod.POST)
public String addPage(Model model) {
return "add_page";
}
#RequestMapping(value = "/search", method = RequestMethod.POST)
public ModelAndView search(#RequestParam(value="pattern") String pattern) {
return new ModelAndView("index", "advs", advDAO.list(pattern));
}
// more code goes here
}
The controller is mapped to /Advertisement, so app should be available at URL localhost:8080/Advertisement/ but it isn't. When I change mapping in annotation to "/" - it becomes available at localhost:8080/Advertisement/. How can it be?
And when I change it back to "/Advertisement" - the same probleb accurs (error 404 and exception "No mapping found for HTTP request with URI …")
So, where I've made a mistake in my code?
Or maybe the problem is in Eclipse/TomCat/Maven?
Source - https://github.com/KostyantynPanchenko/prog.kiev.ua.lesson09.adv
You should change mapping
#Controller
#RequestMapping("/")
public class MainController {
#Autowired
private AdvDAO advDAO;
#RequestMapping("/Advertisement")
public ModelAndView listAdvs() {
return new ModelAndView("index", "advs", advDAO.list());
}
The mistake that a mapper used the value from the annotation to match the request URL, and it can't match the last slash. Note, it should not happen in the above code.
How are you running the application? Atleast in tomcat each deployed application is served from specific context path. Context path is determined from the base file name, more on that here.
So if you're deploying Advertisement.war all requests to the app will be served from localhost:8080/Advertisement/ even though you're declaring the DispatcherServlet and Controller to /

How to specify url-pattern for Servlet filters in WebApplicationInitializer?

I am converting a web.xml file to Java based configuration using Spring-web's WebApplicationInitializer. Following is the sample filter defined
<filter>
<filter-name>sampleFilter</filter-name>
<filter-class>com.SampleFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>sampleFilter</filter-name>
<url-pattern>/sampleUrl</url-pattern>
</filter-mapping>
and now the WebApplicationInitializer class looks like this
class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
#Override
protected Filter[] getServletFilters() {
return new Filter[]{new SampleFilter()};
}
//other methods
}
But as you can see, the Filter is applied to all the resources, whereas I want to map the Filter just for /sampleUrl. How do we do that?
Below a full example i used in one of my project :
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
//add MVC dispatcher servlet and map it to /
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
dispatcher.setAsyncSupported(true);
//add spring characterEncoding filter
//to always have encoding on all requests
EnumSet<DispatcherType> dispatcherTypes = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ERROR);
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);
FilterRegistration.Dynamic characterEncoding = servletContext.addFilter("characterEncoding", characterEncodingFilter);
characterEncoding.addMappingForUrlPatterns(dispatcherTypes, true, "/*");
characterEncoding.setAsyncSupported(true);
// specifies that the parser produced by this factory will
// validate documents as they are parsed.
SAXParserFactory.newInstance().setValidating(false);
// add spring contextloader listener
servletContext.addListener(new ContextLoaderListener(rootContext));
}

java spring URL mapping

I using maven web application, framework spring.
Using Netbeans IDE and Tomcat server.
When I run web in netbeans, URL in browser is:
http://localhost:8080/mywebsite
With this URL website cannot read event servlet mapping.
When I change URL to http://localhost:8080/mywebsite/ then It run good.
What is reason for this case? Why my website don't auto add character "/" in URL?
{update}
config.java
public class Config extends WebMvcConfigurerAdapter {
#Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/html/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/*");
}
}
Initializer
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(Config.class);
ctx.setServletContext(servletContext);
ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
controller
#Controller
public class MyController {
//<editor-fold defaultstate="collapsed" desc="ADMIN">
#RequestMapping(value = "/", method = RequestMethod.GET)
public String login(ModelMap map) {
return "admin/login";
}}
If you open http://localhost:8080/mywebsite, the web app will try to find some index.html file(based on tomcat or http server configuration).
And you mapping is #RequestMapping(value = "/", method = RequestMethod.GET), so it will apply to http://localhost:8080/mywebsite/. If you want to use your controller to handle http://localhost:8080/mywebsite, you can try to use * in your mapping value. It means, for any request, if there is no specific mapping defined, and that default mapping will be applied.

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