Unable to serve jsp in spring boot with gradle - java

I m trying to combine spring boot , gradle , websocketJS and jsp
the idea is to have app running with jsp and websocket
i have managed to get the spring to serve the index.html file when placing it in : resources\static\
however i m unable to get the spring to serve the jsp files when placing them in :
webapp\WEB-INF\jsp\
You can get my github demo from here
application.properties
spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp
controller
#Controller
public class MarkerController {
#RequestMapping(value="/map")
public String trafficSpy() {
return "index";
}
** so far the jsp would not work if i go to localhost:8080/map
but localhost:8080 would point to the index.html
but when i try to implement WebMvcConfigurer , none would work
#EnableWebMvc
#Configuration
#ComponentScan({ "com.otot.mikdah" })
public class SpringWebConfig implements WebMvcConfigurer {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("/webjars/");
}
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/jsp/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}

Related

JSP/SpringMVC not finding the resources folder

I'm developing a webapp using Spring MVC/JSP with Java 11, and SpringMVC 5.2.0, which started with config files, but I wanted to give programatic config (through java) a try. I've got the Servlet running, and I've successfully made the login page to "intercept" any other .jsp view if the user is not logged... However, I haven't been able to get my resources from my resource folder.
Every resource that should be loaded from there (e.g.
<link type="image/png" rel="icon" href="${contextPath}/resources/img/icon.png">) I get a 404 response, and in my IDE (Netbeans 11) I get the following message in the Network Monitor:
Request URL: http://localhost:8080/icon.png
Method: GET
Status: 404
Note: The URL should be http://localhost:8080/dragonline/resources/img/icon.png (<c:set var="contextPath" value="${pageContext.request.contextPath}"/>)
Here's my config java file:
package com.midknightmunch.dragonline.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.ResourceBundleViewResolver;
import org.springframework.web.servlet.view.JstlView;
#EnableWebMvc
#Configuration
#ComponentScan(basePackages = {"com.midknightmunch.dragonline"})
public class WebConfig implements WebMvcConfigurer{
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
}
#Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
//registry.addResourceHandler("/img/**").addResourceLocations("/resources/img/");
//registry.addResourceHandler("/css/**").addResourceLocations("/resources/css/");
//registry.addResourceHandler("/js/**").addResourceLocations("/resources/js/");
//I've tried with and without these 3 (the commented ones)
}
#Bean
public ViewResolver internalViewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/views/");
bean.setSuffix(".jsp");
bean.setOrder(0);
return bean;
}
#Bean
public ViewResolver resourceBundleViewResolver() {
ResourceBundleViewResolver bean = new ResourceBundleViewResolver();
bean.setBasename("views");
bean.setOrder(1);
return bean;
}
#Bean("messageSource")
public ReloadableResourceBundleMessageSource messageSource() {
ReloadableResourceBundleMessageSource bean = new ReloadableResourceBundleMessageSource();
String[] basenames = {"classpath:validation"};
bean.setBasenames(basenames);
return bean;
}
}
And my project structure:
icon.png: dragonline/src/main/webapp/resources/img/icon.png
views(including the jsp trying to import this image): dragonline/src/main/webapp/WEB-INF/views/login.jsp
I've tried moving the resources folder everywhere, but everytime I get a 404.
Please, any help would be appreciated.
I figured it out. The problem was that I did not grant permission in my Spring Security config file to access the resources folder, so I solved it by adding:
http.authorizeRequests().antMatchers("/resources/**").permitAll()
in my WebSecurityAdapter's config() method

cannot change language in spring application

