Neither BindingResult nor plain target object for bean name 'cliente' available as request attribute - spring

I'm facing an issue with spring and thymeleaf, i'm trying to fill a form with data from an entity called cliente, but i'm getting a Whitelabel Error Page message in the browser and this message in the console
Neither BindingResult nor plain target object for bean name 'cliente' available as request attribute
this is the Cliente
package com.bolsadeideasspringboot.app.models.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import org.springframework.format.annotation.DateTimeFormat;
#Entity
#Table(name="clientes")
public class Cliente implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotEmpty
private String nombre;
#NotEmpty
private String apellido;
#NotEmpty
#Email
private String email;
#Column(name="create_at")
#Temporal(TemporalType.DATE)
#DateTimeFormat(pattern="dd/MM/yyyy")
private Date createAt;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellido() {
return apellido;
}
public void setApellido(String apellido) {
this.apellido = apellido;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getCreateAt() {
return createAt;
}
public void setCreateAt(Date createAt) {
this.createAt = createAt;
}
}
this is the controller method
#RequestMapping(value="/form/{id}")
public String editar(#ModelAttribute("form") #PathVariable(value="id")Long id, Map<String, Object>model) {
Cliente cliente = null;
if(id > 0) {
clientedao.findOne(id);
model.put("cliente", cliente);
model.put("titulo", "Editar Cliente");
return "form";
}
else {
return "redirect:/listar";
}
}
this is the ClienteDaoImpl.java method
#Override
public Cliente findOne(Long id) {
// TODO Auto-generated method stub
return em.find(Cliente.class, id);
}
this is the Dao interface method
public Cliente findOne(Long id);
and this is the form
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title th:text="${titulo}">Insert title here</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-3">
<h1 class="text-success" th:text="${titulo}"></h1>
<form th:action="#{/form}" th:object="${cliente}" method="post">
<div class="form-group">
<label>Nombre</label>
<input class="form-control" type="text" th:field="*{nombre}" placeholder="Nombre"/>
<small class="form-text text-danger" th:if="${#fields.hasErrors('nombre')}" th:errors="*{nombre}"></small>
</div>
<div class="form-group">
<label>Apellido</label>
<input class="form-control" type="text" th:field="*{apellido}" placeholder="Apellido"/>
<small class="form-text text-danger" th:if="${#fields.hasErrors('apellido')}" th:errors="*{apellido}"></small>
</div>
<div class="form-group">
<label>Email</label>
<input class="form-control" type="text" th:field="*{email}" placeholder="correo#ejemplo.com"/>
<small class="form-text text-danger" th:if="${#fields.hasErrors('email')}" th:errors="*{email}"></small>
</div>
<div class="form-group">
<label>Fecha</label>
<input class="form-control" type="text" th:field="*{createAt}" placeholder="DD/MM/YYYY"/>
<small class="form-text text-danger" th:if="${#fields.hasErrors('createAt')}" th:errors="*{createAt}"></small>
</div>
<div class="form-group">
<input class="btn btn-primary" type="submit" value="Crear Cliente" />
</div>
<input type="hidden" th:field="*{id}" />
</form>
</div>
</div>
</div>
</body>
</html>
i'm setting the cliente in the controller method and i'm using th:object in the form, so i don't know what i'm doing wrong, any help would be helpul, thanks in advice

Instead of put(), try using the recommended approach to adding an object to your model with
model.addAttribute("cliente", clientedao.findOne(id));
You typically want to use #GetMapping as well for your requests to populate the form. And use #PostMapping for submissions.
Aside: also take a look at Project Lombok to make your beans less error-prone and more readable. You could remove all those getters and setters and just annotate the class with #Data.
While not deprecated, you'll also want to move away from using java.util.Date and use the newer date/time classes.

Related

Spring Boot+Thymeleaf: th not able to resolve a Spring EL expression

