How to import javascript resource into thymeleaf template without Spring? - java

I use thymeleaf WITHOUT Spring. Configuration looks
#WebListener
public class ThymeleafConfig implements ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
TemplateEngine engine = templateEngine(sce.getServletContext());
TemplateEngineUtil.storeTemplateEngine(sce.getServletContext(), engine);
}
private TemplateEngine templateEngine(ServletContext servletContext) {
TemplateEngine engine = new TemplateEngine();
engine.setTemplateResolver(templateResolver(servletContext));
return engine;
}
private ITemplateResolver templateResolver(ServletContext servletContext) {
ServletContextTemplateResolver resolver = new ServletContextTemplateResolver(servletContext);
resolver.setPrefix("/WEB-INF/templates/");
resolver.setTemplateMode(TemplateMode.HTML);
return resolver;
}
where I specify path /src/main/webapp/WEB-INF/templates as prefix /WEB-INF/templates/ for my index.html template. It works. Now I am trying to add javascrpt static resource that is located at /src/main/webapp/WEB-INF/js, so that I can import it in template, like
<script src="example.js" type="text/javascript"></script>
OR
<script th:src="#{/example.js}" type="text/javascript"></script>
How can I add javascript resource? All documentation and examples I have found are for the combination Spring+thymeleaf.
EDIT:
The project was configured incorrectly, maven plugin maven-resources-plugin was missing. Thus resources were not recognized.

Related

How to add static files using Spring MVC and Thymeleaf

My question is how to add static files like CSS and image files so that I can use them. I am using Spring MVC and Thymeleaf. I looked at various posts on this subject, but they did't help me, so I am asking. As per those posts, I put my CSS and image file in the resources/static/css and resources/static/images directory.
Under templates (under webapp/WEB-INF/templates) is where all my HTML files are stored, the ones who want to use the CSS and image files.
I have the following LoginApplicationConfig file. The very two bottom methods I included so that my HTML files could use the styles and image files:
#EnableWebMvc
#Configuration
#ComponentScan({ "com.myapp.spring.*" })
#Import(value = { LoginSecurityConfig.class })
public class LoginApplicationConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware{
private ApplicationContext applicationContext;
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
#Bean
public ViewResolver viewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
resolver.setCharacterEncoding("UTF-8");
return resolver;
}
#Bean
public TemplateEngine templateEngine() {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setEnableSpringELCompiler(true);
engine.setTemplateResolver(templateResolver());
return engine;
}
private ITemplateResolver templateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setApplicationContext(applicationContext);
resolver.setPrefix("/WEB-INF/templates/");
resolver.setTemplateMode(TemplateMode.HTML);
return resolver;
}
#Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/static/css").setCachePeriod(31556926);
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/static/images").setCachePeriod(31556926);
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
Then in my index.html file, I included the following line so I could include the style file (using thymeleaf):
<link rel="stylesheet" th:href="#{css/stylesmd.css}" type="text/css">
But I keep getting the error that the stylesmd.css failed to load.
My questions:
Is the placement of my styles and image files correct. That is, what folders should I specifically put them in. I tried various location like under the webapp and WEB-INF directory but that didn't work.
Are the bottom two methods in LoginApplicationConfigrequired? In addition, I was a bit confused on what to include in the addResourceHandler(...) method and what in the addResourceLocations(...) method.
Is my reference to the style sheet (using thymeleaf) correct?
I am aware a lot of content already exists on this question, but that did't work for me, so that's why I am asking.
This is how I made it work.
Only one line suffice.
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
And
<head>
<link rel="stylesheet" type="text/css" href="/static/css/your.css" th:href="#{/static/css/your.css}"/>
</head>
If it keeps failing, try to move your "templates" folder into the resources folder as a subfolder.

utf8 charset with Thymeleaf

