Closed. This question is not written in English. It is not currently accepting answers.
Stack Overflow is an English-only site. The author must be able to communicate in English to understand and engage with any comments and/or answers their question receives. Don't translate this post for the author; machine translations can be inaccurate, and even human translations can alter the intended meaning of the post.
Closed 5 days ago.
Improve this question
Este es el controller donde añado la variable con el model.addAttribute()
package com.sms.studentmanagemensystem.controller;
import com.sms.studentmanagemensystem.service.StudentService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class StudentController {
private StudentService studentService;
public StudentController(StudentService studentService) {
super();
this.studentService = studentService;
}
//métodos para manipular las vistas y modos de los estudiennte
#GetMapping("/students")
public String listStudents(Model model){
model.addAttribute("students", studentService.getAllStudents());
return "Student";
}
}
Aquí estoy intentando instanciarla con la sintaxi de thymeleaf ${attributeName}
type here<!DOCTYPE html>
<html lang="es" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Student Management System</title>
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap#4.0.0/dist/css/bootstrap.min.css"
integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous"
>
</head>
<body>
<div class="container">
<div class="row">
<h1> --Lista de estudiantes-- </h1>
</div>
<table class="table table-striped table-bordered">
<thead class="thead-dark">
<tr>
<th scope="col">Nombre</th>
<th scope="col">Apellido</th>
<th scope="col">Correo</th>
<th scope="col">Acción</th>
</tr>
</thead>
<tbody>
<tr th:each= "student : ${students}">
<th th:text="${student.firstName}"></th>
<th th:text="${student.lastName}"></th>
<th th:text="${student.email}"></th>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Este es mi pom.xml donde tengo añadida la dependencia de
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.sms</groupId>
<artifactId>StudentManagemenSystem</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>StudentManagemenSystem-SMS</name>
<description>StudentManagemenSystem-SMS</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
<version>2.7.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
ya intente cambiando la instancia a :
<tr th:each= "#{'student=?' + ${students}}">.
Pero sigue sin funcionar, les agradecería la ayuda.
Related
hello i am trying to build a web services for login page in springboot. When I run the project application all looks fine but problem is that instead of redirecting to "login.jsp" page controller return the string value "login". Any idea where i did wrong?
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-
4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.micro</groupId>
<artifactId>login-mvc</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>login-mvc</name>
<description>a micro service for login</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-catalina -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-catalina</artifactId>
<version>10.0.10</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
application properties
##port
server.port=9001
##DB Connection
spring.datasource.url= jdbc:mysql://localhost:3306/newdb?useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
##MVC view
spring.mvc.view.prefix=/WEB-INF/
spring.mvc.view.suffix= .jsp
spring.mvc.static-path-pattern=/resources/**
Controller
package com.micro.services;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class LoginController {
#RequestMapping("/login-page")
public String checkMVC() {
return "login";
}
}
SpringBootApplication :
package com.micro.services;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class LoginMvcApplication {
public static void main(String[] args) {
SpringApplication.run(LoginMvcApplication.class, args);
}
}
login.jsp
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css"
rel="stylesheet" integrity="sha384-
1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<title>Login Page</title>
</head>
<body>
<h1>Hello Friends I am learning WebServices!!!</h1>
<div>
<form action="/login" method="post">
<div><input type="text" name="userName" value=""></div>
<div><input type="text" name="password" value=""></div>
<div><input type="submit" name="login" value=""></div>
<div><input type="button" name="Register" value=""></div>
</form>
</div>
<!-- Optional JavaScript; choose one of the two! -->
<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"
integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
crossorigin="anonymous"></script>
<!-- Option 2: Separate Popper and Bootstrap JS -->
<!--
<script src="https://cdn.jsdelivr.net/npm/#popperjs/core#2.10.2/dist/umd/popper.min.js"
integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.min.js"
integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13"
crossorigin="anonymous"></script>
-->
</body>
</html>
Project:
file structure
Browser:
Output
#RestController <---------------
public class LoginController {
#RequestMapping("/login-page")
public String checkMVC() {
return "login";
}
The problem as I have marked in your code is that you have used #RestController, meaning it would parse the request and give back a response as the actual message body when you do return "login". So in the body of response it is just written the String "login".
What you need instead is #Controller which will work in context of Spring MVC, and when you do return "login", it will by default search for a page with the name login to return, so it would translate your login.jsp into some html code and would return this page to the client as a response.
Edit: There is another problem with your project as well. As indicated by the Spring boot doc, when you package your application as jar, there are problems with rendering jsp views.
Check this answer to see how you can configure it to work.
When running Tomcat I get this error:
It happened after I added jstl-1.2.jar to tomcat/webapps. I had to do it because I was getting
org.apache.jasper.JasperException: The absolute uri: [http://java.sun.com/jsp/jstl/core] cannot be resolved in either web.xml or the jar files deployed with this application
for a jsp with
<c:forEach items="${requestScope.users}" var="user" varStatus="loop">
<tr class="user" >
<td>${user.getFirstName()}</td>
<td class="item-name">${user.getLastName()}</td>
<td>${user.getEmail()}</td>
<td>${user.getAge()}</td>
</tr>
</c:forEach>
(that's what all SO answers suggested).
I also have
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
in my pom.xml.
the whole jsp:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'/>
<title>Some Web Page</title>
<%# include file = "/WEB-INF/views/shared/meta.jsp" %>
</head>
<body>
<%# include file = "/WEB-INF/views/shared/header.jsp" %>
<br/><br/><br/>
<div class = "home_panel">
<div class="table-container all-users-table">
<table class = "table" style="width:100%">
<thread>
<tr>
<th>First name</th>
<th>Last name</th>
<th>Email</th>
<th>Age</th>
<th>Gender</th>
</tr>
</thread>
<c:forEach items="${requestScope.users}" var="user" varStatus="loop">
<tr class="user" >
<td>${user.getFirstName()}</td>
<td class="item-name">${user.getLastName()}</td>
<td>${user.getEmail()}</td>
<td>${user.getAge()}</td>
<td>${user.getGender().name().toLowerCase()}</td>
</tr>
</c:forEach>
</table>
</div>
<div class="table-container videos-container">
<table class = "all-videos-table" style="width:100%">
<tr>
<th>Title</th>
<th>Description</th>
<th>URL</th>
<th>Added by</th>
<th>Posting date</th>
<th>Tags</th>
</tr>
<tr>
<td>Title</td>
<td>Description</td>
<td>
<div class = "video-link dark-button" onclick="">
https://youtube.com
</div>
</td>
<td>Jon</td>
<td>22/03/20</td>
<td>
<div class="tags-container">
<div class="red-button tag">
funny
</div>
<div class="red-button tag">
nature
</div>
<div class="red-button tag">
animals
</div>
</div>
</td>
</tr>
</table>
</div>
<iframe width="560" height="315" src="https://www.youtube.com/embed/xV83h4A9a9w"
frameborder="0" allow="accelerometer;
autoplay; encrypted-media;
gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</body>
</html>
I tried adding this web.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<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/web-app_2_4.xsd"
version="2.4">
<display-name>comediansappf</display-name>
<description>
Comedy videos app
</description>
<context-param>
<param-name>appname</param-name>
<param-value>comediansappf</param-value>
</context-param>
</web-app>
but still get either
or
if I renew the page several times.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>automotivepartsapp</groupId>
<artifactId>automotivepartsapp</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.4</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.taglibs</groupId>
<artifactId>taglibs-standard-impl</artifactId>
<version>1.2.5</version>
</dependency>
<!-- Add support for JSP ... get rid of Eclipse error -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-war-plugin -->
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.12.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
</dependencies>
<!-- Support for Maven WAR Plugin -->
<build>
<finalName>comedianswar2</finalName>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
I'm building an app using Spring boot. The problem started when I was trying to upload a file to server and thought this was a MultipartFile problem. But then I tried submitting a simple form with POST method to Spring #Controller and it got the same error. After hours of searching I could not find anything similar.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="/webjars/bootstrap/4.1.3/css/bootstrap.min.css"/>
<script type="text/javascript" src="/webjars/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="/webjars/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<title>Title</title>
</head>
<body>
<div class="container">
<div class="card">
<div class="card-body">
<div class="offset-3 col-6">
<form method="post"
action="/save">
<input type="text" class="form-control" name="name">
<input type="submit" class="btn btn-primary" value="Save">
</form>
</div>
</div>
</div>
</div>
</body>
</html>
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tantsurepertuaar</groupId>
<artifactId>tantsurepertuaar</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>tantsurepertuaar</name>
<description></description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--<dependency>-->
<!--<groupId>org.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-starter-security</artifactId>-->
<!--</dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<!--<dependency>-->
<!--<groupId>org.springframework.security</groupId>-->
<!--<artifactId>spring-security-test</artifactId>-->
<!--<scope>test</scope>-->
<!--</dependency>-->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>4.1.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Controller
package com.tantsurepertuaar.tantsurepertuaar.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
#Controller
public class TestController {
#RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(#RequestParam("name") String name) {
return "redirect:/";
}
}
When I check browser developer tools then I can see that in FormData there is a parameter called "name" and it has the entered value.
When I use GET method then I had no problems using #RequestParam.
Can it be that it has something to do with my project configuration or am I missing something completely here?
Thanks
The #RequestParam annotation you are using is for GET paramaters (passed via the URL), in order to retrieve the values of a POST parameter you have to use the #RequestBody annotation.
So your code should be like this:
#Controller
public class TestController {
#RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(#RequestBody("name") String name) {
return "redirect:/";
}
}
package com.tantsurepertuaar.tantsurepertuaar.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
#Controller
public class TestController {
#RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(#ModelAttribute String name) {
return "redirect:/";
}
}
try this?
if you redirect and want to use #Requestparam value that you get from 'form' in the redirect address ..
you need to use Redirectattributes .
#RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(#RequestParam("name") String name,RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("name","name");
return "redirect:/";
}
#RequestMapping(value = "/", method = RequestMethod.GET)
public String homeMethod(#ModelAttribue("name") String name){
return "name";
}
ModelAttribute will help you get that redirectflashattributes ..
I am using spring boot from spring.start.io
I have a problem where my view(thymleaf) doesn't render sec: tags to proper html
my pom.xml file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>security</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.2.0</thymeleaf-layout-dialect.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
My thymeleaf template
<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<th:block th:replace="~{fragments/main-page-fragments:: htmlHeadTag}">
</th:block>
<body>
<th:block th:replace="~{fragments/main-page-fragments:: navBar}">
</th:block>
<h1>Home</h1>
<div sec:authentication="name"></div>
<div sec:authorize="hasRole('ROLE_ADMIN')">
Za Admina
</div>
<div sec:authorize="hasRole('ROLE_USER')">
Za user
</div>
<div sec:authentication="name"></div>
<div sec:authorize="hasRole('ADMIN')">
Za Admina
</div>
<div sec:authorize="hasRole('USER')">
Za user
</div>
<th:block th:replace="~{fragments/main-page-fragments:: bootstrapScripts}">
</th:block>
</body>
</html>
And the result is this: http://imgur.com/a/t0uNv
What exactly have i done wrong? I even have intellisence for the roles, i linked the correct dependecies i link the sec xml tag as well.
You don't need to use sec: extension for simple Spring Security integration.
Conditional block depending on role:
<div th:if="${#request.isUserInRole('ADMIN')}">
Za Admina
</div>
Print username:
<div th:text="${#request.userPrincipal.name}"></div>
i think it's caused by not having the spring security dialect added to the TemplateEngine. I'm not sure how you set up your WebMvcConfig, but as an example:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.thymeleaf.extras.springsecurity4.dialect.SpringSecurityDialect;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
import org.thymeleaf.templateresolver.TemplateResolver;
import org.thymeleaf.templateresolver.UrlTemplateResolver;
#Configuration
#EnableScheduling
#EnableTransactionManagement
public class WebMvcConfig extends WebMvcConfigurerAdapter {
#Bean
public TemplateResolver templateResolver() {
TemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setPrefix("views/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML5");
templateResolver.setCacheable(false);
return templateResolver;
}
#Bean
public UrlTemplateResolver urlTemplateResolver() {
return new UrlTemplateResolver();
}
#Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.addTemplateResolver(templateResolver());
templateEngine.addTemplateResolver(urlTemplateResolver());
templateEngine.addDialect(new SpringSecurityDialect());
return templateEngine;
}
#Bean
public ViewResolver thymeleafViewResolver() {
ThymeleafViewResolver vr = new ThymeleafViewResolver();
vr.setTemplateEngine(templateEngine());
vr.setCharacterEncoding("UTF-8");
vr.setOrder(Ordered.HIGHEST_PRECEDENCE);
return vr;
}
}
Greetings
Marian
#Edit:
I added a complete Example of an WebMvcConfig. For this Example the Views would be located in Resources/views, but you can ofc set it up however you'd like to.
Here i am using spring boot, hibernate and sql server database.
the problem is, .css is not loading.
if i am not integrate with hibernate then .css is loading perfectly.
i don't understand why .css is not loading when i am integrate with hibernate ?
please give the solution
Project Structure
pom.xml
4.0.0
<groupId>com.example</groupId>
<artifactId>AngularIntegration</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>AngularIntegration</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- Optional, for bootstrap -->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.7</version>
</dependency>
<!-- Tomcat embedded container-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>net.sourceforge.jtds</groupId>
<artifactId>jtds</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
SchoolController.java
package com.nd.controller;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class SchoolController {
#RequestMapping("/")
public String welcome(Map<String, Object> model) {
model.put("message", "All Students");
return "welcome";
}
}
DBConfiguration.java
package com.nd.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
#Configuration
#EnableWebMvc
#ComponentScan
public class DBConfiguration {
#Bean
public HibernateJpaSessionFactoryBean sessionFactory(){
return new HibernateJpaSessionFactoryBean();
}
}
application.properties
spring.datasource.url=jdbc:jtds:sqlserver://SQLSERVER/abc
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-net.sourceforge.jtds.jdbc.Driver
welcome.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>AngularJS Example</title>
<link rel="stylesheet" href="/css/school_style.css" type="text/css"/>
</head>
<body>
<div id="main_container">
<div id="content_container">
<div id="content">
<div id="contentborder">
<div class="content_head">Class Students</div>
<form method="post" name="frm" id="frm">
<table align="center" cellpadding="2" cellspacing="2" class="table_border" width="90%">
<tr>
<br></br>
<td class="td_line" align="right" width="50%"><b>Class : </b></td>
<td class="td_line" align="left" width="50%">
<select size="1" name="cl" id="cl" class="validate[required]">
<option value="">Select</option>
<option th:each="clazz : ${allClasses}" value="${clazz.classID}">
<span th:text="${clazz.className}"></span>
</option>
</select>
</td>
</tr>
<tr>
<td class="td_line" align="right" width="50%"><b>Section :</b></td>
<td class="td_line" align="left" width="50%">
<select size="1" name="section" id="section" class="validate[required]">
<option value="">Select</option>
</select>
</td>
</tr>
<tr>
<td class="td_line" align="right" width="50%"><b>Students :</b></td>
<td class="td_line" align="left" width="50%">
<select size="1" name="term" id="term" onClick="return valid()" class="validate[required]">
<option value="">Select</option>
</select>
</td>
</tr>
<tr>
<td colspan="2" align="center"><br></br>
<input type="submit" class="submit" value="Submit"/>
<input type="reset" class="submit" value="Reset"/>
</td>
</tr>
</table>
</form>
</div>
</div>
</div>
</div>
</body>
</html>