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

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

Related

Coexistence of both thymeleaf and jasper files in Spring Boot application

I tried, in a project both jasper and thymeleaf, but can not coexist, as I would like to use jsp must comment out Spring-boot-starter-thymeleaf depend on the package, so that it can run. Looking for a solution so that both jasper and thymeleaf can co exist. I got a solution on stackoverflow if some one use servlet-context.xml ( Mixing thymeleaf and jsp files in Spring Boot ), where both jasper and thymeleaf coexist. But my requirement is how to include those attributes in pom.xml if I am using spring-boot-starter-web.
I was able to run both HTML and JSP page from embedded jar build inside Spring boot. But if you like to run it independently by copying the Jar in command prompt then you need to copy the JSP page folder structure as it will not be in the jar content and you need to change the pom file little bit so that the jar can add external content to it.
STEP 1: Add Thymeleaf and JSP dependencies
Add below dependencies to your pom.xml file
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<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>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
STEP 2: Project structure and file creation
Under source folder src/main/resources create folder templates, under that create sub-folder thymeleaf. And create a html file sample.html(say)
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Hello</title>
</head>
<body>
THYMELEAF PAGE: <p th:text="${name}"></p>
</body>
</html>
Under src/main/webapp/WEB-INF create sub-folder views. Under views create a jsp file, sample.jsp(say)
<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello</title>
</head>
<body>
JSP PAGE: Hello ${name}
</body>
</html>
STEP 3: In your application.properties set thymeleaf view names and JSP configuration for internal view resolution.
#tomcat-connection settings
spring.datasource.tomcat.initialSize=20
spring.datasource.tomcat.max-active=25
#Jasper and thymeleaf configaration
spring.view.prefix= /WEB-INF/
spring.view.suffix= .jsp
spring.view.view-names= views
spring.thymeleaf.view-names= thymeleaf
#Embedded Tomcat server
server.port = 8080
#Enable Debug
debug=true
management.security.enabled=false
STEP 4: Create controller for serving Thymeleaf and JSP pages:
package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
#Controller
public class TestController {
#RequestMapping(value="/jasper", method=RequestMethod.GET)
public String newjasper(Map<String, Object> m, String name){
//System.out.print("-- INSIDE JSP CONTROLER ------");
m.put("name", name);
return "views/sample";
}
#RequestMapping(value="/thymeleaf", method=RequestMethod.GET)
public String newthymeleaf(Map<String, Object> m, String name){
//System.out.print("-- INSIDE HTML CONTROLER ------");
m.put("name", name);
return "thymeleaf/sample";
}
}
STEP 5: Some cases you may required to create a configuration class SpringConfig.class (say) for view resolution for JSP pages. But optional, I don't use it in my configuration file.
import org.springframework.web.servlet.view.JstlView;
#Configuration
public class SpringConfig {
#Value("${spring.view.prefix}")
private String prefix;
#Value("${spring.view.suffix}")
private String suffix;
#Value("${spring.view.view-names}")
private String viewNames;
#Bean
InternalResourceViewResolver jspViewResolver() {
final InternalResourceViewResolver viewResolver = new
InternalResourceViewResolver();
viewResolver.setPrefix(prefix);
viewResolver.setSuffix(suffix);
viewResolver.setViewClass(JstlView.class);
viewResolver.setViewNames(viewNames);
return viewResolver;
}
}
STEP 6: Testing application for both jsp and html.
When you hit this url in your browser: http://localhost:8080/thymeleaf?name=rohit . This will open our sample.html file with parameter name in center of page and with this url: http://localhost:8080/jasper?name=rohit will open sample.jsp page with parameter name in center.
from the viewresover javadoc.
Specify a set of name patterns that will applied to determine whether
a view name returned by a controller will be resolved by this resolver
or not.
In applications configuring several view resolvers –for example, one
for Thymeleaf and another one for JSP+JSTL legacy pages–, this
property establishes when a view will be considered to be resolved by
this view resolver and when Spring should simply ask the next resolver
in the chain –according to its order– instead.
The specified view name patterns can be complete view names, but can
also use the * wildcard: "index.", "user_", "admin/*", etc.
Also note that these view name patterns are checked before applying
any prefixes or suffixes to the view name, so they should not include
these. Usually therefore, you would specify orders/* instead of
/WEB-INF/templates/orders/*.html.
Specify names of views –patterns, in fact– that cannot be handled by
this view resolver.
These patterns can be specified in the same format as those in
setViewNames(String []), but work as an exclusion list.
viewResolver.setViewNames(viewNames);

why deploy tomcat7-maven-plugin with /manager/text messed up the context

If I change the path to anything different from "/" I get 404 error. I mean, if use
<plugin><groupId>org.apache.tomcat.maven</groupId><artifactId>tomcat7-maven-plugin</artifactId><path>/any_word</path><url>http://localhost:8080/manager/text</url>
in the below pom.xml then I will get
http://localhost:8080/authenticate 404 (Not Found)
It seems to me that there is certain issue with context path but I don't know how to fix it. I managed to make the application run in my local Tomcat but certainly I can't apply same approach in production. I deleted the "/" default found in Tomcat. Then, I took away "any_word" and just left "/" in pom.xml. It makes the application run perfectly but, as you can imagine, I can't deploy the application to the root path "/" in production because the server administrator will require obviously from me a specific and unique context path.
I added below all steps and sources relevants to my question. I ordered from the less important to more important from my personal perspective (I do believe it may be something wrong with pom.xml but I may be wrong and I must change some spring configuration or Tomcat Server property).
Take a note that, in browser I do see localhost:8080/calories-tracker no matter if I start/deploy "mvn clean install tomcat7:run-war" instead of "mvn tomcat7:deploy" in a previous started Tomcat server.
1 - In TomcatManager (http://localhost:8080/manager/html/list)
I undeployed “/”
2 - Command Prompt of Windows
C:> mvn tomcat7:deploy
3 - Profile("development")
#Configuration
#Profile("development")
#EnableTransactionManagement
public class DevelopmentConfiguration {
#Bean(name = "datasource")
public DriverManagerDataSource dataSource() {
#Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DriverManagerDataSource dataSource) {
4 - catalina.properties
spring.profiles.active=development
5 - settings.xml
<servers>
<server>
<id>tomcat8</id>
<username>admin</username>
<password>admin</password>
</server>
</servers>
6 - WebAppInitializer
public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{RootContextConfig.class, DevelopmentConfiguration.class, TestConfiguration.class,
AppSecurityConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] {ServletContextConfig.class};
}
#Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
7 - Web.xml
<web-app>
<display-name>Archetype Created Web Application</display-name>
<welcome-file-list>
<welcome-file>/resources/calories-tracker.html</welcome-file>
</welcome-file-list>
</web-app>
8- Pom.xml
<build>
<finalName>calories-tracker</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>${java-version}</source>
<target>${java-version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/</path>
<url>http://localhost:8080/manager/text</url>
<server>tomcat8</server>
<keystoreFile>${basedir}/other/keystore.jks</keystoreFile>
<keystorePass>secret</keystorePass>
</configuration>
</plugin>
</plugins>
</build>
***Added few minutes after created the question
The original project can be downlowed from https://github.com/jhades/spring-mvc-angularjs-sample-app. I just made the changes wrote above with Tomcat and Pom.
you need to add $location to your controllers.
angular.module('common', ['ngMessages'])
.controller('BaseFormCtrl', ['$scope', '$http', '$location', function ($scope, $http, $location) {
var fieldWithFocus;
$scope.path = $location.absUrl().split('/')[3];
$scope.vm = {
submitted: false,
errorMessages: []
};
then you store the context path in a scope variable and you can use it at the specified controller context. maybe it's not the neatest way, but it works!
edit:
first you need to change in login page the following tag for require
<script type="text/javascript" data-main="./js/run-loggin-app"
src="../bower_components/requirejs/require.js"></script>
then, if you like to see it in action
<link rel="stylesheet" type="text/css" href="/{{path}}/resources/bower_components/pure/pure.css">
<link rel="stylesheet" type="text/css" href="/{{path}}/resources/bower_components/pure/grids-responsive.css">
<link rel="stylesheet" type="text/css" href="/{{path}}/resources/public/css/pure-theme.css">
<link rel="stylesheet" type="text/css" href="/{{path}}/resources//public/css/calories-tracker.css">
but this will take some milliseconds to load which means that you will see for an instance the page without any css, till angular loads.
you can see the difference you change the links to be of relative path.
<link rel="stylesheet" type="text/css" href="../bower_components/pure/pure.css">
<link rel="stylesheet" type="text/css" href="../bower_components/pure/grids-responsive.css">
<link rel="stylesheet" type="text/css" href="../public/css/pure-theme.css">
<link rel="stylesheet" type="text/css" href="../public/css/calories-tracker.css">
you can start by changing the links first and the POST/GET endpoints and then decide what to do with the styling links.

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.

CSS not loading in Spring Boot

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]

Issue with creating Custom Tag Libraries in CQ5.5

I am creating a custom tag library and want to use it in one of my components. I have created a bundle which includes tag hello class which is extending TagSupport class and i created tags.tld file under my resource folder
In my pom.xml, I have used resource tag to include my .tld file in the generated jar file.
Here is my java class and tld file
TAG CLASS:-
package com.cb;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
/**
* Simple tag example to show how content is added to the
* output stream when a tag is encountered in a JSP page.
*/
public class Hello extends TagSupport {
private String name=null;
/**
* Getter/Setter for the attribute name
as defined in the tld file
* for this tag*/
public void setName(String value){
name = value;
}
public String getName(){
return(name);
}
/**
* doStartTag is called by the JSP container
when the tag is encountered */
public int doStartTag() {
try {
JspWriter out = pageContext.getOut();
out.println("<table border=\"1\">");
if (name != null)
out.println("<tr><td> Welcome <b>" + name +
"</b> </td></tr>");
else
out.println("<tr><td> Hello World </td></tr></table>");
} catch (Exception ex) {
throw new Error("All is not well in the world.");
}
// Must return SKIP_BODY because we are not
//supporting a body for this
// tag.
return SKIP_BODY;
}
/**
* doEndTag is called by the
JSP container when the tag is closed */
public int doEndTag(){
return EVAL_PAGE;
}
}
I also successfully installed the bundle in my felix console without having any error. Then i written custom tag in my jsp as below
JSP:-
<%#include file="/libs/foundation/global.jsp"%>
<%# page import="com.testcb.TestCustomTag"%>
<%# taglib prefix="mytest" uri="http://cs.test.com/bundles/cq/1.8"%>
<mytest:hello name="sachin"></mytest:hello>
I am getting the like "org.apache.sling.api.scripting.ScriptEvaluationException: org.apache.sling.scripting.jsp.jasper.JasperException: /apps/test/components/content/test/test.jsp(4,0) Unable to load tag handler class "com.cb.Hello" for tag "mytest:hello".
The same code is working fine in my apache tomcat server without having any issue. I am getting the error when i incorporate it in CQ.
What am i doing here? Is there any config i need to do in OSGI console to make it available?
UPDATE:
There was some problem with package name. Now Sling can read my tag handler class after i renamed the package name.
The error "Unable to load tag handler class" also has gone.
Now i am getting error as "org.apache.sling.api.scripting.ScriptEvaluationException: javax.servlet.ServletException: javax.servlet.jsp.JspException: com.testcb.TestCustomTag cannot be cast to javax.servlet.jsp.tagext.Tag"
I have the following dependency in pom.xml
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
</dependency>
And Here is my tld
<?xml version="1.0" encoding="ISO-8859-1" ?>
<taglib 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/web-jsptaglibrary_2_0.xsd" version="2.0">
<description>My tag library123</description>
<tlib-version>1.0</tlib-version>
<short-name>TagLib-Test</short-name>
<uri>http://cs.test.com/bundles/cq/1.0</uri>
<jspversion>2.1</jspversion>
<tag>
<name>testcustomtag</name>
<tagclass>com.testcb.TestCustomTag</tagclass>
<bodycontent>empty</bodycontent>
<info>This is a simple hello tag</info>
<attribute>
<name>name</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
Is there any problem with jsp version?
Please guide me to resolve.
Thanks
The tags.tld file needs to be under the META-INF folder. If you don't have it already you can create one under your resources source folder.
Yes, It is working as expected after i removed tag in pom.xml. This was the cause issues. :)
Thanks !

Resources