When using Spring with Thymeleaf all my Cyrillic characters are shown as ????? on pages.
Using
#RequestMapping(value = "/login", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
as it was suggested here: https://stackoverflow.com/a/11866822/1479414 and here: https://stackoverflow.com/a/12023816/1479414 doesn't help.
How to solve this issue?
The answer can be found here:
Property characterEncoding should be explicitly set for templateResolver and ThymeleafViewResolver:
<bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
...
<property name="characterEncoding" value="UTF-8"/>
...
</bean>
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
...
<property name="characterEncoding" value="UTF-8"/>
...
</bean>
working for me. java config
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.projectName.controller")
public class MVCConfig implements WebMvcConfigurer, ApplicationContextAware {
#Autowired
private ApplicationContext applicationContext;
#Override
public void setApplicationContext(ApplicationContext applicationContext) throws
BeansException {
this.applicationContext = applicationContext;
}
#Bean
public ViewResolver viewResolver(){
ThymeleafViewResolver thymeleafViewResolver = new ThymeleafViewResolver();
thymeleafViewResolver.setTemplateEngine(templateEngine());
thymeleafViewResolver.setCharacterEncoding("UTF-8");
return thymeleafViewResolver;
}
#Bean
public TemplateEngine templateEngine(){
SpringTemplateEngine springTemplateEngine = new SpringTemplateEngine();
springTemplateEngine.setEnableSpringELCompiler(true);
springTemplateEngine.setTemplateResolver(templateResolver());
return springTemplateEngine;
}
#Bean
public ITemplateResolver templateResolver(){
SpringResourceTemplateResolver springResourceTemplateResolver = new
SpringResourceTemplateResolver();
springResourceTemplateResolver.setApplicationContext(applicationContext);
springResourceTemplateResolver.setPrefix("/WEB-INF/views/");
springResourceTemplateResolver.setTemplateMode(TemplateMode.HTML);
springResourceTemplateResolver.setSuffix(".html");
springResourceTemplateResolver.setCharacterEncoding("UTF-8");
return springResourceTemplateResolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
}
in Config
public class SpringConfig implements WebMvcConfigurer {
private final ApplicationContext applicationContext;
#Autowired
public SpringConfig(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
#Bean
public SpringResourceTemplateResolver templateResolver() {
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(applicationContext);
templateResolver.setPrefix("/WEB-INF/views/");
templateResolver.setSuffix(".html");
templateResolver.setCharacterEncoding("UTF-8");
return templateResolver;
}
#Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
templateEngine.setEnableSpringELCompiler(true);
return templateEngine;
}
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
resolver.setCharacterEncoding("UTF-8");
registry.viewResolver(resolver);
}
}
In ServletInitializer
public class MySpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return null;
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringConfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
#Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("UTF-8");
filter.setForceEncoding(true);
return new Filter[] { filter };
}
}
If you have added <property name="characterEncoding" value="UTF-8"/> in the bean configuration for view resolver and still text are not shown in correct format then the problem is in the properties/resource_bundle files.
Try encoding UTF-8 or non-English characters with native2ascii tool. (its included in the java_home/bin folder.
In my case, I put below 2 lines in application.properties file
spring.thymeleaf.enabled=true
spring.thymeleaf.encoding=UTF-8
(Korean)Reference: https://blog.thjang.net/33
With Spring WebFlux, I've restricted the view resolver to use text/html; charset=UTF-8 as the only supported content type. I've used a custom WebFluxConfigurer for that (in Kotlin):
class CustomWebFluxConfigurer(
private val viewResolver: ThymeleafReactiveViewResolver
) : WebFluxConfigurer {
override fun configureViewResolvers(registry: ViewResolverRegistry) {
viewResolver.supportedMediaTypes =
listOf(MediaType.parseMediaType("text/html; charset=UTF-8"))
registry.viewResolver(viewResolver)
}
}
I think in thymeleaf html page you are using th:text with html element, th:text it just display normal text,
if you want use special charter with your thymeleaf html page so just need to change for example
th:utext="${yourcontroller_var}"
or
th:utext="#{properties_var}"
For example
<div th:utext="${user.name}"> Test! </div> // for your controller variable
And
<div th:utext="#{message.username}"> UserName! </div> // for your properties variable
Nothing do other configuration for using special character with thymeleaf html page.
Hope you will fix your problem

Spring 4 with Annotation Tomcat Deployment 404 Error

I am using Spring 4, Servlet 3 API and Tomcat 8 for my project. I have a problem with deployment. I am trying to deploy WAR package in my VPS. I am using Intellij IDEA.
I coppied my WAR to /opt/tomcat/webapps path. I can see WAR from Tomcat's apps page. But when I try to browse URL I get 404 Not Found error.
I am using Spring with annotation and empty web.xml and also I am using Spring Security.
WepAppInitializer.java
public class WepAppInitializer implements WebApplicationInitializer {
#Override
public void onStartup(final ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebConfig.class);
ctx.setServletContext(servletContext);
ServletRegistration.Dynamic dynamic = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
dynamic.addMapping("/acentecilik");
dynamic.setLoadOnStartup(1);
}
}
WebConfig.java
#Configuration
#EnableWebMvc
#EnableTransactionManagement
#ComponentScan("com.decimatech.acentecilik")
#PropertySource("classpath:application.properties")
public class WebConfig extends WebMvcConfigurerAdapter{
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new ThymeleafLayoutInterceptor());
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry){
registry.addResourceHandler("/resources/**").addResourceLocations("/static/");
}
#Bean
#Description("Thymeleaf template resolver serving HTML 5")
public ServletContextTemplateResolver templateResolver() {
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
templateResolver.setPrefix("/WEB-INF/html/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("LEGACYHTML5");
templateResolver.setCharacterEncoding("UTF-8");
templateResolver.setCacheable(false);
return templateResolver;
}
#Bean
#Description("Thymeleaf template engine with Spring integration")
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
return templateEngine;
}
#Bean
#Description("Thymeleaf view resolver")
public ThymeleafViewResolver viewResolver() {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
viewResolver.setContentType("text/html;charset=UTF-8");
viewResolver.setCharacterEncoding("utf-8");
return viewResolver;
}
#Value("${spring.datasource.driver-class-name}")
private String driverClassName;
#Value("${spring.datasource.url}")
private String datasourceUrl;
#Value("${spring.datasource.username}")
private String datasourceUsername;
#Value("${spring.datasource.password}")
private String datasourcePassword;
#Bean(name = "dataSource")
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(datasourceUrl);
dataSource.setUsername(datasourceUsername);
dataSource.setPassword(datasourcePassword);
return dataSource;
}
#Autowired
#Bean(name = "transactionManager")
public HibernateTransactionManager getTransactionManager(SessionFactory sessionFactory) {
HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory);
return transactionManager;
}
#Autowired
#Bean(name = "sessionFactory")
public SessionFactory getSessionFactory(DataSource dataSource) {
LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
sessionBuilder.scanPackages("com.decimatech.acentecilik.model");
sessionBuilder.addProperties(getHibernateProperties());
return sessionBuilder.buildSessionFactory();
}
private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
properties.put("hibernate.hbm2ddl.auto", "update");
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
properties.put("hibernate.use_sql_comments", "true");
properties.put("hibernate.enable_lazy_load_no_trans", "true");
return properties;
}
#Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
web.xml
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1"
metadata-complete="true">
<display-name>Acentecilik</display-name>
<description>
Acentecilik
</description>
</web-app>
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.decimatech</groupId>
<artifactId>acentecilik</artifactId>
<version>1.0-SNAPSHOT</version>
//Some package dependencies
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.7</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
Here is some screenshot about what settings I used.
IDEA WAR Settings
Project Structures
Tomcat Manage Apps Page
And 404 Error
How can I solve this problem?
Here is my catalina log file's output. I changed WAR's ownership from root to tomcat user. But still same problem.
02-Oct-2015 16:03:23.800 SEVERE [localhost-startStop-10] org.apache.catalina.startup.ContextConfig.beforeStart Exception fixing docBase for context [/acentecilik]
java.io.IOException: Unable to create the directory [/opt/tomcat/webapps/acentecilik]
at org.apache.catalina.startup.ExpandWar.expand(ExpandWar.java:115)
at org.apache.catalina.startup.ContextConfig.fixDocBase(ContextConfig.java:618)
at org.apache.catalina.startup.ContextConfig.beforeStart(ContextConfig.java:744)
at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:307)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:95)
at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
at org.apache.catalina.util.LifecycleBase.setStateInternal(LifecycleBase.java:402)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:945)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1798)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
02-Oct-2015 16:03:58.561 INFO [localhost-startStop-10] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
02-Oct-2015 16:03:58.649 INFO [localhost-startStop-10] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive /opt/tomcat/webapps/acentecilik.war has finished in 34,860 ms
Edit
I changed /opt/tomcat/webapps ownership to tomcat and now I don't get the 404 error. But now I have this.
INFO [http-nio-8080-exec-17] org.apache.catalina.core.ApplicationContext.log No Spring WebApplicationInitializer types detected on classpath
the exception says
org.apache.catalina.startup.ContextConfig.beforeStart Exception fixing docBase for context [/acentecilik] java.io.IOException: Unable to create the directory
and you've already stated that tomcat is under /opt. so I suppose tomcat has not sufficient permission to create (write permission) on its own directory /opt/tomcat.
If you give write permission to the user who launches the tomcat (most probably your own user) then the problem goes away.
sudo chmod -R 0744 /opt/tomcat

