Spring Thymeleafs Template Engine error during template parsing - spring

I can see there are a few question already asked in there, but still I can't find any solution to fix my issue. I am using Spring boot Thymeleafs Template Engine to parse value attribute with Spring Context. Then, I can process PDF generated with flying-saucer-pdf.
I can say the problem is because String is passed to parameter and it is not referent to html file.
Error description:
2022-10-11T16:45:58.209+0700 ERROR [THYMELEAF][http-nio-8080-exec-2] Exception processing template "world-check-report": An error happened during template parsing (template: "applicationprocess/world-check-report.html")
org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "applicationprocess/world-check-report.html")
at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:235) ~[thymeleaf-3.0.11.RELEASE.jar:3.0.11.RELEASE]
at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parseStandalone(AbstractMarkupTemplateParser.java:100) ~[thymeleaf-3.0.11.RELEASE.jar:3.0.11.RELEASE]
at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:649) ~[thymeleaf-3.0.11.RELEASE.jar:3.0.11.RELEASE]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1098) [thymeleaf-3.0.11.RELEASE.jar:3.0.11.RELEASE]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1059) [thymeleaf-3.0.11.RELEASE.jar:3.0.11.RELEASE]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1048) [thymeleaf-3.0.11.RELEASE.jar:3.0.11.RELEASE]
at com.aeon.webadmin.controller.AssessmentController.getWorldCheckStatus(AssessmentController.java:820) [classes/:1.3.5]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_333]
Caused by: java.io.FileNotFoundException: ClassLoader resource "applicationprocess/world-check-report.html" could not be resolved
at org.thymeleaf.templateresource.ClassLoaderTemplateResource.reader(ClassLoaderTemplateResource.java:130) ~[thymeleaf-3.0.11.RELEASE.jar:3.0.11.RELEASE]
My Controller:
#PostMapping(value = "/world-check-info")
public ObjResponseEntity<AmlApplyLoan> getWorldCheckStatus(#RequestBody String aln_id) {
try {
HttpHeaders headers = new HttpHeaders();
AssessmentController assessmentController = new AssessmentController();
ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setPrefix("applicationprocess/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("XHTML");
templateResolver.setCharacterEncoding("UTF-8");
TemplateEngine templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
Context ctx = new Context();
ctx.setVariable("message", "TESTING");
//error here when parsing
String htmtContent = templateEngine.process("world-check-report", ctx);
return ObjResponseFactory.success();
} catch (Exception e) {
e.printStackTrace();
}
return ObjResponseFactory.fail();
Template File:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<div class="content-wrapper" style="padding-left: 120px; font-family: sans-serif;">
<h2 class="page_title" th:text="${message}"></h2>
<h2>CASE REPORT</h2>
</div>
</body>
</html>

Related

javax.servlet.ServletException: java.lang.ClassNotFoundException: com.mysql.cj.jbdc.Driver

I created a j2ee web app and converted to maven project, but I have this error
javax.servlet.ServletException: java.lang.ClassNotFoundException: com.mysql.cj.jbdc.Driver.
I've tried all solutions : maven dependecy, paste the jar file manually in web app lib, paste the jar file manually in Tom cat lib , added the path on build path but still havin the same problem.
I am using Eclipse
Any help please thank a lot.
the conn class
public class DbCon {
private static Connection connection = null;
public static Connection getConnection() throws ClassNotFoundException, SQLException {
if(connection==null) {
Class.forName("com.mysql.cj.jbdc.Driver");
connection = DriverManager.getConnection("jbdc:mysql://localhost:3306/ecommerce_cart","root","");
System.out.print("connected");
}
return connection;
}
}
I call in index.jsp
<%# page import="cn.techtutorial.connection.DbCon" %>
<!DOCTYPE html>
<html>
<head>
<%# include file="includes/head.jsp" %>
<title>Shopping Cart Home</title>
</head>
<body>
<%# include file="includes/navbar.jsp" %>
<% out.print(DbCon.getConnection()); %>
<%# include file="includes/footer.jsp" %>
</body>
</html>
But it gives me this error:
javax.servlet.ServletException: java.lang.ClassNotFoundException: com.mysql.cj.jbdc.Driver.
Please help guys thanks

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.

ControllerAdvice configuration not working

I am having issues trying to get the controller advice working, Below is my code snippet. I have tired most of the answers on stackoverflow but havent had any success. I would appreciate if someone could guide me with this.
```
#ControllerAdvice
public class PollCoreExceptionHandler {
#ExceptionHandler(Exception.class)
public #ResponseBody ResponseException handleIllegalArgumentServiceException(
final Exception illegalArgumentServiceException) {
System.out.println("Error handling called ");
final ResponseException responseException = new ResponseException();
responseException.setErrorMessage("Error handler called " + illegalArgumentServiceException.getMessage());
return responseException;
}
}
```
My controller
```
#RequestMapping(value = "/login", method = RequestMethod.POST)
public UserDTO loginUser(#RequestBody final UserDTO userDto) throws Exception {
throw new Exception("error testing ");
}
```
Output
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>Error 500 Server Error</title>
</head>
<body>
<h2>HTTP ERROR 500</h2>
<p>Problem accessing /ws/user/login. Reason:
<pre> Server Error</pre>
</p>
<h3>Caused by:</h3>
<pre>javax.servlet.ServletException: org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.Exception: error testing
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:146)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132)
at org.eclipse.jetty.server.Server.handle(Server.java:564)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:317)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:251)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:279)
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:110)
at org.eclipse.jetty.io.ChannelEndPoint$2.run(ChannelEndPoint.java:124)
at org.eclipse.jetty.util.thread.Invocable.invokePreferred(Invocable.java:128)
at org.eclipse.jetty.util.thread.Invocable$InvocableExecutor.invoke(Invocable.java:222)
at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouK
</pre>
<h3>Caused by:</h3>
<pre>java.lang.Exception: error testing
at com.multi.enterprise.poll.core.controllers.UserController.loginUser(UserController.java:65)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet
I also see this when my app boots up.
2017-04-30 15:07:05,488 [main] INFO annotation.ExceptionHandlerExceptionResolver:273 () - Detected #ExceptionHandler methods in controllerAdvisor
2017-04-30 15:07:05,488 [main] INFO annotation.ExceptionHandlerExceptionResolver:273 () - Detected #ExceptionHandler methods in pollCoreExceptionHandler
2017-04-30 15:07:05,585 [main] INFO servlet.DispatcherServlet:508 () - FrameworkServlet 'dispatcher': initialization completed in 1213 ms

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.

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]

Resources