Spring MVC webapp HTTP Status 400 - spring

Im developing a webapp with Spring and hibernate. I have a simple form with a text field and a select:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# page language="java" contentType="text/html; charset=utf8" pageEncoding="utf8" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# page trimDirectiveWhitespaces="true" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="Content-Language" content="English"/>
<!-- <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta http-equiv="Content-Language" content="es"/>-->
<link rel="stylesheet" media="all" href="<c:url value="/resources/site.css"/>">
<title>Nuevo expediente</title>
</head>
<body>
<h2>Nuevo expediente</h2>
<form:form modelAttribute="expediente" method="post">
<table>
<tr>
<td>Tipo de expediente:</td>
<td>
<form:select path="tipoExpediente">
<form:option value="-" label="Seleccione un tipo"/>
<form:options items="${expedientes}" itemValue="tipoExpediente" itemLabel="tipoExpediente" />
</form:select>
<form:errors path="tipoExpediente" element="span"/>
</td>
</tr>
<tr>
<td>Estado:</td>
<td>
<form:input path="estado"/>
<form:errors path="estado" element="span"/>
</td>
</tr>
</table>
<br/>
<input type="submit" value="Create" />
</form:form>
</body>
</html>
The form show correctly, but when i submit, I get a HTTP Status 400 exception, with the description:
description The request sent by the client was syntactically incorrect ()..
I have read that it would be caused by requestparams, but i not using them.
Here is my controller:
package com.atlantis.atecliente.controller;
import com.atlantis.atecliente.model.Book;
import com.atlantis.atecliente.model.Expediente;
import com.atlantis.atecliente.model.TipoExpediente;
import com.atlantis.atecliente.repository.ExpedienteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class ExpedienteController {
#Autowired
protected ExpedienteService service;
#RequestMapping(value = {"/*", "/expedientes"})
public String getExpedientes(Model model) {
List<Expediente> expedientes = service.getExpedientes();
model.addAttribute("expedientes", expedientes);
return "expediente";
}
#RequestMapping(value = "nuevo-expediente")
public String createExpedienteGet(Model model) {
model.addAttribute("expediente", new Expediente());
List<TipoExpediente> tiposExpediente = service.getTiposExpedientes();
// List<String> canales = service.getCanales();
model.addAttribute("expedientes", tiposExpediente);
// model.addAttribute("canales", canales);
return "nuevo-expediente";
}
#RequestMapping(value = "nuevo-expediente", method = RequestMethod.POST)
public String createExpedientePost(#ModelAttribute("expediente") Expediente expediente) {
service.createExpediente(expediente);
return "redirect:expedientes";
}
}
Finalyy the Expediente class:
package com.atlantis.atecliente.model;
import java.util.Date;
import javax.persistence.*;
#Entity
#Table(name="Expediente")
public class Expediente {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int codExpediente;
#ManyToOne
#JoinColumn(name = "tipoExpediente")
private TipoExpediente tipoExpediente;
#ManyToOne
#JoinColumn(name = "estadoExpediente")
private EstadoExpediente estadoExpediente;
#ManyToOne
#JoinColumn(name = "expedientePadre")
private Expediente expedientePadre;
#ManyToOne
#JoinColumn(name = "tipoRelacion")
private TipoRelacion tipoRelacion;
#ManyToOne
#JoinColumn(name = "canalEntrada")
private CanalExpediente canalEntrada;
#ManyToOne
#JoinColumn(name = "idiomaEntrada")
private IdiomaExpediente idiomaEntrada;
#ManyToOne
#JoinColumn(name = "idiomaSalida")
private IdiomaExpediente idiomaSalida;
#ManyToOne
#JoinColumn(name = "tipoResolucion")
private TipoResolucion tipoResolucion;
#ManyToOne
#JoinColumn(name = "canalSalida")
private CanalExpediente canalSalida;
#Column(length = 30)
private String estado;
#Column(length = 10)
private String numeroSerie;
#Column(length = 10)
private String numeroHoja;
#Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date fechaRedaccion;
#Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date fechaRecepcion;
#Column(length = 200)
private String asunto;
#Column (length = 1000)
private String descripcion;
#Column(length = 20)
private String usuarioRegistro;
#Temporal(javax.persistence.TemporalType.DATE)
private Date fechaRegistro;
#Column (length = 20)
private String usuarioModificacion;
#Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date fechaModificacion;
#Column (length = 20)
private String usuarioCierre;
#Temporal(javax.persistence.TemporalType.TIMESTAMP)
private Date fechaCierre;
public int getCodExpediente() {
return codExpediente;
}
public void setCodExpediente(int codExpediente) {
this.codExpediente = codExpediente;
}
public EstadoExpediente getEstadoExpediente() {
return estadoExpediente;
}
public void setEstadoExpediente(EstadoExpediente estadoExpediente) {
this.estadoExpediente = estadoExpediente;
}
public Expediente getExpedientePadre() {
return expedientePadre;
}
public void setExpedientePadre(Expediente expedientePadre) {
this.expedientePadre = expedientePadre;
}
public TipoRelacion getTipoRelacion() {
return tipoRelacion;
}
public void setTipoRelacion(TipoRelacion tipoRelacion) {
this.tipoRelacion = tipoRelacion;
}
public CanalExpediente getCanalEntrada() {
return canalEntrada;
}
public void setCanalEntrada(CanalExpediente canalEntrada) {
this.canalEntrada = canalEntrada;
}
public IdiomaExpediente getIdiomaEntrada() {
return idiomaEntrada;
}
public void setIdiomaEntrada(IdiomaExpediente idiomaEntrada) {
this.idiomaEntrada = idiomaEntrada;
}
public IdiomaExpediente getIdiomaSalida() {
return idiomaSalida;
}
public void setIdiomaSalida(IdiomaExpediente idiomaSalida) {
this.idiomaSalida = idiomaSalida;
}
public TipoResolucion getTipoResolucion() {
return tipoResolucion;
}
public void setTipoResolucion(TipoResolucion tipoResolucion) {
this.tipoResolucion = tipoResolucion;
}
public CanalExpediente getCanalSalida() {
return canalSalida;
}
public void setCanalSalida(CanalExpediente canalSalida) {
this.canalSalida = canalSalida;
}
public String getUsuarioRegistro() {
return usuarioRegistro;
}
public void setUsuarioRegistro(String usuarioRegistro) {
this.usuarioRegistro = usuarioRegistro;
}
public String getNumeroSerie() {
return numeroSerie;
}
public void setNumeroSerie(String numeroSerie) {
this.numeroSerie = numeroSerie;
}
public String getNumeroHoja() {
return numeroHoja;
}
public void setNumeroHoja(String numeroHoja) {
this.numeroHoja = numeroHoja;
}
public Date getFechaRedaccion() {
return fechaRedaccion;
}
public void setFechaRedaccion(Date fechaRedaccion) {
this.fechaRedaccion = fechaRedaccion;
}
public Date getFechaRecepcion() {
return fechaRecepcion;
}
public void setFechaRecepcion(Date fechaRecepcion) {
this.fechaRecepcion = fechaRecepcion;
}
public String getAsunto() {
return asunto;
}
public void setAsunto(String asunto) {
this.asunto = asunto;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public Date getFechaRegistro() {
return fechaRegistro;
}
public void setFechaRegistro(Date fechaRegistro) {
this.fechaRegistro = fechaRegistro;
}
public String getUsuarioModificacion() {
return usuarioModificacion;
}
public void setUsuarioModificacion(String usuarioModificacion) {
this.usuarioModificacion = usuarioModificacion;
}
public Date getFechaModificacion() {
return fechaModificacion;
}
public void setFechaModificacion(Date fechaModificacion) {
this.fechaModificacion = fechaModificacion;
}
public String getUsuarioCierre() {
return usuarioCierre;
}
public void setUsuarioCierre(String usuarioCierre) {
this.usuarioCierre = usuarioCierre;
}
public Date getFechaCierre() {
return fechaCierre;
}
public void setFechaCierre(Date fechaCierre) {
this.fechaCierre = fechaCierre;
}
public TipoExpediente getTipoExpediente() {
return tipoExpediente;
}
public void setTipoExpediente(TipoExpediente tipoExpediente) {
this.tipoExpediente = tipoExpediente;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
}
Some help?
Thanks

I have resolve this issue. The problem was with the controller method mapping to the url.
I modified the function createExpedientePost to:
public String createExpedientePost(#ModelAttribute("expediente") Expediente expediente, BindingResult result) {
The change was the addition of BindingResult as an argument.
I hope this may help others.

It seems somebody can get such error status, when arguments for a controller method were set incorrectly.
For instance I had the same because of wrong name of referer header(It was called as referrer)
public String foo(#RequestHeader(value = "referer") final String referer) {}

Related

Spring MVC Form not taking object path

Error shown is Bean property 'emergencyComplaint.emergencyComplaint' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
The getters and setters have the same return type, still it is showing this error.
JSP Page
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>CRS | Kolkata</title>
</head>
<body>
<div>
<h1>Lodge an Emergency Complaint Now</h1>
<form:form action="" method="post" modelAttribute="people">
<form:label
path="emergencyComplaint.emergencyComplaint"
for="emergencyComplaint"
>
Emergency Complaint
</form:label>
<form:input
type="text"
name="emergencyComplaint"
id="emergencyComplaint"
path="emergencyComplaint.emergencyComplaint"
/>
<form:label
path="emergencyComplaint.status"
for="emergencyComplaintStatus"
>Status</form:label
>
<form:input
type="text"
name="emergencyComplaintStatus"
id="emergencyComplaintStatus"
path="emergencyComplaint.status"
></form:input>
<form:label path="name" for="name">Name</form:label>
<form:input path="name" type="text" name="name" id="name" />
<form:label path="phoneNumber" for="phoneNumber"
>Phone Number</form:label
>
<form:input
path="phoneNumber"
type="text"
name="phoneNumber"
id="phoneNumber"
/>
<button type="submit">Lodge</button>
</form:form>
</div>
</body>
</html>
Model Class
package com.naha.crimereportingsystem.people;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import com.naha.crimereportingsystem.emergencyComplaint.EmergencyComplaint;
#Entity
public class People {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String phoneNumber;
#OneToMany(targetEntity = EmergencyComplaint.class, cascade = CascadeType.ALL)
private List<EmergencyComplaint> emergencyComplaint;
public People() {
}
public People(long id, String name, String phoneNumber) {
this.id = id;
this.name = name;
this.phoneNumber = phoneNumber;
this.emergencyComplaint = (List<EmergencyComplaint>) new EmergencyComplaint();
}
public List<EmergencyComplaint> getEmergencyComplaint() {
return emergencyComplaint;
}
public void setEmergencyComplaint(List<EmergencyComplaint> emergencyComplaint) {
this.emergencyComplaint = emergencyComplaint;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(final String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setName(final String name) {
this.name = name;
}
}
Mapped Other Model Class
package com.naha.crimereportingsystem.emergencyComplaint;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class EmergencyComplaint {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
long id;
private String emergencyComplaint;
private String status;
public String getEmergencyComplaint() {
return emergencyComplaint;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public void setEmergencyComplaint(String emergencyComplaint) {
this.emergencyComplaint = emergencyComplaint;
}
public EmergencyComplaint(long id, String emergencyComplaint, String status) {
this.id = id;
this.emergencyComplaint = emergencyComplaint;
this.status = status;
}
public EmergencyComplaint(String emergencyComplaint, String status) {
this.emergencyComplaint = emergencyComplaint;
this.status = status;
}
public EmergencyComplaint() {
}
}
This is a valid error. Take a close look at your Entity and your modelAttribute. There is no such thing emergencyComplaint.emergencyComplaint.
So, instead of:
<form:input type="text" name="emergencyComplaint" id="emergencyComplaint" path="emergencyComplaint.emergencyComplaint" />
Try this:
<form:input type="text" name="emergencyComplaint" id="emergencyComplaint" path="emergencyComplaint" />
I do not have OneToMany example handy but I think you are smart enough to identify the issue by now while reading this. If not then to get an idea, take a look at this and this.

Not mapping all fields from html to controller

I need to update my category object
my model:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
#Entity
public class Category {
#Id
#GeneratedValue
private int id;
#NotNull
private String name;
private String description;
#NotNull
private Long created;
private Long updated;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getCreated() {
return created;
}
public void setCreated(Long created) {
this.created = created;
}
public Long getUpdated() {
return updated;
}
public void setUpdated(Long updated) {
this.updated = updated;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
Here my controller:
#Controller
public class CategoryController {
private CategoryRepository categoryRepository;
private static Logger logger = LogManager.getLogger(CategoryController.class);
// If class has only one constructore then #Autowired wiil execute automatically
public CategoryController(CategoryRepository categoryRepository) {
this.categoryRepository = categoryRepository;
createStubCategoryList();
}
#PostMapping(value = "/category")
public String submitCategory(Category category, Model model) {
logger.info("updateCategory = " + category);
model.addAttribute("submitted", true);
model.addAttribute("category", category);
categoryRepository.save(category);
return "category";
}
#RequestMapping("category/edit/{id}")
public String editCategory(#PathVariable("id") int id, Model model) {
Optional<Category> category = categoryRepository.findById(id);
logger.info("find_category = " + category);
model.addAttribute("category", category);
return "category";
}
Here my template to edit category:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="${appName}">Category template title</title>
<link th:href="#{/public/style.css}" rel="stylesheet"/>
<meta charset="UTF-8"/>
</head>
<body>
<div class="container">
<form method="post" action="#" th:object="${category}" th:action="#{/category}">
<h3>Category</h3>
<input type="text" placeholder="name" id="name" th:field="*{name}"/>
<textarea placeholder="Description of the category" rows="5" id="description"
th:field="*{description}"></textarea>
<input type="submit" value="Submit"/>
</form>
<div class="result_message" th:if="${submitted}">
<h3>Your category has been submitted.</h3>
<p>Find all categories here</p>
</div>
</div>
</body>
</html>
When call method in log has:
[INFO ] 2020-01-07 19:38:07.493 [http-nio-8090-exec-8] CategoryController - find_category = Optional[
Category{id=2, name='Electronics', created=1578418669105, updated=null, description='Electronics's description'}]
and here screen:
As you can see the field created=1578418669105
Nice.
Now I edit name "Electronics" to "Electronics2" and click submit.
As result call method: submitCategory in my controller. Nice.
Here result in log:
[INFO ] 2020-01-07 19:40:23.327 [http-nio-8090-exec-2] CategoryController - updateCategory =
Category{id=0, name='Electronics2', created=null, updated=null, description='Electronics's description'}
but as you can see the field created is null. Why?
I need to update only editable fields: name and description.
Another fields (like created, updated, id) must not change. This fields are not mapped.
How I can do this?
Because created, updated, id you need to pass as hidden. It is not available in html page.
Each column should be changed to updatable to false because by default is true.
#Column(name = "created", updatable = false)
private Long created;

Unable to fetch Data from database using Spring Hibernate maven

Program is executing Select query is also running in console but not displaying on page,please check the program and correct me thank you
Output
Output of the Program
product class
package com.ecom.Model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
#Entity
#Table(name="product")
public class Product {
#Id
#Column
private int id;
#Column
#NotNull
#Size(min=1,message="is required")
private String product_name;
#Column
#NotNull
#Size(min=1,message="is required")
private String manufacturer;
#Column
private int stock;
#Column
private String description;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public int getStock() {
return stock;
}
public void setStock(int stock) {
this.stock = stock;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Product(int id, String product_name, String manufacturer, int stock, String description) {
super();
this.id = id;
this.product_name = product_name;
this.manufacturer = manufacturer;
this.stock = stock;
this.description = description;
}
public Product()
{}
#Override
public String toString() {
return "Product [id=" + id + ", product_name=" + product_name + ", manufacturer=" + manufacturer + ", stock="
+ stock + ", description=" + description + "]";
}
}
product controller class
In controller i have created the model to save the data into model with the help of Product reference calling getAllProduct method.
package com.ecom.Controller;
import java.util.List;
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.RequestMapping;
import com.ecom.DAO.ProductDAO;
import com.ecom.Model.Product;
#Controller
public class ProductController {
//injecting Dependecy
#Autowired
private ProductDAO productDAO;
#RequestMapping("/ProductList")
public String ListProducts(Model theModel)
{
List<Product> theProducts = productDAO.getAllProduct();
theModel.addAttribute("products",theProducts);
return "productlist";
}
#RequestMapping("/ProductForm")
public String ProductForm(Model theModel)
{
Product theProduct = new Product();
theModel.addAttribute("addProduct", theProduct);
return "productform";
}
#RequestMapping("/saveProduct")
public String saveProduct(#ModelAttribute("addProduct") Product theProdut)
{
productDAO.addProducts(theProdut);
return "productform";
}
}
Product Dao Implementation
package com.ecom.DAOImplementation;
import java.util.List;
import javax.transaction.Transactional;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.ecom.DAO.ProductDAO;
import com.ecom.Model.Product;
#Repository("ProductDAO")
public class ProductImpl implements ProductDAO {
#Autowired
private SessionFactory sessionFactory;
#Transactional
public List<Product> getAllProduct() {
Session currentSession = sessionFactory.getCurrentSession();
Query<Product> theQuery = currentSession.createQuery("from Product",Product.class);
List<Product> products = theQuery.getResultList();
return products;
}
#javax.transaction.Transactional
public void addProducts(Product theProdut)
{
Session currentSession = sessionFactory.getCurrentSession();
System.out.println("Adding Product");
currentSession.save(theProdut);
System.out.println("Success");
}
}
Jsp page
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# 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">
<title>Insert title here</title>
</head>
<body>
<table border="1px">
<tr>
<th>ID</th>
<th>Product Name</th>
<th>Manufacturer</th>
<th>Stock</th>
<th>Description</th>
</tr>
<c:forEach var="tempCustomer" items="${products}">
<tr>
<td> ${tempCustomer.id} </td>
<td> ${tempCustomer.product_name} </td>
<td> ${tempCustomer.manufacturer} </td>
<td> ${tempCustomer.stock} </td>
<td> ${tempCustomer.description} </td>
</tr>
</c:forEach>
</table>
</body>
</html>
Just tried to set this up by creating a sample list as shown below.
#RequestMapping("/ProductList")
public String ListProducts(Model theModel)
{
List<Product> theProducts = productDAO.getAllProduct();
Product product = new Product(1,"pro-1","man-1",10,"pro-1 desc");
theProducts.add(product);
product = new Product(2,"pro-2","man-2",10,"pro-2 desc");
theProducts.add(product);
product = new Product(3,"pro-3","man-3",10,"pro-3 desc");
theProducts.add(product);
product = new Product(4,"pro-4","man-4",10,"pro-4 desc");
theProducts.add(product);
product = new Product(5,"pro-5","man-5",10,"pro-5 desc");
theProducts.add(product);
theModel.addAttribute("products",theProducts);
return "productlist";
}
The JSP page productlist.jsp is as is. No changes done. I get the output as below.
You can perhaps try putting up debug statements to see if the theProducts is correctly populated.

Spring MVC test failure

I'm writing simple integration tests for my app using the Spring MVC Test framework. I have two basic test cases:
The Add link form is filled in correctly (the URL and optional description input fields are entered) and a link is added to a database via POST and then the client is redirected to the /link URL.
The Add link form is empty, so the /links/create view is rendered and form errors from BindingResult are presented.
The testAddLink() test passes successfully, but the problem occurs with the testAddEmptyLink() test method.
In this test, the 'links/create' view should be rendered and I should get a 200 status code once the expression
result.hasErrors()
is true.
However, I'm getting a 302 response, which should be sent when there are no errors in the form (the URL has been set correctly)
It seems the test method testAddEmptyLink() cannot deal with form errors with BindingResult.
Do you have any ideas what could be the cause it cannot deal with form errors?
Thanks in advance.
Link Entity
#Entity
#Table(name = "links")
public class Link {
#Id #GeneratedValue
private Integer ID;
#Column(name = "url") #NotNull #NotEmpty #URL
private String URL;
private String description;
#Column(name="created_at", nullable = false)
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
private LocalDateTime createdAt;
#Column(name="updated_at", nullable = true)
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
private LocalDateTime updatedAt;
#ManyToOne
#JoinColumn(name = "category_id")
private Category category;
public Integer getID() {
return ID;
}
public void setID(Integer ID) {
this.ID = ID;
}
public String getURL() {
return URL;
}
public void setURL(String URL) {
this.URL = URL;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public LocalDateTime getUpdateddAt() {
return updatedAt;
}
public void setUpdateddAt(LocalDateTime updateddAt) {
this.updatedAt = updateddAt;
}
public LocalDateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(LocalDateTime updatedAt) {
this.updatedAt = updatedAt;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
LinkController
#Controller
public class LinkController {
#Autowired(required = true) #Qualifier(value = "linkService")
private LinkService linkService;
#Autowired
private CategoryService categoryService;
#RequestMapping(value = "/links")
public String getLinks(Model model) {
model.addAttribute("results", linkService.getLinks());
return "links/index";
}
#RequestMapping(value = "/links/create", method = RequestMethod.GET)
public ModelAndView showLinkForm() {
ModelAndView model = new ModelAndView("links/create");
model.addObject("link", new Link());
model.addObject("categories", categoryService.getCategories());
return model;
}
#RequestMapping(value = "/links/create", method = RequestMethod.POST)
public String addLink(#Valid #ModelAttribute("link") Link link, BindingResult result, Model model) {
if (result.hasErrors()) {
model.addAttribute("categories", categoryService.getCategories());
return "links/create";
}
linkService.addLink(link);
return "redirect:/links";
}
}
LinkControllerTest
#ContextConfiguration(classes = {AppInitializer.class})
#RunWith(SpringJUnit4ClassRunner.class)
public class LinkControllerTest {
#Mock
private LinkService linkService;
#InjectMocks
private LinkController linkController;
private MockMvc mockMvc;
#Before
public void setUp() {
// Process mock annotations
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.standaloneSetup(linkController).build();
}
#Test
public void testAddLink() throws Exception {
mockMvc.perform(post("/links/create")
.param("URL", "http://test.com")
.param("description", "Lorem Ipsum")
.param("category.ID", "1"))
.andExpect(status().is3xxRedirection())
.andExpect(view().name("redirect:/links"));
}
#Test
public void testAddEmptyLink() throws Exception {
mockMvc.perform(post("/links/create")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.sessionAttr("link", new Link())
)
.andExpect(status().isOk())
.andExpect(view().name("links/create"))
.andExpect(forwardedUrl("/WEB-INF/views/links/create.jsp"))
.andExpect(model().attributeHasFieldErrors("link", "URL", "description"))
.andExpect(model().attribute("link", hasProperty("URL", isEmptyOrNullString())))
.andExpect(model().attribute("link", hasProperty("description", isEmptyOrNullString())));
}
}
create.jsp (View)
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
<title>Create Category</title>
</head>
<body>
<form:form action="" modelAttribute="category">
<div>
<form:label path="name">Name</form:label>
<form:input path="name" />
<form:errors path="name" cssClass="error"></form:errors>
</div>
<div>
<form:label path="description">Description</form:label>
<form:input path="description" />
<form:errors path="description" cssClass="error"></form:errors>
</div>
<div>
<input type="submit" value="Create Category">
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</div>
</form:form>
</body>
</html>

javax.el.PropertyNotFoundException: Property 'name' not found on type java.lang.String [duplicate]

This question already has answers here:
c:forEach throws javax.el.PropertyNotFoundException: Property 'foo' not found on type java.lang.String
(3 answers)
Closed 7 years ago.
I'm getting the error above.
What i'm trying to do is write an app that takes in an unknown number of names, then prints them out on a new page. This is supposed to be for a bowling scoring app, but for now I just want to get a list of names. The idea is for each name to go into a player object, then in turn be stored in the players arraylist. If anyone can help, I would appreciate it.
This is my controller code:
package multiplayergame;
import java.util.ArrayList;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
#Controller
#SessionAttributes
public class MultiplayerController {
int score;
int roll;
Game game = new Game();
GameProperties gameProps = new GameProperties();
int playerNo = 0;
ArrayList<PlayerGame> players = new ArrayList<>();
PlayerGame player;
#RequestMapping(value = "/home", method = RequestMethod.GET)
public ModelAndView home() {
return new ModelAndView("home", "command", gameProps);
}
#RequestMapping(value = "/nextName", method = { RequestMethod.POST, RequestMethod.GET})
public ModelAndView homeNext(MContact mcontact, BindingResult result) {
player = new PlayerGame();
player.setName(mcontact.getName());
players.add(player);
gameProps.setPlayers(players);
playerNo++;
return new ModelAndView("home", "command", gameProps);
}
#RequestMapping(value = "/test", method = RequestMethod.POST)
public ModelAndView playNext(GameProperties gameProps2, ModelMap model) {
model.addAttribute("players", gameProps.getPlayers());
model.addAttribute("name", gameProps.getPlayers().get(playerNo).getName());
return new ModelAndView("test", "players", gameProps2);
}
}
This holds details for each player:
package multiplayergame;
public class PlayerGame {
private int score;
private int pins;
private String name;
private int roll;
private int nOfPlayers;
private int playerNo;
Game game = new Game();
public Game getGame() {
return game;
}
public void setGame(Game game) {
this.game = game;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int getPins() {
return pins;
}
public void setPins(int pins) {
this.pins = pins;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRoll() {
return roll;
}
public void setRoll(int roll) {
this.roll = roll;
}
public int getnOfPlayers() {
return nOfPlayers;
}
public void setnOfPlayers(int nOfPlayers) {
this.nOfPlayers = nOfPlayers;
}
public int getPlayerNo() {
return playerNo;
}
public void setPlayerNo(int playerNo) {
this.playerNo = playerNo;
}
}
This is the code for all Game properties, such as scoring etc.
package multiplayergame;
import java.util.ArrayList;
public class GameProperties {
private int score;
private int pins;
private String name;
private int roll;
private int nOfPlayers;
PlayerGame player;
private ArrayList<PlayerGame> players;
private int playerNo;
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int getPins() {
return pins;
}
public void setPins(int pins) {
this.pins = pins;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRoll() {
return roll;
}
public void setRoll(int roll) {
this.roll = roll;
}
public int getnOfPlayers() {
return nOfPlayers;
}
public void setnOfPlayers(int nOfPlayers) {
this.nOfPlayers = nOfPlayers;
}
public ArrayList<PlayerGame> getPlayers() {
return players;
}
public void setPlayers(ArrayList<PlayerGame> players) {
this.players = players;
}
public int getPlayerNo() {
return playerNo;
}
public void setPlayerNo(int playerNo) {
this.playerNo = playerNo;
}
}
The following are my JSP files, the output first:
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Test output</title>
</head>
<body>
<h2>Test Roll</h2>
<c:forEach var="player" items="players">
Name <c:out value="${player.name}"/><p>
</c:forEach>
</body>
</html>
This is the home page:
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Bowling</title>
</head>
<body>
<h2>Welcome players!</h2>
<h2>Please enter your names.</h2>
<form:form method="post" action="/multiplayergame/nextName">
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name = "button" value="Next Player"/>
</td>
</tr>
</table>
</form:form>
<form:form method="post" action="/multiplayergame/test">
<tr>
<td colspan="2">
<input type="submit" name = "button" value="Play"/>
</td>
</tr>
</form:form>
</body>
</html>
Change this <c:forEach var="player" items="players"> to <c:forEach var="player" items="${players}">
As your referring "players" string. it is trying to find the property name in string.

Resources