I cant include css file in jsp page - java

I tried various tutorials but it simply dosen't work.
I am building spring application with boostrap. I want to include bootstrap.min.css in my jsp page.
Here is my project tree:
this is my spring configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.packt.webstore" />
<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" />
<mvc:resources location="WEB-INF" mapping="/resource"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10240000"/>
</bean>
</beans>
This line is important:
<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" />
This is my view page:
I uploaded image on purpose to show that I can't even import it because it dosen't recognize the path. Well I tried other configuration but I can't figure out how to do it the right way.

you can use the jstl :
<link href="<c:url value="/resources/css/main.css" />" rel="stylesheet">
<script src="<c:url value="/resources/js/jquery.1.10.2.min.js" />"></script>
or Spring tags :
<spring:url value="/resources/js/jquery.1.10.2.min.js" var="jqueryJs" />
<spring:url value="/resources/js/main.js" var="bootstrap" />
<link href="${bootstrap}" rel="stylesheet" />
<script src="${jqueryJs}"></script>
or
<link href="${pageContext.request.contextPath}/resources/css/main.css" rel="stylesheet" >
<script src="${pageContext.request.contextPath}/resources/css/jquery.js"></script>

Some time ago I've created simple web app using jsp and servlets and I had same problem. I've resolved this by adding context name at the beginning of every url. Here is example of that url:
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/form-style.css" />
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/edit-contact-form-style.css" />
<script src="${pageContext.request.contextPath}/js/edit-contact-form-scripts.js"></script>
<script src="${pageContext.request.contextPath}/js/datetimepicker.js"></script>
Try it. I hope this helps.

configure view resolver and move the css files under the configured location.
you can refer this already answered question: spring mvc where to put css/js/img files

If you want to be not like those xml losers and do an app with zero xml, don't forget to make a class like this:
public class DemoAppConfig implements WebMvcConfigurer {
#Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/pages/");
bean.setSuffix(".jsp");
return bean;
}
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}

Related

Java Spring-MVC application doesn't send CSS and JS files. Error 404

Problem is common, I've tried a lot of solutions but nothing works for me.
I am quite new in Spring so I may not understand some things.
I've got next files structure:
My link inside page is templated by Thymeleaf like this:
<link rel="stylesheet" th:href="#{css/bootstrap.css}" type="text/css"/>
Also, there is attribute in head of html.
Ok, and my spring-context.xml is:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--to pick up all annotation in the package-->
<context:component-scan base-package="langquiz"/>
<mvc:annotation-driven />
<mvc:resources mapping="/css/**" location="/css/"/>
</beans>
I've tried some manipulations with mapping (like writing location="/templates/css/" or location="css/"), also tried resource handler in configuration class. But nothing helps.
Thank you!
UPD:
Changed
<mvc:resources mapping="/css/**" location="/css/"/>
to
<mvc:resources mapping="/css/**" location="/templates/"/>
and also tried
<mvc:resources mapping="/css/**" location="/"/>
but still have no result.
Use
<mvc:resources mapping="/css/**" location="/templates/css/"/>
Or adding a resource handler,
#Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**").addResourceLocations("/templates/css/");
}
}
Your mapping is incorrect in which location should include your templates directory as well as shown below:
<mvc:resources mapping="/css/**" location="/templates/css/"/>
You can refer here from the spring doc on this:
For example, to serve resource requests with a URL pattern of
/resources/ from a public-resources directory within the web
application root you would use:
<mvc:resources mapping="/resources/**" location="/public-resources/"/>
Changed to to make it work.
Still wondering if there is a way to see web site not on http://localhost:8080/project-name-snapshot but on http://localhost:8080

XHTML Basic support for Thymeleaf?

