Error during execution of processor 'org.thymeleaf.spring4.processor.attr.SpringInputGeneralFieldAttrProcessor' - spring

Trying to change value inside my model class which contains a private String name and I wanted to change the name using Thymeleaf in HTML page then see the change in another url response body.
When I try to access my ("/myname") page in localhost I got the error:
Error during execution of processor 'org.thymeleaf.spring4.processor.attr.SpringInputGeneralFieldAttrProcessor'
Here is my Model:
public class Name {
public String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Here is my Controller
#Controller
public class MainController {
#RequestMapping("/name")
#ResponseBody
public String showName() {
Name myname = new Name();
return myname.getName();
}
#RequestMapping("/myname")
public String setName() {
return "myname";
}
#RequestMapping(value = "myname", method = RequestMethod.POST)
public String showName(#ModelAttribute Name iko, BindingResult errors, Model model) {
return "name";
}
}
Here is my html thymeleaf pages:
myname.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1"/>
<title>Insert title here</title>
</head>
<body>
<form action="#" th:action="#{/myname}" th:object="${iko}" method="post">
<label>Enter the name</label><br/>
<input type="text" th:field="*{name}"/>
<button type="submit">SUBMIT</button>
</form>
</body>
</html>

Related

How do I enter a null value in the thymeleaf field of an html page?

I'm making an input page using thymeleaf:
insertText.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Handing Form Submission</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Form</h1>
<form action="#" th:action="#{/insertText}" th:object="${text}" method="post">
<p th:text="'id: ' + ${text.id}" />
<p th:text="'parent_id' + ${text.parent_id} ?: 'original'" />
<p th:text="'id: ' + ${text.name}" />
<p th:text="'content: ' + ${text.operation}" />
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
And in the parent_it field I want to enter null if it is the original text but I get an error:
Field error in object 'textTable' on field 'parent_id': rejected value [null];
codes [typeMismatch.textTable.parent_id,typeMismatch.parent_id,typeMismatch.java.lang.Integer,typeMismatch];
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [textTable.parent_id,parent_id]; arguments []; default message [parent_id]];
default message [Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Integer' for property 'parent_id';
nested exception is java.lang.NumberFormatException: For input string: "null"]]
Although in the post page I added zero value processing:
result.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Getting Started: Handing Form Submission</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Result</h1>
<p th:text="'id: ' + ${text.id}" />
<p th:text="'content: ' + ${text?.parent_id}" />
<p th:text="'id: ' + ${text.name}" />
<p th:text="'content: ' + ${text.operation}" />
Submit another message
</body>
</html>
Maybe there is a way to make this possible?
My entity
textTablt
package com.example.HiberTest.Entities;
#Entity
#Table(name = "textTable")
public class textTable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Integer id;
#Column(name = "parent_id")
private Integer parent_id;
#NotBlank
#Size(min=1, max=128)
#Column(name = "name")
private String name;
#NotBlank
#Size(min=1, max=128)
#Column(name = "operation")
private String operation;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getParent_id() {
return parent_id;
}
public void setParent_id(Integer parent_id) {
this.parent_id = parent_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOperation() {
return operation;
}
public void setOperation(String operation) {
this.operation = operation;
}
#Override
public String toString(){
return String.format("id = %o" +
", parent_id = %o, " +
"name = %s, operation = %s ",
id,parent_id,name,operation);
}
}
My conroller:
package com.example.HiberTest.Controller;
import java.util.List;
#Controller
public class TextController {
#Autowired
daoRepository dao;
#GetMapping("/insertText")
public String insertText(Model model){
//List<textTable> list =dao.findAll();
//model.addAttribute("texts",list);
model.addAttribute("text", new textTable());
return "insertText";
}
#PostMapping("/insertText")
public String getAllText(#ModelAttribute textTable texts, Model model){
//List<textTable> list =dao.findAll();
model.addAttribute("text", texts);
return "result";
}
}
I would be glad of help to figure out how to enter a null value so that it is processed correctly
Your variable parent_id in class textTable is of type Integer but you are trying to insert string in it. you are trying to append integer id in string 'parent_id' and then store in Database that's why you are getting error.

Springboot homepage after login