How to use CommonsMultipartResolver in Spring Boot

I have tried to use CommonsMultipartResolver in Boot translating my old application (WAR) to Boot, and right now it got the following code:
#Configuration
public class TestConfig {
#Bean
public FilterRegistrationBean openEntityManagerFilterRegistrationBean() {
// Set upload filter
final MultipartFilter multipartFilter = new MultipartFilter();
final FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(multipartFilter);
filterRegistrationBean.addInitParameter("multipartResolverBeanName", "commonsMultipartResolver");
return filterRegistrationBean;
}
#Bean
public CommonsMultipartResolver commonsMultipartResolver() {
final CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
commonsMultipartResolver.setMaxUploadSize(-1);
return commonsMultipartResolver;
}
}
Is this the right way in Boot, cause a I saw some properties to be applied in application.properties. Would they be the same purpose than defining a FilterRegistrationBean?
# MULTIPART (MultipartProperties)
multipart.enabled=true
multipart.file-size-threshold=0 # Threshold after which files will be written to disk.
multipart.location= # Intermediate location of uploaded files.
multipart.max-file-size=1Mb # Max file size.
multipart.max-request-size=10Mb # Max request size.
Could anyone provide any sample how to use it? Thanks.
By the way, It tried to set the property "multipart.enabled=true" and I got:
Caused by: org.springframework.beans.NotWritablePropertyException: Invalid property 'enabled' of bean class [org.springframework.boot.autoconfigure.web.MultipartProperties]: Bean property 'enabled' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:1076)
at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:927)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:95)
at org.springframework.validation.DataBinder.applyPropertyValues(DataBinder.java:749)
at org.springframework.validation.DataBinder.doBind(DataBinder.java:645)
at org.springframework.boot.bind.RelaxedDataBinder.doBind(RelaxedDataBinder.java:121)
at org.springframework.validation.DataBinder.bind(DataBinder.java:630)
at org.springframework.boot.bind.PropertiesConfigurationFactory.doBindPropertiesToTarget(PropertiesConfigurationFactory.java:253)
at org.springframework.boot.bind.PropertiesConfigurationFactory.bindPropertiesToTarget(PropertiesConfigurationFactory.java:227)
at org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor.postProcessBeforeInitialization(ConfigurationPropertiesBindingPostProcessor.java:296)
... 73 common frames omitted
First, there is no enabled property in org.springframework.boot.autoconfigure.web.MultipartProperties class.
Refer https://github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/MultipartProperties.java
If you are using Servlet 3 container you no need to use commons-fileupload mechanism and Multipart support is enabled by default. If you don't want to customize any multipart default config no need to add any config in application.properties as well.
<form method="post" action="upload" enctype="multipart/form-data">
File: <input type="file" name="file"/>
<input type="submit" value="Submit"/>
</form>
#RequestMapping(value="/upload", method=RequestMethod.POST)
public String upload(#RequestPart("file") MultipartFile multipartFile)
{
System.out.println(multipartFile.getOriginalFilename());
return "redirect:/";
}
If you want to use commons-fileupload then adding following configuration is working fine:
package demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.multipart.support.MultipartFilter;
#SpringBootApplication
public class BootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(BootDemoApplication.class, args);
}
#Bean
public CommonsMultipartResolver commonsMultipartResolver() {
final CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
commonsMultipartResolver.setMaxUploadSize(-1);
return commonsMultipartResolver;
}
#Bean
public FilterRegistrationBean multipartFilterRegistrationBean() {
final MultipartFilter multipartFilter = new MultipartFilter();
final FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(multipartFilter);
filterRegistrationBean.addInitParameter("multipartResolverBeanName", "commonsMultipartResolver");
return filterRegistrationBean;
}
}
And of course we need to add commons-fileupload dependency.
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
This was a bug in Spring Boot and will be fixed in 1.2.5.
If you want to use CommonsMultipartFile to upload a file, please add #EnableAutoConfiguration(exclude = {MultipartAutoConfiguration.class}) in your spring boot project. Disable the multi-part configuration in spring boot.
public RespDataView provisionalMediaUpload(#RequestParam("file") CommonsMultipartFile file,
#RequestParam("type") String type) {}

Spring boot not serving static content returns a 404 not found

Spring boot configuration.
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
...
}
Where I placed the necessary static content
And accessing it through my jsp
<link href="./resources/css/bootstrap.min.css" rel="stylesheet">
it returns a 404 not found. What am I missing?
Spring Boot serves static resources from directories like /static, /public or /resources. So you could put your resources into src/main/resources/static.
If you have a resource src/main/resources/static/css/bootstrap.min.css you can access it via
<link href="/css/bootstrap.min.css" rel="stylesheet">
See also the Reference Guide.

Categories

Resources