I'm trying to change language using <spring:message> tag. But it doesn't get recognized.
language.jsp
<%# taglib prefix="spring"
uri="http://www.springframework.org/tags" %>
<html>
<body>
<h1><spring:message code="home.title" /></h1>
<p><spring:message code="home.intro" /></p>
<p>
English |
French
</p>
</body>
</html>
AppConfig.java
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = {"com.dilini.controller", "com.dilini.service"})
#Import({DatabaseConfig.class, SecurityConfig.class})
public class AppConfig extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver jspViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setViewClass(JstlView.class);
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
return resolver;
}
#Bean
public HandlerInterceptor performanceInterceptor() {
PerformanceInterceptor interceptor;
interceptor = new PerformanceInterceptor();
return interceptor;
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(performanceInterceptor()).addPathPatterns("/user/*");
registry.addInterceptor(localeChangeInterceptor());
}
#Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:/messages");
messageSource.setUseCodeAsDefaultMessage(true);
return messageSource;
}
#Bean
public HandlerInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor();
interceptor.setParamName("lang");
return interceptor;
}
#Bean
public LocaleResolver localeResolver() {
CookieLocaleResolver localeResolver = new CookieLocaleResolver();
localeResolver.setDefaultLocale(new Locale("en"));
return localeResolver;
}
}
src/main/resources/messages/en.properties
home.title=Home
home.intro= this is my magnificent intro
Likewise the french.
src/main/resources/messages/fr.properties
home.title=Accueil
home.intro=Splendide page d'accueil,
Do I need to add another dependency for this feature? Or there is any issue is the code?
Please help
try this below code
#Bean(name = "localeResolver")
public LocaleResolver getLocaleResolver() {
CookieLocaleResolver resolver= new CookieLocaleResolver();
resolver.setCookieDomain("myAppLocaleCookie");
resolver.setCookieMaxAge(600);
return resolver;
}
#Bean(name = "messageSource")
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageResource= new ReloadableResourceBundleMessageSource();
// For example: i18n/messages_en.properties
// For example: i18n/messages_fr.properties
messageResource.setBasename("classpath:i18n/messages");
messageResource.setDefaultEncoding("UTF-8");
return messageResource;
}
#Override
public void addInterceptors(InterceptorRegistry registry) {
LocaleChangeInterceptor localeInterceptor = new LocaleChangeInterceptor();
localeInterceptor.setParamName("lang");
registry.addInterceptor(localeInterceptor).addPathPatterns("/*");
}
Note : messages_en.properties and messages_fr.properties should be present into src/main/resources/i18n
In your appconfig i don't see the interceptor registration. You simply defined it but you never registered it. You should override the addInterceptors method
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localeChangeInterceptor());
}
Try to add it and check if it works
In your src/main/resources/messages/ be sur to create both i18 files (en and fr named as below ):
in your MessageSource you just set the basename to messages => messageSource.setBasename("classpath:/messages");
so your local files should be named messages_[local].properties (spring will search for local names file as set in the as .setBasename() )
as below
messages_en.properties that contains :
home.title=Home
home.intro= this is my magnificent intro
and messages_fr.properties that
home.title=Accueil
home.intro= ceci est ma magnifique intro
It should work

Error saying : No mapping found for HTTP request with URI in DispatcherServlet due to Maven dependency