I'm trying to get Spring 4.1.9 and Thymeleaf 2.1.5 to render XHTML Basic 1.1 pages, which have the following preamble:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN"
"http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
Simply using this in a template doesn't work, as Thymeleaf doesn't recognize the doctype.
org.thymeleaf.exceptions.TemplateProcessingException: Unsupported entity requested with PUBLICID "-//W3C//DTD XHTML Basic 1.1//EN" and SYSTEMID "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd". Make sure a corresponding org.thymeleaf.doctype.resolution.IDocTypeResolutionEntry implementation is provided by you dialect (index:1)
Setup
I went through the Thymeleaf extension documentation and source code and using that as a starting point, defined a new dialect inheriting from SpringStandardDialect. I figured out the missing modules through trial and error, downloading them from w3.org and adding them to the resources directory of my project:
XhtmlBasicDialect.java
import java.util.LinkedHashSet;
import java.util.Set;
import org.thymeleaf.doctype.DocTypeIdentifier;
import org.thymeleaf.doctype.resolution.ClassLoaderDocTypeResolutionEntry;
import org.thymeleaf.doctype.resolution.IDocTypeResolutionEntry;
import org.thymeleaf.spring4.dialect.SpringStandardDialect;
public class XhtmlBasicDialect extends SpringStandardDialect {
private static final String DTD_STANDARD_PATH = "org/thymeleaf/dtd/standard/";
private static final DocTypeIdentifier XHTML_BASIC_11_PUBLICID = DocTypeIdentifier.forValue("-//W3C//DTD XHTML Basic 1.1//EN");
private static final DocTypeIdentifier XHTML_BASIC_11_SYSTEMID = DocTypeIdentifier.forValue("http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd");
private static final DocTypeIdentifier ENTITIES_XHTML_BASIC_11_DOCUMENT_MODEL_1_PUBLICID = DocTypeIdentifier.forValue("-//W3C//ENTITIES XHTML Basic 1.1 Document Model 1.0//EN");
private static final DocTypeIdentifier ELEMENTS_XHTML_BASIC_TABLES_1_PUBLICID = DocTypeIdentifier.forValue("-//W3C//ELEMENTS XHTML Basic Tables 1.0//EN");
private static final DocTypeIdentifier ELEMENTS_XHTML_INPUTMODE_1_PUBLICID = DocTypeIdentifier.forValue("-//W3C//ELEMENTS XHTML Inputmode 1.0//EN");
private static final DocTypeIdentifier ELEMENTS_XHTML_TARGET_1_PUBLICID = DocTypeIdentifier.forValue("-//W3C//ELEMENTS XHTML Target 1.0//EN");
private static final IDocTypeResolutionEntry XHTML_BASIC_STRICT_DOC_TYPE_RESOLUTION_ENTRY = new ClassLoaderDocTypeResolutionEntry(XHTML_BASIC_11_PUBLICID, XHTML_BASIC_11_SYSTEMID, DTD_STANDARD_PATH + "xhtml-basic11.dtd");
private static final IDocTypeResolutionEntry ENTITIES_XHTML_BASIC_11_DOCUMENT_MODEL_1_DOC_TYPE_RESOLUTION_ENTRY = new ClassLoaderDocTypeResolutionEntry(ENTITIES_XHTML_BASIC_11_DOCUMENT_MODEL_1_PUBLICID, DocTypeIdentifier.ANY, DTD_STANDARD_PATH + "xhtml-basic11-model-1.mod");
private static final IDocTypeResolutionEntry ELEMENTS_XHTML_BASIC_TABLES_1_DOC_TYPE_RESOLUTION_ENTRY = new ClassLoaderDocTypeResolutionEntry(ELEMENTS_XHTML_BASIC_TABLES_1_PUBLICID, DocTypeIdentifier.ANY, DTD_STANDARD_PATH + "xhtml-basic-table-1.mod");
private static final IDocTypeResolutionEntry ELEMENTS_XHTML_INPUTMODE_1_DOC_TYPE_RESOLUTION_ENTRY = new ClassLoaderDocTypeResolutionEntry(ELEMENTS_XHTML_INPUTMODE_1_PUBLICID, DocTypeIdentifier.ANY, DTD_STANDARD_PATH + "xhtml-inputmode-1.mod");
private static final IDocTypeResolutionEntry ELEMENTS_XHTML_TARGET_1_DOC_TYPE_RESOLUTION_ENTRY = new ClassLoaderDocTypeResolutionEntry(ELEMENTS_XHTML_TARGET_1_PUBLICID, DocTypeIdentifier.ANY, DTD_STANDARD_PATH + "xhtml-target-1.mod");
#Override
protected Set<IDocTypeResolutionEntry> getAdditionalDocTypeResolutionEntries() {
final Set<IDocTypeResolutionEntry> docTypeResolutionEntries = new LinkedHashSet<IDocTypeResolutionEntry>();
docTypeResolutionEntries.add(XHTML_BASIC_STRICT_DOC_TYPE_RESOLUTION_ENTRY);
docTypeResolutionEntries.add(ENTITIES_XHTML_BASIC_11_DOCUMENT_MODEL_1_DOC_TYPE_RESOLUTION_ENTRY);
docTypeResolutionEntries.add(ELEMENTS_XHTML_BASIC_TABLES_1_DOC_TYPE_RESOLUTION_ENTRY);
docTypeResolutionEntries.add(ELEMENTS_XHTML_INPUTMODE_1_DOC_TYPE_RESOLUTION_ENTRY);
docTypeResolutionEntries.add(ELEMENTS_XHTML_TARGET_1_DOC_TYPE_RESOLUTION_ENTRY);
return docTypeResolutionEntries;
}
}
I configure the custom dialect as follows:
mvc-config.xml
...
<bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
<property name="prefix" value="/WEB-INF/templates/" />
<property name="suffix" value=".xhtml" />
<property name="characterEncoding" value="UTF-8" />
<property name="templateMode" value="XHTML" />
<property name="xhtmlTemplateModePatterns" value="*.xhtml" />
</bean>
<bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="templateResolver" ref="templateResolver" />
<property name="additionalDialects">
<set>
<bean class="demo.XhtmlBasicDialect" />
</set>
</property>
</bean>
<bean id="xhtmlViewResolver" class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="templateEngine" ref="templateEngine" />
<property name="characterEncoding" value="UTF-8" />
<property name="contentType" value="application/xhtml+xml" />
</bean>
...
My template is as follows:
DemoTemplate.xhtml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN"
"http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Demo</title>
<link th:href="${'style' + '.css'}" rel="stylesheet" type="text/css"/>
</head>
<body>
<div>
<p>Demo content</p>
</div>
</body>
</html>
The Problem
At first glance, this seems to render fine, except that the resulting XHTML is missing the XML header, and has several extra attributes that are added to every element.
Rendered output:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="-//W3C//DTD XHTML Basic 1.1//EN">
<head xmlns="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<title xmlns="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Demo</title>
<link rel="stylesheet" type="text/css" xmlns="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xml:space="preserve" href="style.css" />
</head>
<body xmlns="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xml:space="preserve">
<div xmlns="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xml:space="preserve">
<p xmlns="http://www.w3.org/1999/xhtml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xml:space="preserve">Demo content</p>
</div>
</body>
</html>
This doesn't quite match the XHTML Basic preamable; for one, I would like to keep XML declaration <?xml version="1.0" encoding="utf-8"?>
More importantly, I do not want the xmlns="http://www.w3.org/1999/xhtml", xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance", and xml:space="preserve" attributes to be added to just about every element. There's also an version="-//W3C//DTD XHTML Basic 1.1//EN" attribute added to the <html> element.
Am I doing something wrong, do I need to configure something differently, or am I missing something from the custom dialect?
Well I don't have "canonical" evidence that XHTML Basic templates can't be handled the way you want with Thymeleaf 2.x, and there probably is a way given enough effort. But I did see that:
XhtmlAndHtml5NonValidatingSAXTemplateParser in Thymeleaf 2.1 looks fishy and no longer exists in Thymeleaf 3.0
The XHTML TemplateMode is now deprecated, along with xhtmlTemplateModePatterns
That all the parsing code in 2.1 had been rewritten in 3.0
This, along with my own struggles to get something working, leads me to believe that the XHTML handling in Thymeleaf 2.X was never fully baked. However, it seems to work just fine in 3.0 with no special effort. Just configure a ViewResolver as follows:
<bean id="viewResolver" class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
<property name="characterEncoding" value="UTF-8"/>
<property name="templateEngine">
<bean class="org.thymeleaf.spring4.SpringTemplateEngine">
<property name="enableSpringELCompiler" value="true"/>
<property name="templateResolver">
<bean class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
<property name="prefix" value="/WEB-INF/templates/"/>
<property name="suffix" value=".xhtml"/>
<property name="templateMode" value="XML"/>
</bean>
</property>
</bean>
</property>
</bean>
I posted a complete working example on github.

