Not mapping all fields from html to controller - spring-boot

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;

Related

Problem with controller return statement not performed (about redirect)

I'm working on a side project and it's been delayed for several days. When I run my code, I always can't run it from the "return redirect:/" part of the controller.
The result I expected is that I think of moving from sentence "return redirect:/" to another page, but everything seems fine inside, but only sentence "return redirect:/" is not performed.
I am using Mysql, SpringBoot, JPA, Spring Data Jpa, Lombok. What is the problem?
This is View to receive email and password.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel = "stylesheet" href ="/css/sample.css">
<link href="https://getbootstrap.com/docs/5.2/assets/css/docs.css" rel="stylesheet">
<link href="/css/font.css" rel = "stylesheet">
<link href="/css/navbar.css" rel = "stylesheet">
<title>loginpage</title>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/js/bootstrap.bundle.min.js"></script>
<script type="text/javascript">
function functionclick() {
let email = document.getElementById('exampleDropdownFormEmail1').value;
let password = document.getElementById('exampleDropdownFormPassword1').value;
if (email == "" || password == "") {
alert("회원 정보를 입력하세요");
history.back();
} else{
const url = new URL("/trylogin",location);
url.searchParams.append('email',email);
url.searchParams.append('password',password);
location = url;
}
}
</script>
</head>
<body class="p-3 m-0 border-0 bd-example">
<!-- Example Code -->
<div class="dropdown-menu">
<form class="px-4 py-3" method="get" action="login">
<div class="mb-3">
<label for="exampleDropdownFormEmail1" class="form-label">이메일을 입력하세요</label>
<input type="text" class="form-control" id="exampleDropdownFormEmail1" placeholder="email#example.com" name = "email">
</div>
<div class="mb-3">
<label for="exampleDropdownFormPassword1" class="form-label">비밀번호를 입력하세요.</label>
<input type="password" class="form-control" id="exampleDropdownFormPassword1" placeholder="Password" name = "password">
</div>
<div class="mb-3">
<div class="form-check">
<input type="checkbox" class="form-check-input" id="dropdownCheck">
<label class="form-check-label" for="dropdownCheck">
비밀번호 기억하기
</label>
</div>
</div>
<button type="submit" class="btn btn-primary" ONCLICK="functionclick()">확인</button>
</form>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="http://localhost:8080/signup">회원가입 하기</a>
<a class="dropdown-item" href="http://localhost:8080/forgotpassword">비밀번호 찾기</a>
</div>
<!-- End Example Code -->
</body>
</html>
This is LoginController
#Controller
public class LoginController {
#Autowired
private
UserService userService;
#GetMapping("/trylogin")
public String login(LoginDto loginDto) {
try {
if(userService.login(loginDto).isPresent()) {
return "redirect:/loginSuccess";
}
} catch (Exception e) {
e.printStackTrace();
return "redirect:/loginFailed";
}
return "redirect:/loginFailed";
}
#GetMapping("/loginSuccess")
public String loginSuccess() {
return "login_success";
}
#GetMapping("/loginFailed")
public String loginFailed() {
return "login_failed";
}
}
It is a service layer and the Repository used spring data jpa.
#Service
#RequiredArgsConstructor
#Getter
public class UserService {
#Autowired
private UsersRepository usersRepository;
#Transactional
public Optional<Users> login(LoginDto loginDto) throws Exception{
return usersRepository.findByEmailAndPassword(loginDto.getEmail(), loginDto.getPassword());
}
}
This is the Users entity to perform the query.
#Entity
#Getter
#NoArgsConstructor
#AllArgsConstructor
#Table(uniqueConstraints = {#UniqueConstraint(columnNames = {"ssn","phone_number"})})
public class Users {
#Column(name = "email", length = 40, updatable = false, nullable = false)
#Id
private String email;
#Column(name = "password", length = 20, nullable = false)
private String password;
#Column(name = "name", length = 25, nullable = false)
private String name;
#Column(name = "phone_number", length = 12, nullable = false)
private String phoneNumber;
#Column(name = "ssn", length = 13, nullable = false, updatable = false)
private String ssn;
#Embedded
private Address address;
#Column(name = "point")
private Long point;
#OneToMany(mappedBy = "postedUser")
private List<PostInfo> uploadedPost = new ArrayList<>();
#OneToMany(mappedBy = "userId")
private List<PointHistory> pointHistories = new ArrayList<>();
#Embedded
private Dates dates;
public Users(UserInfoDto userInfoDto){
this.setEmail(userInfoDto.getEmail());
this.setPassword(userInfoDto.getPassword());
this.setPhoneNumber(userInfoDto.getPhone_number());
this.setSsn(userInfoDto.getSsn());
this.setPoint(0L);
this.setName(userInfoDto.getName());
Address address = new Address(
userInfoDto.getCity_name(),
userInfoDto.getTown_name(),
userInfoDto.getStreet_name(),
userInfoDto.getZip_code(),
userInfoDto.getDetails()
);
this.setAddress(address);
List<PostInfo> postInfoList = new ArrayList<>();
List<PointHistory> pointHistoryList = new ArrayList<>();
this.setUploadedPost(postInfoList);
this.setPointHistories(pointHistoryList);
Dates dates = new Dates(LocalDateTime.now(), LocalDateTime.now());
this.setDates(dates);
}
public void setEmail(String id) {
this.email = id;
}
public void setPassword(String password) {
this.password = password;
}
public void setName(String name) {
this.name = name;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setSsn(String ssn) {
this.ssn = ssn;
}
public void setAddress(Address address) {
this.address = address;
}
public void setPoint(Long point) {
this.point = point;
}
public void setUploadedPost(List<PostInfo> uploadedPost) {
this.uploadedPost = uploadedPost;
}
public void setPointHistories(List<PointHistory> pointHistories) {
this.pointHistories = pointHistories;
}
public void setDates(Dates dates) {
this.dates = dates;
}
}
This is LoginDto (To transfer to the controller)
#Getter
#Setter
#AllArgsConstructor
public class LoginDto {
private String email;
private String password;
}
The page for redirection.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login Success</title>
<script type = "text/javascript">
alert("로그인 성공");
location.href = "/";
</script>
</head>
<body>
</body>
</html>

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.

How to Display Map Objects in c:forEach Jsp file

I am trying to display HashMap object values in <c:forEach. But Only I cannot display Object values. <c:forEach var="empl" items="${empList}"> In this case empl.name is not working
I Only can display object.value in jsp file. Maybe I making mistake in sending Map object to jsp file
My Controller employerController.java
``
#Controller
public class employerController {
#RequestMapping(value = "/empList",method = RequestMethod.GET)
public String employerList(){
return "employerMain";
}
#RequestMapping(value = "/empl_account",method = RequestMethod.POST)
public String AddEmployer(#RequestParam("name") String name, ModelMap modelMap){
String employerName = name;
HashMap<Employer,String> map = new HashMap<>();
Employer one = new Employer(1,"Jack","jack#gmail.com",200000);
Employer two = new Employer(2,"Oven","oven#gmail.com",450000);
Employer three = new Employer(3,"Nick","nick#gmail.com",600000);
map.put(one,one.getName());
map.put(two,two.getName());
map.put(three,three.getName());
modelMap.addAttribute("empList",map);
return "employerList";
}
}
``
my Employeer.java
``
private int id;
private String name;
private String email;
private int salary;
public Employer(int id, String name, String email, int salary) {
this.id = id;
this.name = name;
this.email = email;
this.salary = salary;
}
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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
``
my employerList.jsp
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2>Submitted Employer Information</h2>
<ol>
<c:forEach var="empl" items="${empList}">
<li>${empl.value.id}</li>
<li>${empl.value.name}</li>
<li>${empl.value.email}</li>
</c:forEach>
</ol>
</body>
</html>
I wan to see id,name,email in jsp file
1 Nick nick#gmail.com
2 Jack jack#gmail.com
Instead of map, you can take a list as follows :
#RequestMapping(value = "/empl_account",method = RequestMethod.POST)
public String AddEmployer(#RequestParam("name") String name, ModelMap modelMap){
String employerName = name;
List<Employer> employers = new ArrayList<>();
Employer one = new Employer(1,"Jack","jack#gmail.com",200000);
Employer two = new Employer(2,"Oven","oven#gmail.com",450000);
Employer three = new Employer(3,"Nick","nick#gmail.com",600000);
employers.add(one);
employers.add(two);
employers.add(three);
modelMap.addAttribute("empList",employers);
return "employerList";
}
in Jsp :
employerList.jsp
<c:forEach items="${empList}" var="employee">
<tr>
<td>Employee ID: <c:out value="${employee.id}"/></td>
<td>Employee Pass: <c:out value="${employee.name}"/></td>
</tr>
</c:forEach>
if you want the previous map, then do as follows :
(here in map key, the actual object resides, so you need to access the key)
<c:forEach var="empl" items="${empList}">
<li>${empl.key.id}</li>
<li>${empl.key.name}</li>
<li>${empl.key.email}</li>
</c:forEach>

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>

Spring MVC webapp HTTP Status 400

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) {}

Resources