Spring / Resource handler location - spring-mvc

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.

Related

Reference a CSS in Spring Boot

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;
}
}

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..!

How to link CSS in asp core MVC

I can't get my CSS files to work. I keep getting error 404. Apologies if this is really straightforward but I just can't get it to work.
I have a project in visual studio with the following folder structure:
-Properties
-launchSettings.json
-wwwroot
-css
-site.css
-images
-script
-site.js
-Pages
-Shared
_layout.cshtml
-index.cshtml
-index.cshtml.cs
-appsettings.json
-Program.cs
-Startup.cs
my startup.cs file
namespace WebApp
{
public class Startup
{
public IConfiguration Configuration { get; set; }
public Startup(IConfiguration config)
{
Configuration = config;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}
}
my _layout.cshtml page:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Welcome to JellyZone</title>
<link href="~/css/site.css" rel="stylesheet" type="text/css" />
<script src="~/script/site.js" type="text/javascript"></script>
</head>
<body onload="fadeIn()">
#RenderBody()
</body>
</html>
my index.cshtml is:
#page
#{ Layout = "~/Pages/Shared/_Login.cshtml";}
And whenever I try to debug this it gives me error 404.
I've looked online lots and tried using "#Use.Content("~/css/site.cs")" on the link and href and moving the folders into different locations etc.
Please help
Many thanks

Introductory Spring Boot MVC App - login failed because Could not verify the provided CSRF token because your session was not found

I am trying to write a simple introductory application via Spring Boot, Spring MVC, and Spring Security, but after submitting my Login-form I'm getting redirected a Whitelabel Error Page as a result of a 403 response. The error message is Could not verify the provided CSRF token because your session was not found.
Could anyone please tell me what I'm doing wrong? Should I be disabling CSRF filtering for the login endpoint somehow? And even though it seems to be saying a CSRF token was provided, I don't see one in the request's headers or in the form data... could that be the problem - that I'm not even providing a CSRF token?
/build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.springframework.boot:spring-boot-gradle-plugin:1.5.7.RELEASE'
}
}
apply plugin: 'groovy'
apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile ('org.springframework.boot:spring-boot-starter-web') {
exclude module: 'spring-boot-starter-tomcat'
}
compile 'org.springframework.boot:spring-boot-starter-jetty'
compile 'org.springframework.boot:spring-boot-starter-actuator'
compile 'org.springframework.boot:spring-boot-starter-security'
compile 'org.codehaus.groovy:groovy-all:2.3.11'
compile 'javax.servlet:jstl:1.2'
testCompile group: 'junit', name: 'junit', version: '4.12'
testCompile 'org.springframework.boot:spring-boot-starter-test'
testCompile 'org.springframework.security:spring-security-test'
}
/src/main/groovy/my.little.app.Application.groovy
#SpringBootApplication
#EnableWebMvc
#EnableAutoConfiguration
#ComponentScan
class Application extends AbstractAnnotationConfigDispatcherServletInitializer {
protected Class<?>[] getRootConfigClasses() {
return [WebMvcConfig.class, WebSecurityConfig.class]
}
protected Class<?>[] getServletConfigClasses() {
return [WebMvcConfig.class, WebSecurityConfig.class]
}
protected String[] getServletMappings() {
return [ "/" ]
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args)
}
}
/src/main/groovy/my.little.app.MainController.groovy
#Controller
class MainController {
#RequestMapping(path = '/', method = RequestMethod.GET)
public String index() {
return 'index'
}
}
/src/main/groovy/my.little.app.config.WebMvcConfig.groovy
#Configuration
#ComponentScan('my.little.app')
#EnableWebMvc
class WebMvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
super.addViewControllers(registry)
registry.addViewController('/index').setViewName('index')
registry.addViewController('/login').setViewName('login')
registry.addViewController('/secure_page').setViewName('secure_page')
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public ViewResolver internalResourceViewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver()
// bean.setViewClass(JstlView.class)
bean.setPrefix('/WEB-INF/views/')
bean.setSuffix('.jsp')
return bean
}
}
/src/main/groovy/my.little.app.config.WebSecurityConfig.groovy
#Configuration
#EnableWebMvc
#EnableWebSecurity
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity security) {
security
.authorizeRequests()
.antMatchers('/', '/index').permitAll()
.antMatchers('/login').anonymous()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage('/login').permitAll()
.defaultSuccessUrl('/secure_page')
.failureUrl('/login?error=true')
.and()
.logout()
.permitAll()
.logoutSuccessUrl('/login')
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder authBuilder) {
authBuilder
.inMemoryAuthentication()
.withUser('doug').password('las').roles('WIZARD')
}
}
/src/main/webapp/WEB-INF/views/index.jsp
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Web Security Tutorial</title>
</head>
<body>
<div>Welcome to the Web Security Tutorial</div>
<form method="get" action="/login">
<input type="submit" value="Sign In" />
</form>
</body>
</html>
/src/main/webapp/WEB-INF/views/login.jsp
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Web Security Tutorial</title>
</head>
<body>
<form method="post" action="login">
<div><label> User name: <input name="username" type="text"/></label></div>
<div><label> Password: <input name="password" type="password"/></label></div>
<div><input type="submit" value="Sign In"/></div>
</form>
</body>
</html>
/src/main/webapp/WEB-INF/views/secure_page.jsp
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Web Security Tutorial</title>
</head>
<body>
<div>Don't worry, no one can see this but you. Here are your deepest darkest secrets...</div>
<form action="/logout">
<input type="submit" value="Log Out"/>
</form>
</body>
</html>

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

Resources