Spring MVC default-servlet-handler configuration blocking JSTL view

I have simple Spring configuration
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<!-- Scan for components under this package -->
<context:component-scan base-package="com.osfg.test" />
And my controller is
package com.osfg.test;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* #author athakur
*/
#Controller
public class TestController {
#RequestMapping(value="/test", method=RequestMethod.GET)
public String welcome() {
return "test";
}
}
And my JSP is
<%# 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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>OSFG Test Page</title>
<link href="CSS/test.css" rel="stylesheet">
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
This configuration works fine (CSS does not get applied though).
So I add
<mvc:default-servlet-handler />
to my Spring configuration and now the page itself stops loading giving 404.
Also surprisingly everything works fine (with CSS) will following config
<mvc:view-controller path="/test" view-name="test"/>
<mvc:default-servlet-handler />
Direct rendering no controller involvement.
I think having a simple configuration for resources will suffice.
<mvc:resources mapping="/resources/**" location="/resources/" />
Looks like I found the issue. Somehow the default-sevlet-handler is overriding the DefaultAnnotationHandlerMapping handler? which is why annotation based handler is failing. Following scenarios worked for me -
Use <mvc:annotation-driven/>. This seems to enable default beans including DefaultAnnotationHandlerMapping So combination of
<mvc:annotation-driven/>
<mvc:default-servlet-handler />
worked.
Explicitly define the handler mapping and handler adapter you need with highest preference (chaining). Spring scans all handler mappings and assigns an order property Integer.MAX (if not explicitly defined) which gives it lowest preference. Then these handler mappings are sorted based on this order. Also if two handler mappings are same it looks like it takes bean which is defined first. So following worked for me -
<mvc:default-servlet-handler />
<bean id="annotationUrlMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="order" value="0" />
</bean>
<bean id="annotationMethodHandlerAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>
So I am guessing default-sevlet-handler creates it's own handler mapping which overrides the annotation one all being at same preference.

