I'm starting with a project in springboot, and I've an error that I've never seen before and I have not been able to solve it, it is with the thymeleaf dependency is not working, im working with intellij idea community edition. it dont let me use the th:text, please see the image. i have deleted the project and redownloaded several times, delete the m2 folder and nothing works for me.
this is my controller:
#Controller
public class IndexController {
#GetMapping(value = "/index")
public String index(Model model){
model.addAttribute("titulo", "nombre");
return "index";
}
}
this is de index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>th:text="${titulo}"</title>
</head>
<body>
</body>
</html>
when i run the code localhost don't show me the correct information, I already have the dependency installed.
enter image description here
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
enter image description here
Your template is being served as a static resource. The controller has a mapping for /index but you have accessed http://localhost:8080. Either change the mapping to #GetMapping("/") or access http://local host:8080/index. You should also check the location of index.html in your project. It should be in src/main/resources/templates.
Related
I just create simple template by the help of thmeleaf, When I try to
access the variable from controller class by the help of variable
Expression , But I get Issue on variable expression ,In the time of
variable expression access . Showing below type of error
cannot Resolve variable name
My variable name is today which I define in my controller class
Homecontroller.kt
package com.nilmani.thymeleafdemo.controller
import org.springframework.web.bind.annotation.RestController
import org.thymeleaf.ITemplateEngine
import org.thymeleaf.context.WebContext
import java.text.SimpleDateFormat
import java.util.*
import javax.servlet.ServletContext
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
#RestController
class HomeController : IGTVGController() {
#Throws(Exception::class)
fun process(request:HttpServletRequest,response: HttpServletResponse,
servletContext: ServletContext,templateEngine: ITemplateEngine){
val dateForm:SimpleDateFormat= SimpleDateFormat("dd-mm-yyyy")
val calendar:Calendar = Calendar.getInstance()
val ctx : WebContext = WebContext(request,response,servletContext,request.locale)
ctx.setVariable("today",dateForm.format(calendar.time))
templateEngine.process("home",ctx,response.writer)
}
}
home.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Welcome TO our WebPage</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" media="all"
href="../../css/gtvg.css" th:href="#{/css/gtvg.css}" />
</head>
<body>
<p th:utext="#{home.welcome}">Welcome to our website</p>
<p>Today is: <span th:text= "${today}"></span></p>
</body>
</html>
error shows at this point below point
th:text= "${today}"
What is the reason for not support of variable expression . I already
added thymeleaf gradle depedency in my project.But the variable
expression not working
I don't know Kotlin, so I hope you can convert my Java answer to it.
I see you use #RestController, but if you are using Thymeleaf, use #Controller
You can have Spring Boot inject the Model class and add your attributes there
The easiest is to return a String value that represents the name of the Thymeleaf template.
Using all that, you get something like this:
#Controller
public class HomeController {
public String process(Model model) {
model.addAttribute("today", ...);
return "home"; //this refers to home.html like this
}
}
PS: You should not use Calendar anymore, see https://www.baeldung.com/java-8-date-time-intro for more info on the "new" date/time API introduced in Java 8.
I'm new to springboot. I want to create a class with #RequestMapping at class level. I have a static html file located resource/static/main/index.html
#Controller
#RequestMapping("/home")
public class HomeController {
#GetMapping
#ResponseBody
public String Welcome(){
return "Hello World";
}
#GetMapping("/message")
public String message(){
return "main/index.html";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1, user-scalable=yes">
<title>Hello Message!</title>
</head>
<body>
Welcome everyone!
</body>
</html>
http://localhost:8080/home display Hello World in my browser. When I enter http://localhost:8080/home/message, I get a 404 message, The origin server did not find a current representation for the target resource or is not willing to disclose that one exists. If I remove #RequestMapping("/home") from the class level then it works. My goal is to have mulitple #GetMapping and #RequestMapping at the class level
If you are using thymeleaf then try:
#GetMapping("/message")
public String message(){
return "main/index";
}
The index view location must be resources/templates
I am new to Thymeleaf. In jsp world I could change the theme of my Springboot Web Application using the following tags in "head" of a jsp:
<spring:theme code="stylesheet" var="themeName" />
<link href='<spring:url value="css/${themeName}"/>' rel="stylesheet" />
What should I write "as the exact equivalent of above" if I am going to use "Thymeleaf template" instead of jsp? I am using (and must use) spring boot (with web and data). Can someone please point me a way out?
Update
Adding more information.
I have my config and beans as per following:
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/resources/static/css**", "/resources/static/**", "/static/")
.setCacheControl(CacheControl.maxAge(2, TimeUnit.HOURS).cachePublic());
}
#Bean
public ThemeSource themeSource() {
ResourceBundleThemeSource themeSource = new ResourceBundleThemeSource();
themeSource.setBasenamePrefix("theme/");
return themeSource;
}
#Bean
public ThemeResolver themeResolver() {
CookieThemeResolver resolver = new CookieThemeResolver();
resolver.setDefaultThemeName("cosmo");
return resolver;
}
And also I have bunch of (e.g. Cosmo.BootStrap.min.css) under themes folder. When I select the theme name from JSP, the theme of my entire webapp gets changed.
In short, using Thymeleaf, in my "header.html fragment", I am trying to acheive something similar to this (${somename}) -
<link href="css/${somename}.css" rel="stylesheet" type="text/css" />
For now I am clueless. Please give some guidance.
You can always build dynamic URLs in Thymeleaf like:
<head th:with="themeName=${'stylesheet'}">
<link th:href="#{|/css/${themeName}|}" rel="stylesheet"/>
</head>
Now themeName can either be populated from the controller in the Model or ModelMap class, or computed in the template HTML.
So I am trying to host a Single Page Application alongside a normal REST API with spring.
What this means is that all requests that goes to the normal /api/ endpoints should be handled by the respective controller and all other requests should be directed to the resources in the folder /static/built
I have gotten this to work by catching all NoHandlerFoundExceptions and redirecting to either the js file or the html file. And then used a WebMvcConfigurer to map the static content.
But this all seems like a hack to me, so is there a less hacky way of doing it?
Managed to have React+ReactRouter app working by adding following mapping:
#Controller
public class RedirectController {
#GetMapping(value = {"/{regex:\\w+}", "/**/{regex:\\w+}"})
public String forward404() {
return "forward:/";
}
}
This was inspired by https://stackoverflow.com/a/42998817/991894
The easiest way I get my SPAs to work with a Spring backend API is to have 2 different controllers: one for the root index page of the SPA and the other controller is used to manage various RESTful API endpoints:
Here are my two controllers:
MainController.java
#Controller
public class MainController {
#RequestMapping(value = "/")
public String index() {
return "index";
}
}
MonitoringController.java
#RestController
#RequestMapping(value = "api")
public class MonitoringEndpoints {
#GetMapping(path = "/health", produces = "application/hal+json")
public ResponseEntity<?> checkHealth() throws Exception {
HealthBean healthBean = new HealthBean();
healthBean.setStatus("UP");
return ResponseEntity.ok(healthBean);
}
}
Notice how the API endpoint controller utilizes the '#RestConroller' annotation while the main controller utilizes the '#Conroller' annotation. This is because of how Thymeleaf utilizes it's ViewResolver. See:
Spring Boot MVC, not returning my view
Now go ahead and place your index.html page at src/main/resources/templates/index.html because Spring by default looks for your html pages within this location.
My index.html pages looks like this:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
<meta charset="UTF-8"/>
<title>EDP Monitoring Tool</title>
</head>
<body>
<!-- Entry point to our ReactJS single page web application -->
<div id="root"></div>
<script type="text/javascript" src="built/bundle.js"></script>
</body>
</html>
Not sure how you're wiring up your frontend, whether that is a ReactJS app or something but I believe this information would be helpful for you. Let me know if I can answer additional questions for you.
In addition, if you're using Webpack, you can set up the entry point of your JS files via the webpack.config.js file under the entry key so like so:
entry: ['./src/main/js/index.js']
I think you're looking for the term URL Rewrite.
E.g. https://getpostcookie.com/blog/url-rewriting-for-beginners/
I am trying to load the css file into jsp, it is not loading and showing the message Failed to load resource: the server responded with a status of 404 (Not Found).the following is my code
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Bootstrap Form With Spring Mvc Example</title>
<link href="<c:url value='/resources/css/bootstrap.css'/>" rel="stylesheet" media="screen">
</head>
in configuration class I have added the below code:
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
I have tried all the solutions, I did not find what's the wrong,can any one help me?
Try it this way:
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/css/**")
.addResourceLocations("/css/");
}
This assumes your directory structure is:
src
main
java
resources
css
webapp
The point is that you don't specify the resources level in your resource handler.
Is your css file in WebContent folder..Please check for it.And if your are using maven it must be in resources folder.If the folder structure is correct.
Please treat the jsp pages like html ..
paste your css file near your jsp folder.And try to access it using href directly instead of using c tag.
<link href="../css/bootstrap.css" rel="stylesheet" media="screen">
This approach is dirty one.But good for jsp pages integrated thymeLeaf kindof tools.
Edit your configuration class to inherit from WebMvcConfigurerAdapter as shown below. It solved my own problem after trying a lot of other options. Hope it would work for you.
public class Config extends WebMvcConfigurerAdapter{
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}