I am using spring boot+thymeleaf+neo4j. Everything is working fine except that thymeleaf is not able to resolve a few of the attributes of the 'product' variable used in the th:each block in the template product_grid.html, which includes th:src="${product.URL}", th:text="${Product.title}" and the th:action="#{/product/(${Product.getId()})}" expression in form tag. The th:text="${Product.Price}" is working. When I check the code produced in the browser the src tag is empty (src:""), the text attribute containing the title tag is not shown in the browser. The th:action works fine but when I click the button defined inside the form, the url changes to http://localhost:8080/product/?btn=View+Product
instead of the following code which is shown in the browser console
http://localhost:8080/product/?1
Note: I am trying to get the image url from a field which is stored in neo4j database. The project directory is:
project directory image
Template:product_grid.html
<html xmlns:th="http://www.thymeleaf.org" >
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Products</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.bundle.min.js" integrity="sha384-feJI7QwhOS+hwpX2zkaeJQjeiwlhOP+SdQDqhgvvo1DsjtiSQByFdThsxO669S2D"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="#">Grada</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item ">
<a class="nav-link" href="#">Home
<span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link">My Best Products</a>
</li>
<li class="nav-item">
<a class="nav-link" th:href="#{/login}">Login</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<a class="btn btn-outline-success my-2 my-sm-0" href="file:///home/madhav/SPM/Grada/public_html/product.html">Search</a>
</form>
</div>
</nav>
<div class="container text-center">
<div class="row">
<div th:each="Product:${products}" class="col-lg-3 col-sm-12 col-md-6 my-2 p-auto">
<div class="card">
<div class="card-body">
<img src="http://via.placeholder.com/150x150/888/111" th:src="${Product.URL}" alt="img" class="card-img-top img-thumbnail img-fluid">
<div class="card-title lead" th:text="${Product.title}">Some product name</div>
<div class="card-text">Price: ₹<span th:text="${Product.Price}">400</span></div>
</div>
<form method="GET" action="/" th:action="#{/product/(${Product.getId()})}">
<input type="submit" name="btn" class="form-control btn btn-primary" value="View Product">
<input type="submit" name="btn" class="form-control btn btn-primary" value="Add to Cart">
</form>
</div>
</div>
</div>
</div>
</body>
</html>`
Product model:Product.html
package com.grada.ecommerce.Models;
import com.grada.ecommerce.Models.Seller;
import org.neo4j.ogm.annotation.*;
import java.util.HashSet;
import java.util.Set;
#NodeEntity(label = "Product")
public class Product
{
public Product()
{
}
public Product(String title, Double price, int quantity, float rating, String description, String url, String company)
{
this.title = title;
this.Rating = rating;
this.Description = description;
this.Price = price;
this.Quantity = quantity;
this.URL = url;
this.Company = company;
}
#Id
#GeneratedValue
private Long id;
#Property(name = "title")
public String title;
#Property(name = "Rating")
public float Rating;
#Property(name = "Description")
public String Description;
#Property(name = "Price")
public Double Price;
#Property(name = "Quantity")
public int Quantity;
#Property(name = "Company")
public String Company;
#Property(name = "URL")
public String URL;
#Override
public String toString()
{
return this.title;
}
public Long getId() {
return id;
}
public String getTitle()
{
return title;
}
#Relationship(type = "Sells", direction = Relationship.INCOMING)
public Seller Seller;
}
ProductController.java
package com.grada.ecommerce.Controllers;
import com.grada.ecommerce.Models.Product;
import com.grada.ecommerce.Models.Seller;
import com.grada.ecommerce.Services.ProductService;
import com.grada.ecommerce.Services.SellerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class ProductController
{
final ProductService productService;
final SellerService sellerService;
#Autowired
public ProductController(ProductService productService, SellerService sellerService)
{
this.productService = productService;
this.sellerService = sellerService;
}
#RequestMapping(value = "/", method = RequestMethod.GET)
public String Index(Model model)
{
Iterable<Product> products = productService.products();
model.addAttribute("products", products);
return "product_grid";
}
#RequestMapping(value = "/product", method = RequestMethod.GET)
public String ShowProduct(#RequestParam(value = "id") Long id, Model model)
{
Product product = productService.findProductByID(id);
if(product == null)
return "redirect:/";
model.addAttribute("product", product);
return "productid";
}
#RequestMapping(value = "/add")
public String AddProduct(Model model)
{
model.addAttribute("product", new Product());
return "add";
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String AddProduct(#ModelAttribute Product product)
{
productService.addProduct(product);
return "redirect:/";
}
#RequestMapping(value = "/delete", method = RequestMethod.GET)
public String DeleteProduct(Model model)
{
model.addAttribute("product", new Product());
return "delete";
}
#RequestMapping(value = "/delete", method = RequestMethod.POST)
public String DeleteProduct(#ModelAttribute Product product)
{
productService.deleteProduct(product);
return "redirect:/";
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String LoginPage(Model model)
{
return "login";
}
#RequestMapping(value = "/login", method = RequestMethod.POST)
public String Authenticate(Model model, String username, String password)
{
if (username.equalsIgnoreCase("seller#fake.com") && password.equals("fakeseller"))
{
Iterable<Product> products = productService.products();
model.addAttribute("products", products);
return "loggedin";
}
else
return "redirect:/login";
}
#RequestMapping(value = "/policy", method = RequestMethod.GET)
public String PolicyPage()
{
return "policies";
}
}
Welcome to SO.
Include setX methods for your variables in the Product class. Thymeleaf needs these to bind.
IMO, a great way to do this is to use Project Lombok and simply annotate your class with #Data. Then you won't even need to specify getters or setters (or your toString()) at all.
Use lower-case for your variables since by convention variables with a capital first letter refers to the class, not an instance variable.
As mentioned, use POST instead of GET in your form since you are submitting data.
Use the shorthand #GetMapping and #PostMapping to make it easier to read.

Can I have more than 1 form action(form inside form) in single jsp using hibernate

In this jsp, I have used 2 form actions, one to save the role(table:defining role), and other to call the drop list from other table(table: solutionList).
After clicking on submit, it is not doing anything.
If i remove this form(solutionMaster.html)
Im getting this error " Invalid property 'sMName' of bean class [com.mode;.definingrole]: Bean property 'sMName' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?.
Yes, I know the reason, Because the column 'sMName' was not the part of defining role table. what to do with this.
The Thing i want to know is,
Can we create form inside form?
2.Without creating another form, How can i get the column values of other table to defining role table?
Please help.
Thanks in advance.!!!
<div class="modal inmodal" id="myModalForRole" tabindex="-1"
role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content animated bounceInRight">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span><span class="sr-only">Close</span>
</button>
<i class="fa fa-laptop modal-icon"></i>
<h4 class="modal-title">Define Role</h4>
</div>
<div class="modal-body">
<form:form action="newRoleDetails.html" method="post"
commandName="deftemp" id="deftemp">
<div class="row">
<div class="form-group">
<form:form action="solutionName.html" method="post"
commandName="soltemp" id="soltemp">
<div class="col-sm-6">
<label>Solutions*</label><br>
<form:select path="sMName" class="form-control"
id="sMName">
<form:option value="" label="--select--"></form:option>
<c:forEach var="solutionList" items="${solutionList}"
varStatus="loop">
<form:option value="${solutionList}"
label="${solutionList}">
</form:option>
</c:forEach>
</form:select>
</div>
</form:form>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-sm-6">
<label>Parent Role*</label><br>
<form:textarea path="ParentRole" id="ParentRole"
class="form-control" placeholder="Enter the Parent Role" />
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-sm-6">
<label>Sub Role*</label><br>
<form:textarea path="SubRole" id="SubRole"
class="form-control" placeholder="Enter the Child role" />
</div>
</div>
</div>
<br>
<br>
<div class="modal-footer">
<button type="button" class="btn btn-white"
data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Submit
</button>
</div>
</form:form>
</div>
Models: (solutionlist.java)
package com.model;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table (name="solutionlist")
public class solutionlist implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="solutionId",nullable = false,columnDefinition = "UNSIGNED INT(4)")
Integer solutionId;
#Column(name="solutionName")
String solutionName;
#Column(name="solutionOwner")
String solutionOwner;
#Column(name="ownerMailId")
String ownerMailId;
#Column(name="additionDate")
String additionDate;
public Integer getSolutionId() {
return solutionId;
}
public void setSolutionId(Integer solutionId) {
this.solutionId = solutionId;
}
public String getSolutionName() {
return solutionName;
}
public void setSolutionName(String solutionName) {
this.solutionName = solutionName;
}
public String getSolutionOwner() {
return solutionOwner;
}
public void setSolutionOwner(String solutionOwner) {
this.solutionOwner = solutionOwner;
}
public String getOwnerMailId() {
return ownerMailId;
}
public void setOwnerMailId(String ownerMailId) {
this.ownerMailId = ownerMailId;
}
public String getAdditionDate() {
return new SimpleDateFormat("yyyy-MM-dd HH-mm-ss.SSS")
.format(new Date());
}
public void setAdditionDate(String additionDate) {
this.additionDate = additionDate;
}
}
definingrole.java
package com.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="definingrole")
public class definingrole implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="SNo")
Integer SNo;
#Column(name="Solutions")
String Solutions;
#Column(name="ParentRole")
String ParentRole;
#Column(name="SubRole")
String SubRole;
public Integer getSNo() {
return SNo;
}
public void setSNo(Integer sNo) {
SNo = sNo;
}
public String getSolutions() {
return Solutions;
}
public void setSolutions(String solutions) {
Solutions = solutions;
}
public String getParentRole() {
return ParentRole;
}
public void setParentRole(String parentRole) {
ParentRole = parentRole;
}
public String getSubRole() {
return SubRole;
}
public void setSubRole(String subRole) {
SubRole = subRole;
}
}
Controller : newRoleDetails.html
#RequestMapping(value=NEWROLEDETAILS_PATH)
public String newRoleDetails(Map<String, Object> model, definingrole value,solutionlist sol) throws Exception {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName();
String nameOfUser=TemplateService.getEmpNameOfUser(name);
model.put("nameOfUser",nameOfUser);
String userid=loginService.getUserId();
String role=loginService.getRole();
TemplateService.newRoleDetails(value);
definingrole deftemp=new definingrole();
model.put("deftemp", deftemp);
solutionlist s = new solutionlist();
ArrayList<templateDetails> listOfTemplate=TemplateService.listTemplateDetails(role,userid);
model.put("listOfTemplate",listOfTemplate);
return TEMPLATESUMMARY;
}
controller : solutionName.html
#RequestMapping("/solutionlist.html")
public String solutionName(Map<String, Object> model,solutionlist sol) throws Exception {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName();
String nameOfUser=TemplateService.getEmpNameOfUser(name);
model.put("nameOfUser",nameOfUser);
solutionlist soltemp = new solutionlist();
model.put("soltemp", soltemp);
ArrayList<String> solutionList=TemplateService.getSolutionListForTemplate();
model.put("solutionList", solutionList);
return REDIRECT_TEMPLATESUMMARY_URL;
}
You are trying to populate list inside form under the tag of form. Which is wrong approach. You won't get the value from /solutionlist.html by your form. You have to call at least a GET if you want to use /solutionlist.html controller.
If i think So then you have to do the following
You don't need the '/solutionlist.html' controller.
Just bind the ArrayList solutionList into model in the controller method where the form page served. I mean the GET method of Controller where the given form is served.
ArrayList<String> solutionList=TemplateService.getSolutionListForTemplate();
model.put("solutionList", solutionList);
You will get that solutionList directly to your form as value. So, modify the select part of your form as follows
<select name="solutions"path="Solutions">
<c:forEach items="${solutionList}" var="solution">
<option value="${solution}">${solution}</option>
</c:forEach>
</select>

spring-security:HTTP Status 405 - Request method 'POST' not supported

I have checked so many answers here for the same but it seems nothing worked for me. I have spring security with spring mvc. when my user is trying to sign up I am sending post data to my controller. but it is giving me 405 post not supported I have disabled csrf token in security config. please let me know where did I go wrong?
Here's my webSecurityConfigureDapter:
package org.pkb.springlogin.config;
import org.pkb.springlogin.authentication.MyDBAuthenticationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
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 = #EnableWebMVCSecurity + Extra features
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
MyDBAuthenticationService myDBAauthenticationService;
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// Users in memory.
auth.inMemoryAuthentication().withUser("user1").password("12345").roles("USER");
auth.inMemoryAuthentication().withUser("admin1").password("12345").roles("USER, ADMIN");
// For User in database.
auth.userDetailsService(myDBAauthenticationService);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
// The pages does not require login
http.authorizeRequests().antMatchers("/", "/welcome", "/login", "/logout","/signUp").permitAll();
// /userInfo page requires login as USER or ADMIN.
// If no login, it will redirect to /login page.
http.authorizeRequests().antMatchers("/userInfo").access("hasAnyRole('ROLE_USER', 'ROLE_ADMIN')");
// For ADMIN only.
http.authorizeRequests().antMatchers("/admin").access("hasRole('ROLE_ADMIN')");
// When the user has logged in as XX.
// But access a page that requires role YY,
// AccessDeniedException will throw.
http.authorizeRequests().and().exceptionHandling().accessDeniedPage("/403");
// Config for Login Form
http.authorizeRequests().and().formLogin()//
// Submit URL of login page.
.loginProcessingUrl("/j_spring_security_check") // Submit URL
.loginPage("/login")//
.defaultSuccessUrl("/userInfo")//
.failureUrl("/login?error=true")//
.usernameParameter("username")//
.passwordParameter("password")
// Config for Logout Page
.and().logout().logoutUrl("/logout").logoutSuccessUrl("/logoutSuccessful");
}
}
Here's my sign up page
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# page isELIgnored="false"%>
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
<html lang="en">
<head>
<link rel="stylesheet" href="<c:url value="/resources/css/bootstrap-theme.min.css"/>">
<link rel="stylesheet" href="<c:url value="/resources/css/bootstrap.min.css"/>">
<title>Sign Up Form</title>
<meta http-equiv="Content-Type" content="text/html charset=UTF-8" />
</head>
<body>
<div class="jumbotron page-header">
<h2>Login</h2>
</div>
<form:form class="form-horizontal" method="post"
name="userReg" id="userReg" modelAttribute="userForm" action="${contextPath}/login">
<div class="container">
<label class="col-sm-2 control-label">Name</label>
<div class="col-sm-4">
<input name="userName" type="text" class="form-control" id="userName" placeholder="Name" />
</div>
</div>
<br>
<div class="container">
<label class="col-sm-2 control-label">Email</label>
<div class="col-sm-4">
<input name="email" class="form-control" id="email" placeholder="Email" />
</div>
</div>
<br>
<div class="container">
<label class="col-sm-2 control-label">Date of Birth(dd-mm-yyyy)</label>
<div class="col-sm-4">
<input name="dob" type="text" class="form-control" id="dob" placeholder="Date of birth" />
</div>
</div>
<br>
<div class="container">
<label class="col-sm-2 control-label">Password</label>
<div class="col-sm-4">
<input name="password" type="password" class="form-control" id="password" placeholder="password" />
</div>
</div>
<br>
<div class="container">
<label class="col-sm-2 control-label">Confirm Password</label>
<div class="col-sm-4">
<input name="confirmPassword" type="password" class="form-control" id="cpassword" placeholder="confirm password" />
<span id='message'></span>
</div>
</div>
<br>
<div class="container">
<label class="col-sm-2 control-label">User type</label>
<div class="col-sm-4">
<select class="form-control" name="type" >
<option selected="selected">--select--</option>
<option value="user" >User</option>
<option value="admin">Admin</option>
</select>
</div>
</div>
<br>
<br>
<div class="col-md-6 center-block">
<input type="submit" class="btn-lg btn-primary center-block" value="save">
</div>
</form:form>
</body>
<script type = "text/javascript"
src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js"></script>
<script src="<c:url value="/resources/js/form-validation.js"/>"></script>
<script src="<c:url value="/resources/js/passwordVerification.js"/>"></script>
</html>
Here's my MainController
package org.pkb.springlogin.controller;
import java.security.Principal;
import org.pkb.springlogin.manager.SignUpHandler;
import org.pkb.springlogin.model.SignUpInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class MainController {
#Autowired
SignUpHandler signupHandler;
private static final Logger logger =LoggerFactory.getLogger(MainController.class);
#RequestMapping(value = { "/", "/welcome" }, method = RequestMethod.GET)
public String welcomePage(Model model) {
model.addAttribute("title", "Welcome");
model.addAttribute("message", "Hello friend!");
return "welcomePage";
}
#RequestMapping(value = "/admin", method = RequestMethod.GET)
public String adminPage(Model model) {
return "adminPage";
}
#RequestMapping(value="/signUp",method=RequestMethod.POST)
public String userLogin(#ModelAttribute("userForm") SignUpInfo user,ModelMap model){
System.out.println(user);
Integer id=signupHandler.process(user);
if(id!=null){
logger.debug("ID in controller:"+id);
return "success";
}
logger.error("error in controller");
return "Failure";
}
#RequestMapping(value="/signUp",method=RequestMethod.GET)
public String register(Model model){
SignUpInfo user=new SignUpInfo();
model.addAttribute("userForm", user);
return "signUp";
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginPage(Model model ) {
return "loginPage";
}
#RequestMapping(value = "/logoutSuccessful", method = RequestMethod.GET)
public String logoutSuccessfulPage(Model model) {
model.addAttribute("title", "Logout");
return "logoutSuccessfulPage";
}
#RequestMapping(value = "/userInfo", method = RequestMethod.GET)
public String userInfo(Model model, Principal principal) {
// After user login successfully.
String userName = principal.getName();
System.out.println("User Name: "+ userName);
return "userInfoPage";
}
#RequestMapping(value = "/403", method = RequestMethod.GET)
public String accessDenied(Model model, Principal principal) {
if (principal != null) {
model.addAttribute("message", "Hi " + principal.getName()
+ "<br> You do not have permission to access this page!");
} else {
model.addAttribute("msg",
"You do not have permission to access this page!");
}
return "403Page";
}
}
Here's my signUpInfo
package org.pkb.springlogin.model;
public class SignUpInfo {
private String userName;
private String password;
private String confirmPassword;
private Type type;
private Byte enabled;
public Byte getEnabled() {
return enabled;
}
public void setEnabled(Byte enabled) {
this.enabled = enabled;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getConfirmPassword() {
return confirmPassword;
}
public void setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
#Override
public String toString() {
return "SignUpInfo [userName=" + userName + ", password=" + password + ", confirmPassword=" + confirmPassword
+ ", type=" + type + "]";
}
}
Form is POST-ed to /login
action="${contextPath}/login"
but login is annotated to support only GET
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginPage(Model model ) {
return "loginPage";
}
maybe you should post to /signUp

Spring form data is not received in controller with mustache

I'm using a simple Spring form with mustache. However the data is not received in Spring controller. login.getId(), login.getPass() are always received as null in controller. Any clues if something have to be fixed in template or controller?
My template and controller code as below.
<form class="form-signin" id="loginForm" action="{{{appCtxt}}}/login" method="post">
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" name="{{id}}" id="id" class="form-control" placeholder="Email address" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" name="{{pass}}" id="pass" class="form-control" placeholder="Password" required>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
Controller
#Controller
public class LoginController {
private LoginService loginService;
#Autowired
public void setLoginService(LoginService loginService) {
this.loginService = loginService;
}
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView index(HttpServletRequest request, Model model) {
ModelAndView result = new ModelAndView();
model.addAttribute("login", new Login());
result.addObject("resources", request.getContextPath() + "/resources");
result.addObject("appCtxt", request.getContextPath());
// return "redirect:/users";
result.setViewName("home");
return result;
}
#RequestMapping(value = "login", method = RequestMethod.POST)
public String login(Login login, HttpServletRequest request){
boolean status = loginService.verifyLogin(login.getId(), login.getPass());
if(status == true) {
return "redirect:/users";
}
else
{
return "error";
}
}
}
Instead of the name="{{pass}}" you can use name="pass" assuming you Login class contains a field with the very same name. Another thing is that you need '#ModelAttribute' annotation near the Login parameter.
For easier understanding how it works, please consider following example:
Student.java
package me.disper.model;
public class Student {
private String name;
private String surname;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
}
student.html
<!DOCTYPE html>
<html lang="en" xmlns:form="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<title>Create new student</title>
</head>
<body>
<form name="student" action="add" method="post">
Name: <input type="text" name="name" /><br/>
Surname: <input type="text" name="surname" /><br/>
<input type="submit" value="Save" />
</form>
</body>
</html>
MyMustacheController.java
package me.disper;
import me.disper.model.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class MyMustacheController {
#GetMapping("/student")
public ModelAndView createStudent(){
ModelAndView modelAndView = new ModelAndView("student", "student", new Student());
return modelAndView;
}
#PostMapping("/add")
public ModelAndView addStudent(#ModelAttribute Student student){
ModelAndView modelAndView = new ModelAndView("created", "student", student);
return modelAndView;
}
}
created.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Student created</title>
</head>
<body>
{{#student}}
Hello {{name}} {{surname}}
{{/student}}
</body>
</html>
Take a look at the following tutorial: A guide to forms in Spring MVC. There are some helpful hints like #ModelAttribute.

How do validation with thymeleaf and bean validation?

I'm trying to perform a simple validation in my view, I know that the jsf it is very simple to do more in the spring mvc is giving me a headache ...
Can anyone help me with this validation? see what I'm doing wrong ??
my model
package br.com.nextinfo.multimedia.web.model;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotBlank;
#Table
#Entity(name="slideshow")
public class SlideShow {
private Long condigo;
private String titulo;
private String subTitulo;
private ImagemSlider imagemSlider;
#Id
#GeneratedValue(generator="codigo",strategy=GenerationType.AUTO)
#SequenceGenerator(name = "codigo", sequenceName = "codigo_slideshow")
#Column(name = "CODIGO")
public Long getCondigo() {
return condigo;
}
#NotNull
#NotBlank
#Column(name = "TITULO" ,nullable = false)
public String getTitulo() {
return titulo;
}
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name ="CODIGO_IMAGEM")
public ImagemSlider getImagemSlider() {
return imagemSlider;
}
#NotNull
#NotBlank
#Column(name = "SUBTITULO" ,nullable = false)
public String getSubTitulo() {
return subTitulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public void setSubTitulo(String subTitulo) {
this.subTitulo = subTitulo;
}
public void setImagemSlider(ImagemSlider imagemSlider) {
this.imagemSlider = imagemSlider;
}
public void setCondigo(Long condigo) {
this.condigo = condigo;
}
}
my controller
package br.com.nextinfo.multimedia.web.controller;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import br.com.nextinfo.multimedia.web.model.ImagemSlider;
import br.com.nextinfo.multimedia.web.model.SlideShow;
import br.com.nextinfo.multimedia.web.services.AbstractFactoryService;
import br.com.nextinfo.multimedia.web.services.CreateSlideShowService;
import br.com.nextinfo.multimedia.web.services.ImagemServiceDatabase;
#Controller
#RequestMapping("/arquivosbanco/")
public class FilesDatabaseController implements AbstractControllerApp ,PadraoCrudMetodos<ImagemSlider> {
#Autowired
private ImagemServiceDatabase imagemService;
#Autowired
private CreateSlideShowService slideShowService;
#Override
public String getRequisicaoPadrao(Model model) {
List<ImagemSlider> lista = this.getAbstractService().realizaPaginacao("0", "10" ,null).getContent();
model.addAttribute("listaObjetoPageStart", lista);
model.addAttribute("img", new ImagemSlider());
return this.getUrlInicial();
}
#Override
public String getUrlInicial() {
return "arquivos/database/listarquivosbancodedados";
}
#ResponseBody
#RequestMapping(value = "/img", method = RequestMethod.GET)
public void showImage(#RequestParam("id") Long id, HttpServletResponse response,HttpServletRequest request) throws ServletException, IOException {
response.setContentType("image/jpeg, image/jpg, image/png, image/gif");
ImagemSlider imgdatabase = imagemService.getAbstractService().getBean(id);
if (imgdatabase!=null ) {
response.getOutputStream().write(imgdatabase.getImage());
response.getOutputStream().close();
}
}
#Override
public AbstractFactoryService<ImagemSlider> getAbstractService() {
return imagemService;
}
#RequestMapping(value = "/createslideshow/{imagemid}" ,method=RequestMethod.GET)
public String createslider(#PathVariable("imagemid") Long image,Model model){
final ImagemSlider img = this.imagemService.getBean(image);
model.addAttribute("imgslider", img);
model.addAttribute("slideshow", new SlideShow());
return "arquivos/createdisplay";
}
#RequestMapping(value = "/save" ,method=RequestMethod.POST)
public String saveSlideShowr( #RequestParam Long imagemid ,#Valid final SlideShow slideshow,final BindingResult result ,RedirectAttributes redirectAttrs){
ImagemSlider img = this.imagemService.getBean(imagemid);
if (result.hasErrors()) {
redirectAttrs.addFlashAttribute("org.springframework.validation.BindingResult.strategy", result);
redirectAttrs.addFlashAttribute("slideshow", slideshow);
return "redirect:/arquivosbanco/createslideshow/"+imagemid;
}else{
this.slideShowService.salva(slideshow);
if (img != null) {
slideshow.setImagemSlider(img);
this.slideShowService.salva(slideshow);
}
}
return this.getUrlInicial();
}
}
<html xmlns:th="http://www.thymeleaf.org"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorator="/templates/layouts/principal">
<head>
<title>Criacao slideshow</title>
</head>
<body>
<div class="container-fluid" layout:fragment="corpopagina">
<h3 class="page-header text-center">Criacao slide show</h3>
<form id="registration-form" class="form-horizontal" th:object="${slideShow}" th:action="#{/arquivosbanco/save/?imagemid=}+${imgslider.codigo}" method="post">
<!-- Print all errors here!-->
<div class="col-md-4 col-xs-12">
<div class="thumbnail">
<img class="img-responsive" th:attr="src=#{'/upload/img?codigo='+${imgslider.codigo}}" width="400" height="400" />
<span class="text-center"></span>
</div>
<div class="caption">
<h5>Codigo <span th:text="${imgslider.codigo}" class="badge" style="margin-left:20px">5</span></h5>
<h5>Nome <span th:text="${imgslider.nome}" class="badge" style="margin-left:20px">5</span></h5>
</div>
</div>
<div class="col-md-8 col-xs-12">
<div class="form-group">
<label class="col-xs-3 control-label">Titulo principal</label>
<div class="col-md-8">
<input type="text" class="form-control" name="titulo" />
</div>
</div>
<div class="form-group">
<label class="col-xs-3 control-label">Sub titulo</label>
<div class="col-md-8">
<input type="text" class="form-control input-xs" name="subTitulo" />
</div>
</div>
<div class="form-actions">
<label class="col-md-3 control-label"></label>
<div class="col-md-7">
<button type="submit" class="btn btn-success btn-large">Salvar</button>
</div>
<div class="col-md-1"></div>
</div>
</div>
</form>
</div>
</body>
in my controller is validating usually more in view does not show anything how can I solve?
I am quite some time on stackoverflow, most can not find the solution ...
Your view is not showing anything as you have not included the error messages in your template. Here is an example below.
<td th:if="${#fields.hasErrors('age')}" th:errors="*{age}">Name Error</td>

Resources