I tried to write my Spring Controller, using Thymeleaf, for a simple code sharing platform. So I wrote these methods
#PostMapping(value = "/api/code/new")
#ResponseBody
public String addNewCode(#RequestBody RequestCodeDTO code, Model model) {
CodeSnippet codeSnippet = new CodeSnippet();
codeSnippet.setCode(code.getCode());
codeSnippet.setDate("Jul 17, 2022");
model.addAttribute("code", codeSnippet);
return "";
}
#GetMapping(value = "/code/new")
public String returnNewCode(Model model){
return "CodeSnippet";
}
And my CodeSnippet.html is like this
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://thymeleaf.org" lang="en">
<head>
<title>Code</title>
</head>
<body>
<span id="load_date" th:text="${code.getDate()}">date</span>
<pre id="code_snippet" th:text="${code.getCode()}">code</pre>
</body>
</html>
But when I try to make this get request, I reseive "org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/CodeSnippet.html]")".
I tried to change tags of html file, change gradle build file, but it all was in vain.
Related
I am trying to practice SAP Hybris basic flow and while hitting the URL from the controller I am getting a "server error" as the response as shown below.
The controller looks something like this:
#Controller
public class NewCustomerController {
#RequestMapping(value = "/custid", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public String getCustomerNameFromCustId(#RequestBody final Model model){
final List<NewCustomerData> nameList = newCustomerFacade.getCustomerNamefromID();
model.addAttribute("nameList",nameList);
return ControllerConstants.Views.Pages.NewCustomer.CustId;
}
}
The JSP page "custid.jsp" looks something like this:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib prefix="" tagdir="" %>
<html>
<head>
<title>Customer ID detail</title>
</head>
<body>
<h1>This page displays the name of the customer based on customer ID</h1>
<h3>The name of the customer is ${nameList}.<h3>
</body>
</html>
In the dao layer, when I evaluate the call to execute the query, I get this error:
Can anyone help me please what am I doing wrong? I am stuck on this since 2 days now.
My registration is successful. a notification is sent to the mail with the text about the request to follow the link, after which the account is activated. Everything is fine, but it is impossible to translate this text into a template so that the variables should be stored in it, which should be sent to the post office, but I don’t understand how to place thymeleaf from the java code
user.getUsername()
user.getActivationCode()
in my case they are returned in the same form, they do not give out the value of the user to which they correspond
public void addUser(User user) throws Exception {
User userFromDb = repository.findByUsername(user.getUsername());
if (userFromDb != null) {
throw new Exception("User exist");
}
user.setRoles(new String[]{"USER"});
user.setActive(false);
user.setActivationCode(UUID.randomUUID().toString());
repository.save(user);
if (!org.springframework.util.StringUtils.isEmpty(user.getEmail())) {
//TODO: move to template
String message = String.format(
"Hello," + user.getUsername() + "!\n" + "Welcome. Please, visit http://aa/activate-account/%s",
user.getActivationCode());
mailSenderService.send(user.getEmail(), "Activation code", message);
}
}
Hello Dear ${user.getUsername}
Welcome. Please, visit http://aa.ru/activate-account/%s
%{user.getActivationCode()}
Thanks
my thymeleaf
I am trying to read this file through Context and submit as message in the send method
public void send(String emailTo, String subject, String message){
SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setFrom(username);
mailMessage.setTo(emailTo);
mailMessage.setSubject(subject);
mailMessage.setText(message);
mailSender.send(mailMessage);
}
i get
Hello Dear ${user.getName()}
Welcome. Please, visit http://aa.ru/activate-account/%s
%{user.getActivationCode()}
Thanks
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.1.RELEASE</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<p>Hello Dear,laza</p><p>Welcome.Please visit, http://aa.ru/activate-account/199572cc-17fe-4412-be7b-e54568b0cdb1</p><p> Thanks</p>
</body>
</html>
this is what comes to me in the mail with tags
I get something, but I get all the html code because I use Contex, how can I get around this?
What you are trying to is explained in here Please follow this link and apply the idea to your situation. Sample HTML template is as follows:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:remove="all">Template for HTML email</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p th:text="${'Hello Dear,' + user.getUsername}">
Hello Dear John Doe
</p>
<p th:text="${'Welcome.Please visit, http://aa.ru/activate-account/' + user.getActivationCode}">
Welcome. Please visit http://aa.ru/activate-account/blahblah
</p>
<p>
Thanks
</p>
</body>
</html>
i am new to Spring Mvc,so i have this simple question below
Code1:
#RequestMapping("/hello")
public ModelAndView hello()
{
String str="Be happy!!!!!";
return new ModelAndView("hello","message",str);
}
In hello.jsp View Page ,when i print str then i get result as ${message}
code2:
#RequestMapping("/hello")
public ModelAndView hello()
{
String str="Be happy!!!!!";
return new ModelAndView("hellopage","message",str);
}
but in hellopage.jsp i get result as Be happy!!!!!
so why above code1 does not print str string?
below is my view page jsp code and it is same for both hello.jsp and hellopage.jsp :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
${message}
</body>
</html>
In hello.jsp put this expression <%# page isELIgnored="false"%> at the top. Sometimes expression language automatically off for page
The EL expression doesn't get evaluated? That can have one or more of the following causes:
Application server in question doesn't support JSP 2.0.
The web.xml is not declared as Servlet 2.4 or higher.
The #page is configured with isELIgnored=true.
The web.xml is configured with true in .
In your case it looks like case no 3. Try to put isElIgnored=false in your jsp file.
I only get the error in the console of the IDE, the webpage looks Great.
I tried using the th:if to look for null, but that didn't get rid of the issue.
And the title is never null, so I don't know why I'm getting the error, again only in the console, the webpage, including the title displays fine.
This is my first question on this website, I review code here all the time and find so many great answers, I thought why not try and get some help. I've spent so much time on this one and can't seem to find anyone else with the same issue.
Not enough room to paste the entire stack trace. But also receive this cause of error:
Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "post.title" (template: "post/view" - line 19, col 17)
!DOCTYPE html>
<html lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head th:replace="main :: head"></head>
<!--<html lang="en"-->
<!--html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:layout:decorate="layouts/main.html">-->
<div th:replace="main :: main"> </div>
<body>
<article style="padding:20px">
<header>
<h2 th:text="${post.title}">title</h2>
<p th:text="${#calendars.format(post.postedOn,'M/dd/yyyy hh:mm a')}">postedOn</p>
</header>
<section th:utext="${post.body}">
body
</section>
<footer>
<address>
Posted By <a th:href="|mailto:${post.author.email}|"> <span th:text="|${post.author.firstName} ${post.author.lastName}|">author</span></a>
</address>
</footer>
<hr/>
</article>
</div>
<div th:replace="main :: bottom"> </div>
</body>
</html>
#Controller
#RequestMapping("/posts")
public class PostController {
private static final Logger logger = LoggerFactory.getLogger(PostController.class);
private PostService postService;
#Autowired
public PostController(PostService postService){
this.postService = postService;
}
#RequestMapping("/list")
public String listPosts(Model model){
model.addAttribute("posts", postService.list());
return "post/list";
}
#RequestMapping("/view/{slug}")
public String view(#PathVariable(value="slug") String slug, Model model) {
model.addAttribute("post", postService.getBySlug(slug));
return "post/view";
}
#RequestMapping("/byAuthor/{id}")
public String byAuthor(#PathVariable(value="id") Long id, Model model) {
model.addAttribute("posts", postService.listByAuthor(id));
return "post/list";
}
}
The issue seems to be with this statement: This statement works in all my other html without causing a problem. The other replace statements in this html work fine, it's just this one. I copied the code that is in the head section directly into this html file rather than using the replace and it solved the problem. I have no idea why. –
Got a homework assignment that is giving me problems.... Its modifying a JSF project with two pages and a bean to fit MVC2 by adding two more pages and a controller servlet and another bean for the two additional pages. the new main page forwards to either the second new page or the old first page. My issue is response.getParameter() always results in null.
<%#page session="false" import="java.util.Iterator"%>
<%#taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%#taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<jsp:useBean id="status" scope="request" class="JSFRegistration.Status" />
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>JSP Page</title>
</head>
<body>
<% if (status!=null && !status.isSuccessful()){%>
<font color="red">Processing errors:
<ul><%Iterator errors=status.getExceptions();
while (errors.hasNext()){
Exception e = (Exception) errors.next();%>
<li><%= e.getMessage()%><%}%></ul></font><%}%>
<form action="LoginServlet" method="POST">
<% String username = request.getParameter("username");
if (username==null) username="";%>
<input type="text" name="usernameTF" value="<%=username%>" />
<% String password = request.getParameter("password");
if (password==null) password="";%>
<input type="password" name="passwordTF" value="<%=password%>" />
<input type="submit" value="Login" />
</form>
</body>
</html>
this is basically a direct copy from our book but the fields I need for the new main page. Same for the controller servlet, a direct copy except only contains the fields I need.
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher view = null;
Status status = new Status();
request.setAttribute("status", status);
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username==null || username.length()==0)
status.addException(new Exception("Please enter username"));
if (password==null)
status.addException(new Exception("Please enter password"));
if (!status.isSuccessful()){
view = request.getRequestDispatcher("Login.jsp");
//view.forward(request, response);
}
else
try{
request.setAttribute("username", username);
request.setAttribute("password", password);
view = request.getRequestDispatcher("Registration.jsp");
} catch (Exception e) {
status.addException(new Exception("Error"));
view = request.getRequestDispatcher("Login.jsp");
}
view.forward(request, response);
}
and the Status class, again a direct copy from the book.
public class Status {
private ArrayList exceptions;
public Status(){
exceptions = new ArrayList();
}
public void addException(Exception exception) {
exceptions.add(exception);
}
public boolean isSuccessful(){
return (exceptions.isEmpty());
}
public Iterator getExceptions(){
return exceptions.iterator();
}
regardless of what is typed into the two boxes, stepping through a debug shows the values not getting passed to the parameters. I get the created exceptions printed above the screen for both fields if both have text, if only one has text and when both are empty.
Your request parameter names do not match the input field names. You've assigned the input fields a name of usernameTF and passwordTF. They are then available by exactly those names as request parameter, but you're attempting to get them using the names username and password. So you need either to fix the input field names, or the request parameter names so that they match each other.
By the way, why falling back from a modern MVC framework like JSF to awkward 90's style JSP with mingled business code? Is that really what the homework assignment is asking you? Also the HTML <font> element is deprecated since 1998. Where did you learn about it? Is the quality of the course really good?