Spring MVC resource Mapping

I have been testing some request mapping in Spring MVC, and I came across a strange situation in my application. I decided to create a simple cenario so that you can understand my problem. I will first show you the details of my project (the source), and then I'll get to my question.
I have the following directory structure in my project:
+webapp
+WEB-INF
+recursos
+estilos
test.css
+spring
fronte-beans.xml
+views
+testes
page1.jsp
page2.jsp
web.xml
My Tomcat deployment descriptor:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd http://xmlns.jcp.org/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.4">
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>fronte</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/spring/fronte-beans.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>fronte</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
My application context for DispatcherServlet:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd ">
<mvc:annotation-driven />
<mvc:resources mapping="/recursos/**" location="/WEB-INF/recursos/" />
<context:component-scan base-package="com.regra7.minhaapp.contro" />
<bean id="handlerMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
My controller class for page1.jsp:
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
#RequestMapping(value="/path")
public class TestController
{
#RequestMapping(value="/to/something")
public String getPage()
{
return "testes/page2";
}
}
My page1.jsp:
<!DOCTYPE html>
<%# page
language="java"
contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%#taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html lang="pt-BR">
<!-- ############################################### -->
<!-- HEADER -->
<!-- ############################################### -->
<head>
<title>Test Page</title>
<meta name="author" content="RDS" />
<meta name="description" content="? ? ?" />
<meta charset="UTF-8" />
<link rel="stylesheet" type="text/css" href="recursos/estilos/test.css" media="all" />
</head>
<!-- ############################################### -->
<!-- BODY -->
<!-- ############################################### -->
<body>
<h1>PAGE 1</h1>
<p>This is a test, p1.</p>
<p>This is a test, p2.</p>
<p>This is a test, p3.</p>
CLICK TO PAGE 2
</body>
</html>
I can access page1.jsp and page2.jsp smoothly, but the CSS file of page2.jsp ends up not being found. The following text is printed on my console:
dez 29, 2014 8:16:22 PM org.springframework.web.servlet.PageNotFound noHandlerFound
WARNING: No mapping found for HTTP request with URI [/testeSpringMvc/path/to/recursos/estilos/test.css] in DispatcherServlet with name 'fronte'
For what reason "/path/to" is being included in the resulting path? If I try to add different combinations of mapping, both class or method-level, the same thing happens. However, if I map the link to a query string (URL) as follows, the file is found without problems...
page1.jsp:
CLICK TO PAGE 2
Controller:
#Controller
#RequestMapping(value="/")
public class TestController
...
#RequestMapping(params="cd=page2")
public String getPage()
What's happening? How can I set a path I want so that my pages use and find the necessary resources? I'm trying to separate pages in different paths so that I can apply the security features from Tomcat (security constraints).
NOTE: I've tried using contextPath to help me in setting the CSS file path, but nothing worked. In fact, the situation worsened because Page1.jsp also turned out not having stylization:
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}recursos/estilos/test.css" media="all" />
As always, thank you for your attention and time.
Same was happening to me, and I found a solution. I hope this can help someone else:
As you see in the error message, paths you use for resources /testeSpringMvc/path/to/recursos/estilos/test.css are trying to be resolved by Spring's DispatchServlet.
This happens because in your web.xml file you have the following:
<servlet-mapping>
<servlet-name>fronte</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Your fronte servlet will try to resolve anything that starts with /.
Just add a simple extension to you <url-pattern>. Something like <url-pattern>/*.html</url-pattern> should do the job.
I just found the answer to my problems. I will leave here the solution, but unfortunately I did not understand how it solves the seen scenario.
I have found that this can be solved with JSTL. I read the JSTL documentation, and all I found was this description:
Creates a URL with optional query parameters.
If reference to the CSS file is changed by the following sentence, the problem will be solved:
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<link rel="stylesheet" type="text/css" href="<c:url value="/recursos/estilos/test.css" />" media="all" />
If any moderator see this and know the explanation of how this is resolved, I kindly ask you to expose it here. Edit my answer, or comment it out, please. I'm sure other people can have the same doubt as me in the future.
Thank you all for the attention and time.
Take a look at this blog entry. The relevant passage is:
If I want to apply main.css to url: www.mysite.com/index.html, I need
to use following construction in HTML code:
< link href="resources/css/main.css" rel="stylesheet" type="text/css"/ >
If I want to apply main.css to url: www.mysite.com/some/location.html,
I need to use following construction in HTML code:
< link href="../resources/css/main.css" rel="stylesheet" type="text/css"/ >
As a possible workaround, perhaps this might work:
<mvc:resources mapping="/**/recursos/**" location="/WEB-INF/recursos/" />
You can access resource as given below.
<link rel="stylesheet" type="text/css" href="/recursos/estilos/test.css" media="all" />
you are missing / at the beginning

JSP Expression Language Error

I have created a dynamic web module project usig STS and Spring MVC. The problem is I have add a string into a Model but it cannot be display on the JSP page using EL.
May I know what wrong with it?
Below is the details:
JSP Page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" isELIgnored="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring MVC</title>
</head>
<body>
Home
<br />
<c:out value="${message}" />
</body>
</html>
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
MVC Controller:
#Controller
public class HomeController {
public HomeController() {
super();
}
#RequestMapping(value="/home", method=RequestMethod.GET)
public ModelAndView showHomePage() {
// View Name - Model Name - Model Data
return new ModelAndView("home", "message", "Hello Spring MVC");
}
}
Dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- http://www.jpalace.org/docs/tutorials/spring/mvc_10.html -->
<!-- Context Scan -->
<context:component-scan base-package="com.peter.controller"/>
<!-- Handler Mapping -->
<bean id="handlerMapping" class="org.springframework.web.portlet.mvc.annotation.DefaultAnnotationHandlerMapping">
</bean>
<!-- Handler Adapter - AnnotationMethodHandlerAdapter -->
<!-- Invoke Handler Method -->
<bean id="handlerAdapter" class="org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter">
</bean>
<!-- Pre/Post Handler Interceptor -->
<!--
Implement HandlerInterceptor
Declare HandlerInterceptor inside DefaultAnnotationHandlerMapping property or
globally inside <mvc:interceptors>
Need configure Filter object inside web.xml
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<list>
<bean class="pckg.MyInterceptor1"/>
<bean class="pckg.MyInterceptor2"/>
</list>
</property>
</bean>
<mvc:interceptors>
<bean class="pckg.MyInterceptor1"/>
<bean class="pckg.MyInterceptor2"/>
</mvc:interceptors>
-->
<!-- View Resolver -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- Exception Resolver -->
<!-- Register Interceptor, Message Resource, Bean validation support, Message conversion and field formatting -->
<mvc:annotation-driven />
</beans>
I have JSTL.jar in my build path. There is warning message about the The tag handler class for "c:out" (org.apache.taglibs.standard.tag.rt.core.OutTag) was not found on the Java Build Path
Please help.
Thanks.
Download jstl-1.2.jar from the maven repo (http://repo1.maven.org/maven2/javax/servlet/jstl/1.2/).
Ensure that
the jar is available in WEB-INF\lib folder of your web application.
I would like to view your viewResolver configuration. Are you able to view the home page?? or there is 404 error?
If home.jsp is displaying properly then according to me the problem is in your jsp.
Look at the first line of the jsp where you have defined the page directive.
In that declaration remove the attribute isELIgnored="false" it is bydefault false everytime. So no need to define it explicitely.
I think if you remove that attribute. Your ${message} would display correctly.
Hope this helps you.
Cheers.

Categories

Resources