Reference a CSS in Spring Boot - css

I have a Boot Application with Java Configuration but without ThymeLeaf and I am having trouble referencing CSS in my JSP page.
When I start up the application, I see this in Browser Console.
localhost/:1 Refused to apply style from 'http://localhost:8080/SheridanSports/css/nav.css' because its MIME type ('application/json') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
This is the structure of the Project
index.jsp
<head>
<title>Spring Sports-Home</title>
<base href="/">
<link href="${pageContext.request.contextPath}/css/nav.css" rel="stylesheet" type="text/css">
</head>
AppConfig.java
#Configuration
#EnableWebMvc
//#ComponentScan(basePackages = "com.abc.SheridanSportsWAR")
public class AppConfig implements WebMvcConfigurer{
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp");
return bean;
}
}

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.

Spring MVC show image

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

Spring rest controller not returning html

I'm using spring boot 1.5.2 and my spring rest controller looks like this
#RestController
#RequestMapping("/")
public class HomeController {
#RequestMapping(method=RequestMethod.GET)
public String index() {
return "index";
}
}
when I go to http://localhost:8090/assessment/ it reaches my controller but doesn't return my index.html, which is in a maven project under src/main/resources or src/main/resources/static. If I go to this url http://localhost:8090/assessment/index.html, it returns my index.html. I looked at this tutorial https://spring.io/guides/gs/serving-web-content/ and they use thymeleaf. Do I have to use thymeleaf or something like it for my spring rest controller to return my view?
My application class looks like this
#SpringBootApplication
#ComponentScan(basePackages={"com.pkg.*"})
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
When I add the thymeleaf dependency to my classpath I get this error (500 response code)
org.thymeleaf.exceptions.TemplateInputException: Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers
I guess I do need thymeleaf? I'm going to try and configure it properly now.
It works after changing my controller method to return index.html like this
#RequestMapping(method=RequestMethod.GET)
public String index() {
return "index.html";
}
I think thymeleaf or software like it allows you to leave off the file extension, not sure though.
RestController annotation returns the json from the method not HTML or JSP. It is the combination of #Controller and #ResponseBody in one. The main purpose of #RestController is to create RESTful web services. For returning html or jsp, simply annotated the controller class with #Controller.
Your example would be something like this:
Your Controller Method with your route "assessment"
#Controller
public class HomeController {
#GetMapping("/assessment")
public String index() {
return "index";
}
}
Your Thymeleaf template in "src/main/resources/templates/index.html"
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>Hello World!</p>
</body>
</html>
I solved this by removing #EnableWebMvc annotation from configuration class.
Spring MVC Auto-configuration provides static index.html support.
If you want to take complete control of Spring MVC, you can add your
own #Configuration annotated with #EnableWebMvc.
Get more detail from Spring MVC Auto-configuration.
If you try to "Building a RESTful Web Service" -> annotate your controller class with #RestController annotation if not annotate your controller class with #Controller class.
When we use spring as SpringMVC - #Controller
When we use spring as SpringRESTfull Web Service - #RestController
Use this link to read : Spring Stereo Type

Spring / Resource handler location

I have common problem in spring with resource locator and can not figure out where is problem (CSS style is not working:
My .JSP page and HTML code :
<head>
<link href="/css/basicStyle.css" rel="stylesheet" type="text/css"/>
</head>
My resource locator configuration :
#Configuration
#ComponentScan("loginsystem.controllers")
#EnableWebMvc
public class ServletConfig extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver =
new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
resolver.setViewClass(
org.springframework.web.servlet.view.JstlView.class);
return resolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void addResourceHandlers(final ResourceHandlerRegistry registry)
{
registry.addResourceHandler("/css/**").addResourceLocations("/LoginSystem/WebContent/WEB-INF/css/");
}
}
SOLUTION :
After looking in other questions I have found solution :
<link href="${pageContext.request.contextPath}/css/basicStyle.css/" rel="stylesheet" type="text/css"/>
Can any one explain why pageContext is needed ?
Change the resources locations from "/LoginSystem/WebContent/WEB-INF/css/" to "/WEB-INF/css/"
There's a dedicated JSP tag for this:
<!doctype html>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html>
<head>
<link href="<spring:url value="/css/basicStyle.css"/>"
rel="stylesheet" type="text/css"/>
If you want to have better resource handling support in your application, you may also want to register a ResourceUrlEncodingFilter in your application.

Resources