I just want to display the homepage and the users name after login but I keep getting a 404 not found error.
here is the index.html page
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 th:action="#{/index}">Hello<h1 th: th:text="${name}"></h1> </h1>
</body>
</html>
And here is my controller
#Controller
#AllArgsConstructor
public class UserController {
private final UserService userService;
private final ConfirmationTokenService confirmationTokenService;
#GetMapping("/sign-in")
String signIn() {
return "sign-in";
}
#GetMapping("/sign-up")
String signUpPage(User user) {
return "sign-up";
}
#PostMapping("/sign-up")
String signUp(User user) {
userService.signUpUser(user);
return "redirect:/sign-in";
}
#GetMapping("/sign-up/confirm")
String confirmMail(#RequestParam("token") String token) {
Optional<ConfirmationToken> optionalConfirmationToken = confirmationTokenService.findConfirmationTokenByToken(token);
optionalConfirmationToken.ifPresent(userService::confirmUser);
return "redirect:/sign-in";
}
#RequestMapping(value = {"/index"}, method = RequestMethod.GET)
public String welcome(User user, Model model) {
model.addAttribute("Name", user.getName());
return "index";
}
I've been trying this for a while now and I don't know what I'm doing wrong. The websecurity config is configured so that the default succesuful URL is index.html
Try changing the request mapping to
#RequestMapping(value = {"/index", "/"}, method = RequestMethod.GET)
Also, try calling localhost:9090/index (without the .html) as Eleftheria Stein-Kousathana said.

Getting Error while bootstraping the Spring-boot Application

Well i am developing a spring boot application by choosing view technology as jsp.But when am trying to bootstraping the spring-boot application i am getting white level error page.
Model Class
public class Person {
private String p_first_name;
private String p_last_name;
private int age;
private String city;
private String state;
private String country;
public Person(String p_first_name, String p_last_name, int age, String city, String state, String country) {
super();
this.p_first_name = p_first_name;
this.p_last_name = p_last_name;
this.age = age;
this.city = city;
this.state = state;
this.country = country;
}
public Person() {
super();
// TODO Auto-generated constructor stub
}
public String getP_first_name() {
return p_first_name;
}
public void setP_first_name(String p_first_name) {
this.p_first_name = p_first_name;
}
public String getP_last_name() {
return p_last_name;
}
public void setP_last_name(String p_last_name) {
this.p_last_name = p_last_name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
Controller Class
#Controller
public class PersonController {
private static ArrayList<Person> persons = new ArrayList<Person>();
static {
persons.add(new Person("kumar", "bikash", 28, "bangalore", "karnataka", "india"));
persons.add(new Person("kumar", "pratap", 24, "delhi", "delhi", "india"));
persons.add(new Person("kumar", "ravi", 29, "delhi", "delhi", "india"));
persons.add(new Person("kumar", "mangalam", 65, "delhi", "delhi", "india"));
}
#RequestMapping(value = { "/", "/index" }, method = RequestMethod.GET)
public String index(Model model) {
String message = "Hello" + "Spring Boot implementation with jsp Page";
model.addAttribute("message", message);
return "index";
}
#RequestMapping(value = "/personList", method = RequestMethod.GET)
public String getPersonList(Model model) {
model.addAttribute("persons", persons);
return "personList";
}
}
application.properties
# VIEW RESOLVER CONFIGURATION
spring.mvc.view.prefix=/WEB-INF/jsp
spring.mvc.view.suffix=.jsp
jsp file
index.jsp
=========
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Integration of Spring Boot with jsp page</title>
</head>
<body>
<h1>Welcome to Spring boot</h1>
<p>This project is an Example of how to integrate Spring Boot with
jsp page.</p>
<h2>${message} </h2>
</body>
</html>
personList.jsp
==============
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Person List content Present here</title>
</head>
<body>
<h1>Person List</h1>
<div>
<table border="1">
<tr>
<th>FirstName:</th>
<th>LasttName:</th>
<th>Age:</th>
<th>city:</th>
<th>State:</th>
<th>Country:</th>
</tr>
<c:forEach items="${persons}" var=person>
<tr>
<td>${person.firstname}</td>
<td>${person.lastname}</td>
<td>${person.age }</td>
<td>${person.city }</td>
<td>${person.state }</td>
<td>${person.country }</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
Error page
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Fri Jun 07 23:41:57 IST 2019
There was an unexpected error (type=Not Found, status=404).
No message available
well please review the below code.Help me to resolve thing where i am
getting wrong?
Are you looking to enable your own errorpage disabling the white level error page? May be this can help you.
If you do not specify any custom implementation in the configuration,
BasicErrorController bean is automatically registered in Spring Boot. You can add your implementation of ErrorController.
#Controller
public class MyErrorController implements ErrorController {
#RequestMapping("/error")
public String handleError() {
//do something like logging
return "error";
}
#Override
public String getErrorPath() {
return "/error";
}
}
1) I would suggest trying the #RestController annotation to make sure that you get at least the JSON response. (Only for Debugging)
2) After the first part is figured out, you can go back to your #Controller annotation and make sure that the string you return in the request mapping method is available as a jsp file. I would recommend trying with a single endpoint initially ("/") and having the appropriate jsp page for it.
3) If it still produces the same issue, you can refer to this post
Spring Boot JSP 404.Whitelabel Error Page
4) You can also disable and customize the default error page by following this link https://www.baeldung.com/spring-boot-custom-error-page