I am trying to authenticate and authorize using role base in spring using hibernate in java configuration. When I run the server then it gives me error sarying no mapping found for the URI in servlet.
public class ShoppingInitializerWeb implements WebApplicationInitializer {
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(ShoppingServletConfig.class);
ctx.setServletContext(container);
ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.setLoadOnStartup(1);
servlet.addMapping("/*");
}
}
ShoppingServletConfig.java
#Configuration
#EnableTransactionManagement
#ComponentScan(basePackages = "com.project.shopping")
public class ShoppingServletConfig extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/ui/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
WebConfigStatic.java
#EnableWebMvc
#Configuration
#ComponentScan(basePackages="com.project.shopping")
public class WebConfigStatic extends WebMvcConfigurerAdapter{
#Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/js/**").addResourceLocations("/ui/js/");
registry.addResourceHandler("/css/**").addResourceLocations("/ui/css/");
registry.addResourceHandler("/*.html/**").addResourceLocations("/ui/view/");
}
}
This is my controller:
#Controller
#RequestMapping("/")
public class UserController {
#RequestMapping(value = { "/", "/home" }, method = RequestMethod.GET)
public String homePage(ModelMap model) {
model.addAttribute("user", getPrincipal());
return "welcome";
}
And I have got welcome.jsp in webapp/WEB-INF/ui/view
Here is the error in console:
WARNING: No mapping found for HTTP request with URI [/Shoping/home] in DispatcherServlet with name 'dispatcher'
I looked up all the related errors and tried solving but couldn't get it solved.
I have faced a same project in my Spring project and I tried every possible way but no solution didn't work for that project however, finally I got a solution.
After adding maven dependencies into project deployment assembly, my project worked perfectly. So, you can try with below procedures, it should work if your code is perfect.
Right click on Project then select Properties > Deployment Assembly >
then click add button > Java Build path entries > Select Maven
dependencies > click Finish button.
then update maven project, and then mvn clean install ... then run.
I hope, it would work.

How to remove white label error page in spring boot application?

I am running a spring boot application. When I enter the URL http://localhost:8080 (or http://localhost:8080/index.jsp)I expect the index.jsp file to load, but I am getting the following error on the browser.
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sat Mar 05 21:56:33 IST 2016
There was an unexpected error (type=Not Found, status=404).
No message available
My index.jsp is present in webContent directory and my AppConfig class is as follows
#EnableJpaRepositories("com.test.repository")
#Configuration
#EnableTransactionManagement
#ComponentScan(basePackages="com.test.domain")
#PropertySource(value={"classpath:application.properties"})
public class AppConfig {
#Autowired
private Environment environment;
#Bean
public DataSource dataSource() {
DriverManagerDataSource datasource = new DriverManagerDataSource();
datasource.setDriverClassName(environment.getRequiredProperty("spring.datasource.driver-class-name"));
datasource.setUrl(environment.getRequiredProperty("spring.datasource.url"));
datasource.setUsername(environment.getRequiredProperty("spring.datasource.username"));
datasource.setPassword(environment.getRequiredProperty("spring.datasource.password"));
return datasource;
}
#Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
return resolver;
}
#Bean
public WebMvcConfigurerAdapter forwarderToIndex() {
return new WebMvcConfigurerAdapter() {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("forward://index.jsp");
}
};
}
}
I also referred this which didn't help me. How do I eliminate this error and redirect to index.jsp?
You can remove Error page auto configuration by using
exclude = { ErrorMvcAutoConfiguration.class }
in your #SpringBootApplication annotation
i.e
#SpringBootApplication(scanBasePackages = { "com.myapp.app" }, exclude = { ErrorMvcAutoConfiguration.class })
if you are not using
#SpringBootApplication you can do that by placing in your configuration class
#EnableAutoConfiguration( exclude = { ErrorMvcAutoConfiguration.class })
you can add tomcat jasper dependency in your pom.xml file
<dependency>
<groupId> org.apache.tomcat </groupId>
<artifactId> tomcat-jasper </artifactId>
<version>9.0.5</version>
</dependency>

Spring Boot, Java Config - No mapping found for HTTP request with URI [/...] in DispatcherServlet with name 'dispatcherServlet'

