CSS not loading in Spring Boot - spring

I am new to spring frame work and spring boot.I am trying to add the static html file with CSS,javascript,js. the file structure is
and my html file head looks like this
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>HeavyIndustry by HTML5Templates.com</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<link rel="stylesheet" type="text/css" media="all" href="css/5grid/core.css" th:href="#{css/5grid/core}" />
<link rel="stylesheet" type="text/css" href="css/5grid/core-desktop.css" />
<link rel="stylesheet" type="text/css" href="css/5grid/core-1200px.css" />
<link rel="stylesheet" type="text/css" href="css/5grid/core-noscript.css" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<link rel="stylesheet" type="text/css" href="css/style-desktop.css" />
<script src="css/5grid/jquery.js" type="text/javascript"></script>
<script src="css/5grid/init.js?use=mobile,desktop,1000px&mobileUI=1&mobileUI.theme=none" type="text/javascript"></script>
<!--[if IE 9]><link rel="stylesheet" href="css/style-ie9.css" /><![endif]-->
</head>
when i run the spring project only the content is shown and the CSS is not applied.then the browser show the following error in the console
404 Not Found error for the .css,.js files
some body help me to sort out this issue.Thanks in Advance.

You need to put your css in /resources/static/css. This change fixed the problem for me. Here is my current directory structure.
src
main
java
controller
WebAppMain.java
resources
views
index.html
static
css
index.css
bootstrap.min.css
Here is my template resolver:
public class WebAppMain {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(WebAppMain.class);
System.out.print("Starting app with System Args: [" );
for (String s : args) {
System.out.print(s + " ");
}
System.out.println("]");
app.run(args);
}
#Bean
public ViewResolver viewResolver() {
ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setTemplateMode("XHTML");
templateResolver.setPrefix("views/");
templateResolver.setSuffix(".html");
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setTemplateResolver(templateResolver);
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(engine);
return viewResolver;
}
}
And just in case, here is my index.html:
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring3-3.dtd">
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Subscribe</title>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<!-- Bootstrap -->
<link type="text/css" href="css/bootstrap.min.css" rel="stylesheet" />
<link type="text/css" href="css/index.css" rel="stylesheet" />
</head>
<body>
<h1> Hello</h1>
<p> Hello World!</p>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>

Put css files into webapp resources folder:
src/main/webapp/resources/css/
Configure resource handler
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
Example projects:
https://github.com/spring-guides/tut-web/tree/master/6/complete
Spring Boot Service Template with Static Content
Source:
Designing and Implementing a Web Application with Spring
Serving Web Content with Spring MVC