Accessing Model attributes in Thymleaf and Spring boot

I am learning to use thymeleaf templates for a project I am completing and seem to be missing something.
I am trying to create a very simple Hello type app, here is my code (note I am using groovy):
Controller:
#Controller
class TestController {
#RequestMapping("/")
String homePage(#RequestParam("name") String name, ModelAndView modelAndView){
modelAndView.addObject("name", name)
return "home"
}
}
home.html:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title></title>
</head>
<body>
<h1>Hello</h1>
<p th:text="${name}" />
</body>
</html>
What have I missed? I just get "Hello" and nothing else when I hit:
http://localhost:8080/app-0.0.1-SNAPSHOT/?name=Sam
you have alternate option with access controller data with view name returning
#Controller
class TestController {
#RequestMapping("/")
public String homePage(#RequestParam("name") String name,Model model){
model.addAttribute("name", name)
return "home"
}
}
in your html file
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title></title>
</head>
<body>
<h1>Hello</h1>
<p th:text="${name}" />
</body>
</html>
bind model object with parameter and now you need to set addAttribute with key and value par you can access data without using ModelAndView object.
I'm not sure but you can to change ModelAndView by Model:
#Controller
class TestController {
#RequestMapping("/")
String homePage(#RequestParam("name") String name, Model model){
model.addAttribute("name", name)
return "home"
}
}
To answer my own question, if I change the controller to return a ModelAndView, like so:
#Controller
class TestController {
#RequestMapping("/")
ModelAndView homePage(#RequestParam("name") String name){
ModelAndView mav = new ModelAndView()
mav.addObject("name", name)
mav.setViewName("home")
return mav
}
}
Then all is good, although the tutorials show it working like my original example - I'm quite happy to do it this way.
#Controller
#RequestMapping("/")
class TestController {
#GetMapping
public String homePage(#RequestParam(name = "name") String name,Model model){
model.addAttribute("name", name);
return "home";
}
}

Spring Framework <form:errors/> tag not showing errors

