Error when run: http://localhost:8080 - spring

Current I have 1 bug when I run 1 project of Spring
1- Create class common: BlogMvcApplication.java
package blog;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class BlogMvcApplication {
public static void main(String[] args) {
SpringApplication.run(BlogMvcApplication.class, args);
}
}
2- Create class control: HomeController.java
package blog.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class HomeController {
#RequestMapping("/")
public String index() {
return "index";
}
}
3- view: index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>Blog</title>
</head>
<body>
<h1>Welcome to Spring MVC</h1>
Now is: <b th:text="${execInfo.now.time}"></b>
</body>
</html>
Error when access http://localhost:8080 is :
2017-03-02 00:55:41.931 ERROR 1068 --- [nio-8080-exec-1] org.thymeleaf.TemplateEngine : [THYMELEAF][http-nio-8080-exec-1] Exception processing template "index": Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers
2017-03-02 00:55:41.958 ERROR 1068 --- [nio-8080-exec-1] 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: Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers] with root cause
org.thymeleaf.exceptions.TemplateInputException: Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers
at org.thymeleaf.TemplateRepository.getTemplate(TemplateRepository.java:246) ~[thymeleaf-2.1.5.RELEASE.jar:2.1.5.RELEASE]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1104) ~[thymeleaf-2.1.5.RELEASE.jar:2.1.5.RELEASE]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1060) ~[thymeleaf-2.1.5.RELEASE.jar:2.1.5.RELEASE]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1011) ~[thymeleaf-2.1.5.RELEASE.jar:2.1.5.RELEASE]
I think error because duplicate port 8080 when start
Please helpme fix bug this
Thanks!

I don't think this error cause by duplication on port. If it is the issue then you cannot start your application and will see message like this: ".... port 8080 failed to start".
It seen like your index.html cannot be found at default location:/src/main/resources/templates/index.html when thymeleaf engine try to parse your requested template.
Hope it helps.

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

How to include Spring Security in a spring boot application

I am working of a spring boot application. After developing the application, we are now trying to include spring security in our application.
I have included the following code:
html code:
<li th:if="${#authorization.expression('!isAuthenticated()')}">
<a th:href="#{/login}" th:text="#{navbar.login.text}" />
</li>
Java code:
package com.devopsbuddy.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private static final String[] PUBLIC_MATCHERS = {
"/webjars/**",
"/css/**",
"/js/**",
"/images/**",
"/",
"/about/**",
"/contact/**",
"/error/**/*"
};
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(PUBLIC_MATCHERS).permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").defaultSuccessUrl("/payload")
.failureUrl("/login?error").permitAll()
.and()
.logout().permitAll();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("password")
.roles("USER");
}
}
when I try to hit the url:
http://localhost:8080/
I am getting the below error on screen:
**36673 [http-nio-8080-exec-2] ERROR org.thymeleaf.TemplateEngine - [THYMELEAF][http-nio-8080-exec-2] Exception processing template "user/login": Exception evaluating SpringEL expression: "#authorization.expression('!isAuthenticated()')" (template: "common/navbar" - line 24, col 25)
org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "#authorization.expression('!isAuthenticated()')" (template: "common/navbar" - line 24, col 25)
at org.thymeleaf.spring5.expression.SPELVariableExpressionEvaluator.evaluate(SPELVariableExpressionEvaluator.java:290)
at org.thymeleaf.standard.expression.VariableExpression.executeVariableExpression(VariableExpression.java:166)
at org.thymeleaf.standard.expression.SimpleExpression.executeSimple(SimpleExpression.java:66)
at org.thymeleaf.standard.expression.Expression.execute(Expression.java:109)
at org.thymeleaf.standard.expression.Expression.execute(Expression.java:138)
at org.thymeleaf.standard.expression.Expression.execute(Expression.java:125)
...
...
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1011E: Method call: Attempted to call method expression(java.lang.String) on null context object
at org.springframework.expression.spel.ast.MethodReference.throwIfNotNullSafe(MethodReference.java:153)
at org.springframework.expression.spel.ast.MethodReference.getValueRef(MethodReference.java:82)
at org.springframework.expression.spel.ast.CompoundExpression.getValueRef(CompoundExpression.java:67)
at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:88)
at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:111)
at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:328)
at org.thymeleaf.spring5.expression.SPELVariableExpressionEvaluator.evaluate(SPELVariableExpressionEvaluator.java:263)
... 102 common frames omitted
36673 [http-nio-8080-exec-2] ERROR 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.TemplateProcessingException: Exception evaluating SpringEL expression: "#authorization.expression('!isAuthenticated()')" (template: "common/navbar" - line 24, col 25)] with root cause
org.springframework.expression.spel.SpelEvaluationException: EL1011E: Method call: Attempted to call method expression(java.lang.String) on null context object
at org.springframework.expression.spel.ast.MethodReference.throwIfNotNullSafe(MethodReference.java:153)
at org.springframework.expression.spel.ast.MethodReference.getValueRef(MethodReference.java:82)
at org.springframework.expression.spel.ast.CompoundExpression.getValueRef(CompoundExpression.java:67)**
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>2.1.2.RELEASE</version>
</dependency>
I am new to Thymeleaf and Spring security. So not sure why the Spring security is failing.
If i comment the line with authorization.expression(), it works.
I have shared the code at https://github.com/azaveri7/devopsbuddy in branch security.
Please advise.
please consider this as a suggestion, not an answer. previously I also went through this but hard to figure it out. then I decided to go through spring's automatic configurations. I only used this library -
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
and then spring provided the login URL, login page, logout URL etc.. I only wrote the userdetailsService. and in my case, I also wrote a custom filter also.
The spring security is 5.0.9 in your pom that extend the spring-boot-starter-parent 2.0.6
BUT thymeleaf-extras-springsecurity4 is still spring security 4, so you need to upgrade the thymeleaf-extras to
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
I have the below to check if user is not logged-in or not
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
....
<span sec:authorize="not isAuthenticated()">
You are not logged in - click <a th:href="#{/login}">login</a>
</span>
...