This is what worked for me after many attempts:
css location: /resources/static/css/stylesheet.css
link path in html: th:href="#{/css/stylesheet.css}"
WebSecurityConfig:
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/css/**");
}

Spring Boot will attempt to look in some default locations for your views. Have a look at the following link.
http://docs.spring.io/spring-boot/docs/1.1.4.RELEASE/reference/htmlsingle/#common-application-properties
If you're building an executable jar, your resources should be placed under src/main/resources, not src/main/webapp so that they're copied into your jar at build time.
Your index.html should go under src/main/resources/templates like you've got it, but your static resources shouldn't. Spring Boot will look for your Thymeleaf views there by default. And you don't actually need to define your own view resolver for Thymeleaf, Spring Boot will set this up for you if you have the spring-boot-starter-thymeleaf dependency in your project.
# THYMELEAF (ThymeleafAutoConfiguration)
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html # ;charset=<encoding> is added
spring.thymeleaf.cache=true # set to false for hot refresh
As mentioned by others, if you put your css in src/main/resources/static/css or src/main/resources/public/css, then referencing them from href="css/5grid..." in your HTML should work.

I was facing the same issues and solved it the following way:
Make sure the folder you are exporting is available to the web
public class WebMvcConfig extends WebMvcConfigurerAdapter {
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
"classpath:/META-INF/resources/", "classpath:/resources/",
"classpath:/static/", "classpath:/public/"
};
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
}
}
In addition you must put your css or styles folder into your src/main/resources/(static|public|resources|META-INF/resources) folder
Make sure your security policies don't block them
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
public void configure(WebSecurity web) throws Exception {
//Web resources
web.ignoring().antMatchers("/css/**");
web.ignoring().antMatchers("/scripts/**");
web.ignoring().antMatchers("/images/**");
}
}
That should be enough

In the case of Spring Boot, however, it’s worth mentioning how Spring
Boot deals with static content. When Spring Boot’s web
autoconfiguration is automatically configuring beans for Spring MVC,
those beans include a resource handler that maps /** to several
resource locations. Those resource locations include (relative to the
root of the classpath) the following:
/META-INF/resources/
/resources/
/static/
/public/
In a conventional Maven/Gradle-built application, you’d typically put
static content at src/main/webapp so that it would be placed at the
root of the WAR file that the build produces. When building a WAR file
with Spring Boot, that’s still an option. But you also have the option
of placing static content at one of the four locations mapped to the
resource handler.

I'm new to spring boot too and I have the same problem.
I have put the correct path manually into the browser and have seen the 404 by tomcat.
Then I have found a solution at:
Spring-Boot ResourceLocations not adding the css file resulting in 404
Now the css file is accessible by code.
You must move the css folder to src/main/resources/static/css then the content is readable (at my local configuration).

<link href="<%=request.getContextPath()%>/resources/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="<%=request.getContextPath()%>/resources/css/common.css" rel="stylesheet" media="screen">
[this is the image for my project structure. i added the webapp directory to support .jsp files.this method request.getContextPath() worked for me. Hope i help someone with this... it gets the path so long as it exists.
Nb. You should have a resolver bean in your webconfig
`enter code here`#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver resolver = new `enter code here`InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
return resolver;
}`
for the added directory][1]

Related

Spring boot static resources and controllers endpoint mixed

I have an endpoint 'localhost:8080/users' and a controller which should redirect any reqest which match '/users/**' pattern to 'localhost:8080/users' and show login page by returning index.html file which is an entry point for angular application. I have also a static resources in directory '..resources/static/users' which contains built angular applications. The index.html file is look as follow:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<base href="/users/" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
</head>
<body>
<app-root></app-root>
<script src="runtime-es2015.js" type="module"></script><script src="runtime-es5.js" nomodule defer></script><script src="polyfills-es5.js" nomodule defer></script><script src="polyfills-es2015.js" type="module"></script><script src="styles-es2015.js" type="module"></script><script src="styles-es5.js" nomodule defer></script><script src="vendor-es2015.js" type="module"></script><script src="vendor-es5.js" nomodule defer></script><script src="main-es2015.js" type="module"></script><script src="main-es5.js" nomodule defer></script></body>
</html>
The problem is that any request for static js files match my controller endpoint pattern and return the index.html file. How to resolve such a problem?
Use ResourceResolver for resolving static resources.
From Static Resources section in Spring Framework Reference:
Given a request that starts with /resources, the relative path is
used to find and serve static resources relative to /public under
the web application root or on the classpath under /static.
#Configuration
#EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/public", "classpath:/static/")
.setCachePeriod(31556926);
}
}
And,
WebJars are also supported through the WebJarsResourceResolver which
is automatically registered when the org.webjars:webjars-locator-core
library is present on the classpath.

spring boot jsp file can not be viewed

I'm using spring boot application. I have set the MvcConfig class for it and added tomcat-embed-jasper and jstl dependencies to pom.xml. However, I can not view my jsp file in the 'WEB-INF' folder, I will get 404 error (Whitelabel Error Page).I have set the Application.properties. here is my application.properties:
#
## View resolver
#
spring.view.prefix: /WEB-INF/jsp/
spring.view.suffix: .jsp
Here is my MvcConfig class:
package com.goodvideotutorials.spring.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
#Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("home");
}
}
Here is my home.jsp:
<%# page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Up and running with Spring Framework quickly</title>
</head>
<body>
<h2>Hello, world!</h2>
</body>
</html>
it is inserted inside src > main > webapp > WEB-INF > jsp > home.jsp
I have added these dependencies to pom.xml:
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
this is my Application.java class:
#Configuration
#ComponentScan
#EnableAutoConfiguration
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
}
}
and my controller class:
#Controller
public class RootController {
// #RequestMapping("/")
// public String home() {
//
// return "home";
//
// }
}
Any way if I make the code commented in the controller and don't use MvcConfig, it doesn't work. If I comment that code and use MvcConfig class, it doesn't work as well. This is the url : localhost:8080
I just tested many things , but it shows "Whitelabel Error Page" instead of JSP. I also have Tomcat server installed in the JEE environment. Could that cause problem?
just my 2 cents.
For me i received the following warning in server logs :
WARN : ResourceHttpRequestHandler : Path with "WEB-INF" or "META-INF": [WEB-INF/jsp/welcome.jsp]
and the white label error page was displayed, to fix it i modifed my JSP location
from
src/main/webapp/WEB-INF/jsp/welcome.jsp
to
src/main/webapp/templates/jsp/welcome.jsp
Why it worked for me ?
Spring documentation clearly states that ResourceHttpRequestHandler will reject any URL that contains either WEB-INF or META-INF.
ResourceHttpRequestHandler doc link
From DOCS: Identifies invalid resource paths. By default rejects:
Paths that contain "WEB-INF" or "META-INF"
Hence as soon as i replaced the WEB-INF folder name with templates, it started working.
Note :
I also had my internal view resolver configured with required prefix and suffix.
I am using spring-boot-starter-parent - 2.1.2.RELEASE
Spring boot help you automatically by:
Add file src/main/resources/application.properties:
spring.view.prefix: /WEB-INF/jsp/
spring.view.suffix: .jsp
And dependency:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
Or You should add configuration for view resolver like:
#Configuration
#EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
Change your Application like:
public class Application extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Follow below steps
1 - tomcat-embed-jasper dependency
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
2 - Add below configuration is application.properties
spring.mvc.view.prefix: /
spring.mvc.view.suffix: .jsp
3 - whatever JSP page you want to show so for that add below code in controller
#RequestMapping("/")
public String welcome(Model model) {
model.addAttribute("message", "Hello World !!!");
return "welcome";
}
so based on above code it will look for welcome.jsp file in webapps/welcome.jsp
That's it still have some doubt then check it out below link
Spring Boot and JSP Integration
The problem is caused by the <scope> of the org.apache.tomcat.embed dependency.
To resolve the <scope>provided</scope> line. So, the dependency looks like :
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
The scope provided is only available on the compilation and test classpath not at the runtime. It is not transitive as default scope compile.

Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers

This question has been asked before but I did not solve my problem and I getting some weird functionality.
If I put my index.html file in the static directory like so:
I get the following error in my browser:
And in my console:
[THYMELEAF][http-nio-8080-exec-3] Exception processing template "login":
Exception parsing document: template="login", line 6 - column 3
2015-08-11 16:09:07.922 ERROR 5756 --- [nio-8080-exec-3] o.a.c.c.C.[.[.[/].
[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet]
in context with path [] threw exception [Request processing failed; nested
exception is org.thymeleaf.exceptions.TemplateInputException: Exception
parsing document: template="login", line 6 - column 3] with root cause
org.xml.sax.SAXParseException: The element type "meta" must be terminated by
the matching end-tag "</meta>".
However if I move my index.html file into the templates directory I get the following error in my browser:
I have added my view resolvers:
#Controller
#EnableWebMvc
public class WebController extends WebMvcConfigurerAdapter {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/index").setViewName("index");
registry.addViewController("/results").setViewName("results");
registry.addViewController("/login").setViewName("login");
registry.addViewController("/form").setViewName("form");
}
#RequestMapping(value="/", method = RequestMethod.GET)
public String getHomePage(){
return "index";
}
#RequestMapping(value="/form", method=RequestMethod.GET)
public String showForm(Person person) {
return "form";
}
#RequestMapping(value="/form", method=RequestMethod.POST)
public String checkPersonInfo(#Valid Person person, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "form";
}
return "redirect:/results";
}
#Bean
public ViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("templates/");
//resolver.setSuffix(".html");
return resolver;
}
#Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
WebSecurityConfig.java
#Configuration
#EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/index").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
}
}
index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<meta>
<meta> charset="UTF-8">
<title></title>
</head>
<body>
<h1>Welcome</h1>
<span>Click here to move to the next page</span>
</body>
</html>
At this point I do not know what is going on. Can anyone give me some advice?
Update
I missed a typo in index.html, but I am still getting the same errors
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta> charset="UTF-8">
<title></title>
</head>
<body>
<h1>Welcome</h1>
<span>Click here to move to the next page</span>
</body>
</html>
Check for the name of the
templates
folder. it should be templates not template(without s).
index.html should be inside templates, as I know. So, your second attempt looks correct.
But, as the error message says, index.html looks like having some errors. E.g. the in the third line, the meta tag should be actually head tag, I think.
In the console is telling you that is a conflict with login. I think that you should declare also in the index.html Thymeleaf. Something like:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>k</title>
</head>
I am new to spring spent an hour trying to figure this out.
go to --- > application.properties
add these :
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
this can be resolved by copying the below code in application.properties
spring.thymeleaf.enabled=false
this make me success!
prefix: classpath:/templates/
check your application.yml
If you are facing this issue and everything looks good, try invalidate cache/restart from your IDE. This will resolve the issue in most of the cases.
this error probably is occurred most of the time due to missing closing tag. and further you can the following dependency to resolve this issue while supporting legacy HTML formate.
as it your code charset="UTF-8"> here is no closing for meta tag.
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>
For me the issue was because of Case sensitivity. I was using ~{fragments/Base} instead of ~{fragments/base} (The name of the file was base.html)
My development environment was windows but the server hosting the application was Linux so I was not seeing this issue during development since windows' paths are not case sensitive.
The error message might also occur, if the template name starts with a leading slash:
return "/index";
In the IDE the file was resolved successfully with a path with two slashes:
getResource(templates//index.html)
Delegating to parent classloader org.springframework.boot.devtools.restart.classloader.RestartClassLoader#2399ee45
--> Returning 'file:/Users/andreas/git/my-project/frontend/out/production/resources/templates//index.html'
On the productive system, where the template is packed into a jar, the resolution with two slashes does not work and leads to the same error message.
✅ Omit the leading slash:
return "index";
Adding spring.thymeleaf.mode=HTML5 in the application.properties worked for me. You could try that as well.
I also faced TemplateResolver view error , Adding the spring.thymeleaf.mode=HTML5 in the application.properties worked for me. In case of build created in STS and running for Websphere 9 ..
Check the html file is available in src/main/resources/templates folder
Try adding #RestController as well,
I was facing this same problem, i added both #RestController #Controller, it worked find
It May be due to some exceptions like (Parsing NUMERIC to String or vise versa).
Please verify cell values either are null or do handle Exception and see.
Best,
Shahid
I wasted 2 hours debugging this issue.
Althought I had the template file in the right location (within resources/templates/), I kept getting the same error.
It turns out it was because I had created some extra packages in my project. For instance, all controller files were in 'controller' package.
I did the same thing for the files which were automatically generated by Spring Initializr.
I don't understand exactly why this happens,
but when I moved the ServletInitializer file and the one annotated with #SpringBootApplication back to the root of the project, the error went away !
For me, including these in the pom.xml CAUSES the exception. Removing it from the pom.xml resolves the issue.
(Honestly, I don't know how that happen)
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<targetPath>${project.build.outputDirectory}</targetPath>
<includes>
<include>application.properties</include>
</includes>
</resource>
</resources>
</build>
In my case I had everything else right as suggested above but still it was complaining that "template might not exist or might not be accessible by any of the configured Template Resolvers". On comparing my project with some other sample projects which were working fine, I figured out I was missing
<configuration>
<addResources>true</addResources>
</configuration>
in spring-boot-maven-plugin. Adding which worked for me. So my plugins section now looks like
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<addResources>true</addResources>
</configuration>
</plugin>
</plugins>
I am not sure why I needed to add tag to get thymeleaf working though.
I tried all the solutions here and none of them seemed to be working for me
So I tried changing the return statement a little bit and it worked!
Seems like the issue with thymleaf not being able to recognize the template file, adding ".html" in the return statement seemed to fix this
#RequestMapping(value="/", method = RequestMethod.GET)
public String getHomePage(){
return "index.html";
}

Jersey Freemarker MVC

I try to configure jersey-mvc-freemarker on TomEE 1.7.2. But I can't ...
Configure Jersey
#ApplicationPath("resources")
public class JerseyConfig extends ResourceConfig{
public JerseyConfig() {
packages("my.pack.controllers")
.property(MvcFeature.TEMPLATE_BASE_PATH, "/WEB-INF/classes/my/pack")
.register(org.glassfish.jersey.server.mvc.freemarker.FreemarkerMvcFeature.class);
}
}
Controller
#Path("main")
public class MainController {
#Inject
private TestBean bean;
#GET
public Viewable getIt() {
return new Viewable("test");
}
}
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>ui</display-name>
</web-app>
I put my test.ftl to my.pack
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
test
</body>
</html>
When I go to http://localhost:8080/resources/main I get message
No message body writer has been found for response class Viewable.
Thanks you
UPDATE:
I configured tracing in Jersey and got:
javax.servlet.ServletException: Error processing webservice request
org.apache.tomee.webservices.CXFJAXRSFilter.doFilter(CXFJAXRSFilter.java:98)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.NullPointerException
org.apache.openejb.server.cxf.rs.CxfRsHttpListener.doInvoke(CxfRsHttpListener.java:227)
org.apache.tomee.webservices.CXFJAXRSFilter.doFilter(CXFJAXRSFilter.java:94)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
note The full stack trace of the root cause is available in the Apache Tomcat (TomEE)/7.0.62 (1.7.2) logs.

using ServletContext and ServletConfig in scriptlets and EL

I tried to run the following lines.
<%=application.getInitParameter("tagline")%>
<br />
<%=config.getInitParameter("admincontact")%>
${initParam.tagline}
<br />
${pageContext.servletConfig.initParameter("admincontact")}
And my web.xml is
<servlet>
<jsp-file>/index.jsp</jsp-file>
<init-param>
<param-name>admincontact</param-name>
<param-value>8939302763</param-value>
</init-param>
</servlet>
<context-param>
<param-name>tagline</param-name>
<param-value>Each one Plant one</param-value>
I get a exception at
${pageContext.servletConfig.initParameter("admincontact")}
and null value for
<%=config.getInitParameter("admincontact")%>.
Regards,
John
There is an FAQ on JavaRanch about this.
It states the following;
How to access servlet init parameters using EL?
You cannot use the following syntax to access servlet init parameters:
${pageContext.servletConfig.initParameter.name}
You cannot get Servlet init parameters using this technique. The
getInitParameter(java.lang.String name) does not fit in this case,
because it requires some arguments.
According to the JavaBean spec, the property has getter & setter
methods in the form
public type1 getXXX() -- WITH NO ARGUMENTS.
public void setXXX(type1)
Now consider the pageContext as bean Object. The
PageContext class has methods like getServletConfig(), getRequest(),
getSession() etc. You can access these like pageContext.page,
pageContext.request etc in EL.
ServletContext object has a couple of methods like getMajorVersion(),
getMinorVersion() with no args. so we can access these methods
treating it as properties to sevletContext bean as
pageContext.servletContext.majorVersion and
pageContext.servletContext.minorVersion.
If you want to access Servlet init parameters using EL, then it is
better to create a Map of the init parameters for the servlet and
place it in the request as a scoped variable -- let's say
initParameters. You would then be able to obtain any param by name
with ${requestScope.initParameters.name}.
NOTE:
We can access context init parameters with ${initParam.name}
In addition to Mr Moose's answer, I have found this solution that uses EL defining a custom tag.
It worked in my case.
Here the link
Basically you have to create a Java class like this:
package example.customTags;
import javax.servlet.jsp.JspPage;
public class MyFunctions {
public static String getJspInitParameter(JspPage page, String param){
return page.getServletConfig().getInitParameter(param);
}
}
Create a tld file like this (my filepath is WEB-INF/myTags/customTags.tld):
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>Functions</short-name>
<function>
<name>getJspInitParameter</name>
<function-class>example.customTags.MyFunctions</function-class>
<function-signature>
java.lang.String getJspInitParameter(javax.servlet.jsp.JspPage, java.lang.String)
</function-signature>
</function>
</taglib>
And use it in your JSP like this:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="my" uri="../WEB-INF/myTags/customTags.tld"%>
<!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>Example</title>
</head>
<body>
<c:out value="${my:getJspInitParameter(pageContext.page, 'admincontact')}"/>
</body>
</html>

Resources