Spring MVC show image - spring-mvc

I want to show image in my JSP page in my Spring MVC Project , but the images are not working.
The images are located in src/main/webapp/resources/images folder
Folder structure
Please find the code below. Any help will be appreciated:
#Configuration
#EnableWebMvc
public class WebMVCConfig extends WebMvcConfigurationSupport {
// Resource reading from jsp
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//Here I declare a mapping of src\main\webapp\resources folder and all its content to a resource location value /resources/
registry.addResourceHandler("/resources/**").addResourceLocations("classpath:/resources/");
}
// Property reading from jsp
#Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("/WEB-INF/i18n/application");
return messageSource;
}
// View Resolver
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
//internalResourceViewResolver.setViewClass(JstlView.class);
internalResourceViewResolver.setPrefix("/");
internalResourceViewResolver.setSuffix(".jsp");
return internalResourceViewResolver;
}
}
In the jsp it is called as :
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
</head>
<body>
<img src="<c:url value='/resources/images/abc.jpg' />" >
</body>
</html>

based on our folder structure resource mapping is changed
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//Here I declare a mapping of src\main\webapp\resources folder and all its
content to a resource location value /resources/
registry.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}

ResourceResolvers can resolve resources, given their URL path. They can also resolve the externally facing public URL path for clients to use, given their internal resource path.
XML configuration:
<mvc:resources mapping="/resources/**" location="/resources/"/>
Annotation Configuration:
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
Use in jsp:
<img src="/contextpath/resources/images/abc.jpg" >
Resource folder structure in project:
TestProject
|
src
|
WebContent
|
resources
|
js/css/images

Related

Spring Dispatcher Servlet causing issues when trying to load my CSS sytlesheets

When I load my JSP page home.jsp I include the stylesheet signIn.css. But something is happening where I get Failed to load resource: the server responded with a status of 404 (Not Found) for my stylesheet. I think my spring dispatcher servlet is looking for URI /customerPortal/signIn.css when my CSS file is stored at /customerPortal/src/main/webapp/WEB-INF/signIn.css (w/o using spring I have no issues). I think its something with getServletMappings where it is cutting off the file location.
My CSS page is in the exact same location as my home.jsp page. I also set up my SpringMvcInitializer class and MvcConfiguration class as I'm using Spring boot. I also have a home controller. I am not using spring-dispatcher-servlet.xml.
//MvcConfiguration.java
package Configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import ShoppingCart.Cart;
#Configuration
#ComponentScan(basePackages="Controllers/")
#EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver getViewResolver()
{
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/");
resolver.setSuffix(".jsp");
return resolver;
}
#Bean
public Cart getCart(){
return new Cart();
}
}
//SpringMvcInitializer.java
package Configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {MvcConfiguration.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
//home.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%#include file="header.jsp" %>
<link rel="stylesheet" href="/src/main/webapp/WEB-INF/signIn.css">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
</body
</html>
My jsp and css page are stored in
/customerPortal/src/main/webapp/WEB-INF/home.jsp
/customerPortal/src/main/webapp/WEB-INF/signIn.css
But on my eclipse console I get the following:
- DispatcherServlet with name 'dispatcher' processing GET request for [/customerPortal/signIn.css]
- Did not find handler method for [/signIn.css]
- No mapping found for HTTP request with URI [/customerPortal/signIn.css] in DispatcherServlet with name 'dispatcher'
And on my chrome console browser I get:
GET http://localhost:8035/customerPortal/signIn.css net::ERR_ABORTED 404 (Not Found)
Why is it looking for URI /customerPortal/signIn.css when my CSS file is stored at /customerPortal/src/main/webapp/WEB-INF/signIn.css ?
For your information, you can not directly access WEB-INF with URL, Java servlets will not allow it. moreover, do not place resources under WEB-INF
What should you do now?
Create a folder called, resources under webapp and then create a folder for css (resources/css). then place all css under css folder. and create another folder js and place all JavaScript files there.
then add this method to your MvcConfiguration class.
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
now you have your css inside the resources, then access it via
<link rel="stylesheet" href="resources/css/signIn.css" />
Solution for your current problem, but not recommend to put static resources under WEB-INF.
change your <link rel="stylesheet" href="/src/main/webapp/WEB-INF/signIn.css"> code to this
<style><%#include file="/WEB-INF/signIn.css"%></style>
best of luck...! Happy coding..!

Problem with my mvc app isnt using style.css

Im trying to configure style css file with my mvc app. Everything is working well except that pages dont use style.css. Im doing it first time and i dont know how it should look like but i did this with internet. Where is a problem? :/
App config
#Configuration
#EnableWebMvc
#EnableTransactionManagement
#ComponentScan("spring")
#PropertySource({ "classpath:persistence-mysql.properties" })
public class AppConfig implements WebMvcConfigurer {
#Autowired
private Environment env;
private Logger logger = Logger.getLogger(getClass().getName());
#Bean
public InternalResourceViewResolver viewResolver()
{
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/views/");
return viewResolver;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
Head JSP file
<head>
<title>Site under construction</title>
<link href='<spring:url value="/resources/css/style.css"/>'>
</head>
Path to css file
\src\main\resources\css\style.css
Bring up the debug tools in your browser (F12 generally). You will most likely see a 404 for that file (missing). Check out what URL the browser is trying to pull the resource from. Most likely it's looking somewhere you aren't expecting.

How do I set home.jsp as my welcome page in java config based spring application

I am developing a spring application (annotation based configurations) in which index.jsp is my default welcome page. but now I don't want to display index.jsp as my welcome page and want to change it to home.jsp. how can I achieve this?
I tried below method from WebMvcConfigurerAdapter class
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("home");
}
it is not working.
You need to forward the default mapping. Hope this may help you!
#Configuration
public class YourViewClass extends WebMvcConfigurerAdapter
{
#Override
public void addViewControllers( ViewControllerRegistry registry )
{
registry.addViewController( "/" ).setViewName( "forward:/yourhomepage.html" );
registry.setOrder( Ordered.HIGHEST_PRECEDENCE );
super.addViewControllers( registry );
}
}

Spring Boot custom static resource location outside of project

How can I add a custom resource location that is on for example my D drive in folder called Resources.
#Configuration
public class StaticResourceConfiguration extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
super.addResourceHandlers(registry);
registry.addResourceHandler("/**").addResourceLocations("D:/Resources/");
}
}
This doesn't work.
This is my application class and the only other configuration file.
#SpringBootApplication
public class Application {
public static void main(String args[]){
SpringApplication.run(Application.class, args);
}
#Bean // for websocket endpoints
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
#Bean
public PasswordEncoder bcryptPasswordEncoder(){
return new BCryptPasswordEncoder();
}
}
You should state your location using the file prefix, check more here . So it should be
registry.addResourceHandler("/**").addResourceLocations("file:///D:/Resources/");
Try /D:/Resources/. Absolute path must start with /