error with spring template parsing

I started from new Spring Boot project included Web, Devtools, JPA and Mustache modules.
I have simple controller:
package com.example.elephant;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.HashMap;
import java.util.Map;
#Controller
public class IndexController {
#GetMapping("/")
public ModelAndView index() {
Map<String, String> model = new HashMap<>();
model.put("name", "Spring");
System.out.println("11111111111111111111");
return new ModelAndView("index",model);
}
}
and simple template /resources/templates/index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{name}}
</body>
</html>
application class:
package com.example.elephant;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ElephantApplication {
public static void main(String[] args) {
SpringApplication.run(ElephantApplication.class, args);
}
}
Application log:
2018-04-24 15:09:11.333 INFO 7402 --- [ restartedMain] c.example.elephant.ElephantApplication : Started ElephantApplication in 5.906 seconds (JVM running for 6.477)
2018-04-24 15:09:29.231 INFO 7402 --- [nio-8036-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-04-24 15:09:29.232 INFO 7402 --- [nio-8036-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2018-04-24 15:09:29.252 INFO 7402 --- [nio-8036-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 19 ms
11111111111111111111
All ok, but I have 404 error. It seems I have a problem with template parsing but I can't understand why.
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Apr 24 15:09:29 MSK 2018
There was an unexpected error (type=Not Found, status=404).
No message available
You have to rename your template file to:
index.mustache
The file ending has changed with Spring Boot 2 from html to mustache:
https://github.com/spring-projects/spring-boot/issues/8997

Unable to load the spring beans inside the webapplication

I am having a helper class inside my web application which is responsible to invoke a method on a spring bean.
Below is the class definition:
package org.learning.spring.remoting;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ClientInvoker {
public static int sum(int a, int b) {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:client-beans.xml");
Calculation calculation = (Calculation) context.getBean("calculationBean");
return calculation.add(a, b);
}
}
Inside my jsp below is the code which invokes the function on ClienInvoker
<%#page import="org.learning.spring.remoting.ClientInvoker"%>
<%
int a=Integer.parseInt(request.getParameter("number"));
int b=Integer.parseInt(request.getParameter("number"));
out.print("cube of "+ClientInvoker.sum(a, b));
%>
When I run the web application, I am getting the below exception:
org.apache.jasper.JasperException: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [client-beans.xml]; nested exception is java.io.FileNotFoundException: class path resource [client-beans.xml] cannot be opened because it does not exist
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:555)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:476)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Basically, its not loading the client-beans.xml file which I have placed under the WEB-INF directory.
Can someone let me know where I am going wrong.

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

Resources