I know there are many similar questions here, but none of them solved my problem.
I'm using Spring 4.0.3 and Hibernate Validator 5.1.0.
The problem occurs when I try to omit the path attribute of the <form:errors/> tag, so:
<form:errors path="contato.nome" /> works
<form:errors path="*" /> works
<form:errors /> doesn't work
I don't know why it happens. Spring javadocs (org.springframework.web.servlet.tags.form.ErrorsTag) says it should work like that:
Field only - set path to the field name (or path)
Object errors only - omit path
All errors - set path to *
Can you help me, please?
The interested code is in the 'edicao.jsp' and in the method 'confirmarEdicao' of the ContatoController.java. Sorry if my english is bad.
ContatoController.java
#Controller
#RequestMapping("/contatos")
public class ContatoController {
#Autowired
private ContatoService contatoService;
#Autowired
private MessageSource messageSource;
#RequestMapping(value = "/confirmarEdicao", method = RequestMethod.POST)
public String confirmarEdicao(#Valid Contato contato, BindingResult bindingResult) {
if(bindingResult.hasErrors()) {
return "contatos/edicao";
}
contatoService.save(contato);
return "redirect:/contatos";
}
#RequestMapping(method = RequestMethod.GET)
public ModelAndView form(HttpServletRequest request) {
String message = messageSource.getMessage("teste", null, new Locale("pt", "BR"));
System.out.println(message);
return new ModelAndView("contatos/listagem")
.addObject("contatos", contatoService.list());
}
#RequestMapping("/remover/{id}")
public String remover(Contato contato) {
contatoService.delete(contato);
return "redirect:/contatos";
}
#RequestMapping("/editar/{id}")
public ModelAndView formEdicao(Contato contato) {
contato = contatoService.find(contato.getId());
return new ModelAndView("contatos/edicao")
.addObject(contato);
}
#RequestMapping(value = "/cadastrar")
public String formCadastro() {
return "contatos/cadastro";
}
#RequestMapping(value = "/confirmarCadastro", method = RequestMethod.POST)
public String confirmarCadastro(#Valid Contato contato, BindingResult bindingResult,
RedirectAttributes redirectAttributes) {
if (bindingResult.hasFieldErrors()) {
return "contatos/cadastro";
}
contatoService.save(contato);
redirectAttributes.addFlashAttribute("mensagem", "Contato cadastrado com sucesso.");
return "redirect:/contatos";
}
#ResponseBody
#RequestMapping(value = "/pesquisar/{nome}", method = RequestMethod.GET,
produces="application/json")
public List<Contato> pesquisar(#PathVariable String nome) {
return contatoService.findByName(nome);
}
}
edicao.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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>Editar contato</title>
</head>
<body>
<c:set var="context">${pageContext.request.contextPath}</c:set>
<script type="text/javascript">var context = "${context}";</script>
<script src="${context}/resources/js/jquery-2.1.0.min.js"></script>
<script src="${context}/resources/js/contatos/edicao.js"></script>
<form:form commandName="contato" action="${context}/contatos/confirmarEdicao" method="post">
<form:errors/>
<table>
<form:hidden path="id"/>
<tr>
<td>Nome:</td>
<td><form:input path="nome" /></td>
</tr>
<tr>
<td>Telefone:</td>
<td><form:input path="telefone"/></td>
</tr>
<tr>
<td><input type="button" value="Voltar" id="btn_voltar"/><input type="submit" value="Salvar"/></td>
</tr>
</table>
</form:form>
</body>
</html>
Contato.java
package com.handson.model;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
public class Contato {
private Long id;
#Size(min = 3, message = "Nome deve ter no mínimo 3 caracteres")
#NotEmpty(message = "O nome deve ser preenchido")
private String nome;
private String telefone;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public Contato withId(Long id) {
setId(id);
return this;
}
public Contato withTelefone(String telefone) {
setTelefone(telefone);
return this;
}
public Contato withNome(String nome) {
setNome(nome);
return this;
}
#Override
public String toString() {
return "Contato [id=" + id + ", nome=" + nome + ", telefone="
+ telefone + "]";
}
}
There are some keywords which should be defined:
path - EL-like path to an object or to a field of an object (e.g. foo, foo.bar or foo.bar.baz)
nested path - current path context stored as nestedPath request attribute (new paths are relative to this path)
object error - error connected with object itself (e.g. path is equal to foo)
field error - error connected with object field (e.g. path is foo.bar)
The tag <form:form commandName="foo"> defines nested path as nestedPath=foo. When you write <form:errors path="bar"> it tries to find errors defined for path foo.bar.
Lets say that you have errors connected with foo (object error), foo.bar and foo.bar.baz (nested field error). What this means:
if you enter <form:errors>, only errors bound to foo path are displayed => 1 message
if you enter <form:errors path="bar">, only errors bound to foo.bar path are displayed => 1 message
if you enter <form:errors path="*">, errors bound to foo and its child paths are displayed => 3 messages
if you enter <form:errors path="bar.*">, only child errors for foo.bar are diplayed => 1 message
if you enter <form:errors path="bar*">, errors bound to foo.bar and its child paths are diplayed => 2 messages
Checking on Errors class JavaDoc might give you additional insight.

Resources