This has been a quite common problem here in stackOverflow, but none of the topics of the same problem solves mine.
We have a template configuration that uses xml config, but now we're trying to move away from that and start using Java config.
So I have a new project using Java config and Spring Boot. We're also using JSP and Tiles 3.
Problem is: it fails to render our admin login page.
Here is the code:
Main config class:
#SpringBootApplication
#EnableScheduling
#Import(OnAdminBeans.class)
public class AppConfig extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(AppConfig.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(AppConfig.class);
}
}
The AppConfig.class is is the main package. Through the #ComponentScan that #SpringBootApplication brings, it scans the other configurations that are on mainpackage.config, so it imports the view config class:
#Configuration
#EnableWebMvc
public class ViewConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/adm/static/**").addResourceLocations("/adm/static/");
}
// #Override
// public void addViewControllers(ViewControllerRegistry registry) {
// registry.addViewController("/adm/login").setViewName("login-template-tiles");
// }
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.viewResolver(viewResolver());
registry.viewResolver(jspViewResolver());
registry.viewResolver(tilesViewResolver());
}
#Bean
public LocaleResolver localeResolver() {
CookieLocaleResolver localeResolver = new CookieLocaleResolver();
localeResolver.setCookieName("locale");
localeResolver.setCookieMaxAge(30);
localeResolver.setDefaultLocale(new Locale("pt", "BR"));
return localeResolver;
}
#Bean
public MultipleViewResolver viewResolver() {
Map<String, ViewResolver> viewsResolvers = new HashMap<String, ViewResolver>();
viewsResolvers.put(MultipleViewResolver.ViewType.JSP.getKey(), jspViewResolver());
viewsResolvers.put(MultipleViewResolver.ViewType.TILES.getKey(), tilesViewResolver());
MultipleViewResolver viewResolver = new MultipleViewResolver();
viewResolver.setViewsResolvers(viewsResolvers);
viewResolver.setOrder(1);
return viewResolver;
}
#Bean
public InternalResourceViewResolver jspViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/jsp/");
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);
viewResolver.setOrder(2);
return viewResolver;
}
#Bean
public UrlBasedViewResolver tilesViewResolver() {
UrlBasedViewResolver viewResolver = new UrlBasedViewResolver();
viewResolver.setViewClass(TilesView.class);
viewResolver.setOrder(3);
return viewResolver;
}
#Bean
public TilesConfigurer tilesConfigurer() {
TilesConfigurer configurer = new TilesConfigurer();
configurer.setDefinitions("/WEB-INF/tile-defs/tiles-definitions.xml");
return configurer;
}
}
The LoginController.class is defined as:
#Controller
#RequestMapping(value = "/adm")
public class LoginController {
#RequestMapping(value = "/login")
public ModelAndView login() {
return new ModelAndView("login-template-tiles");
}
}
And in tiles-definitions.xml I have the following definition for login-template-tiles:
<definition name="login-template-tiles" template="/WEB-INF/jsp/adm/templates/login-template.jsp">
<put-attribute name="admin-title" value="Admin" />
<put-attribute name="content" value="/WEB-INF/jsp/adm/templates/sections/login/index.jsp" />
</definition>
Note that both files exist.
Given all that the LoginController.login() does get called when i try to access /adm/login. But it fails to find the proper jsp file, aparently.
It returns a 404. With TRACE enabled, I get the following log:
DispatcherServlet with name 'dispatcherServlet' processing GET request for [/WEB-INF/jsp/adm/templates/login-template.jsp]
Testing handler map [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#2118c09a] in DispatcherServlet with name 'dispatcherServlet'
Looking up handler method for path /WEB-INF/jsp/adm/templates/login-template.jsp
Did not find handler method for [/WEB-INF/jsp/adm/templates/login-template.jsp]
Testing handler map [org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping#2c148974] in DispatcherServlet with name 'dispatcherServlet'
No handler mapping found for [/WEB-INF/jsp/adm/templates/login-template.jsp]
Testing handler map [org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#784c3547] in DispatcherServlet with name 'dispatcherServlet'
No handler mapping found for [/WEB-INF/jsp/adm/templates/login-template.jsp]
Testing handler map [org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport$EmptyHandlerMapping#533e0604] in DispatcherServlet with name 'dispatcherServlet'
Testing handler map [org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport$EmptyHandlerMapping#cfd1b4e] in DispatcherServlet with name 'dispatcherServlet'
No mapping found for HTTP request with URI [/WEB-INF/jsp/adm/templates/login-template.jsp] in DispatcherServlet with name 'dispatcherServlet'
Any suggestions are appreciated!
EDIT:
Ok. By debugging, I found out that it has something to do with the embedded Tomcat. Other than that, I have no clue what is going on.
EDIT 2:
Found that the problem is in org.springframework.web.servlet.DispatcherServlet#getHandler. It simply doesn't find a HandlerMapping for that request. Do I have to register one?
OK! Found the problem.
This link helped me: https://samerabdelkafi.wordpress.com/2014/08/03/spring-mvc-full-java-based-config/
More specifically this configuration:
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
By setting a default handler, I would no longer get a white page but instead the JSP code as html, which clearly tells me that the JSP was being found but not rendered.
So the answer was on this page: JSP file not rendering in Spring Boot web application
I was missing the tomcat-embed-jasper artifact.
Add below dependency to your pom.xml
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
The tips here helped me when I got stuck with a similar problem. I fixed it after adding this fragment on my configuration
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}

Categories