Spring MVC Interceptor does not execute for resource handler URLs

In the following setup, the TimingInterceptor and CORSHeaders interceptor execute on all URL requests, except for /resources/** URLs. How do I make the interceptors work for /resources/** URLs served by the ResourceHttpRequestHandler?
#EnableWebMvc //equivalent to mvc:annotation-driven
#Configuration
#PropertySource("classpath:configuration.properties")
public class WebConfig extends WebMvcConfigurerAdapter {
#Inject
private TimingInterceptor timingInterceptor;
#Inject
private CORSHeaders corsHeaders;
// equivalent to mvc:resources
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
// equivalent to mvc:interceptors
#Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(timingInterceptor).addPathPatterns("/**");
registry.addInterceptor(corsHeaders).addPathPatterns("/**");
}
}
Update: As of Spring Framework 5.0.1 (and SPR-16034), interceptors are automatically mapped on ResourceHttpRequestHandler by default.
I think the configured interceptors aren't mappped on the resource handler, but on the one handling #RequestMapping requests.
Maybe try this instead?
#EnableWebMvc //equivalent to mvc:annotation-driven
#Configuration
#PropertySource("classpath:configuration.properties")
public class WebConfig extends WebMvcConfigurerAdapter {
#Inject
private TimingInterceptor timingInterceptor;
#Inject
private CORSHeaders corsHeaders;
// equivalent to mvc:resources
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Bean
public MappedInterceptor timingInterceptor() {
return new MappedInterceptor(new String[] { "/**" }, timingInterceptor);
}
#Bean
public MappedInterceptor corsHeaders() {
return new MappedInterceptor(new String[] { "/**" }, corsHeaders);
}
}
This should be better documented with SPR-10655.
I never tried to use Spring interceptors for serving resources. The power of interceptors is to have a hook before controller and between controller and view.
To add pre- or post-processing around resources, you'd better use filters.

Resources