Spring and Hibernate Form Validation Error not show - spring

This is my customer.java class using for as bean
package com.zeeshan.form;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Customer {
private String firstName;
#NotNull(message="is required")
#Size(min=1)
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
CustomerController.java
package com.zeeshan.form;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
#RequestMapping("/customer")
public class CustomerController {
#RequestMapping("/showForm")
public String showFormModel(Model theModel) {
theModel.addAttribute("customer", new Customer());
return "customer-form";
}
#RequestMapping("/processForm")
public String processForm(#ModelAttribute("customer") #Valid Customer theCustomer, BindingResult theBindingresult) {
if(theBindingresult.hasErrors()) {
return "customer-form";
}
else {
return "customer-confirmation";
}
}
}
customer-form.jsp
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<style>
.error{
color: red;
}
</style>
</head>
<body>
<h2>Customer Registeration Form</h2>
<form:form action="processForm" modelAttribute="customer">
First Name : <form:input path="firstName"/>
<br><br>
Last Name (*) : <form:input path="lastName"/>
<form:errors path="lastName" cssClass="error" />
<br><br>
<input type="submit" value="Submit" />
</form:form>
</body>
</html>
Hibernate validator doesn't work.
my code run properly but doesn't show any error
I am attaching file structure
following libraries are being used
hibernate version 6.0.2
spring version 5.0.6

The code looks fine. Reading your question, it seems that you might be a little confused between these two:
Hibernate ORM: Implementation of JPA
Hibernate Validator: Implementation of Bean Validation
So, for Bean Validation to work, you need to add Hibernate Validator in classpath. Means simply add it in dependencies of your build.gradle/pom.xml i.e. the build script of your build tool.

Related

String boot getVideo always returns NullPointerException

Good Morning. Can someone help me please?
I followed this tutorial https://www.knowledgefactory.net/2021/09/spring-boot-webflux-video-streaming.html to create a video streaming app. Inside the resources folder there is a subfolder which has two MP4 files inside.
The problem happens when I hit the getVideo inside the next class:
package net.javaguides.springboot.implementations;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;
#Service
public class StreamingService {
private static final String FORMAT = "classpath:videos/%s.mp4";
private ResourceLoader resourceLoader;
public Mono<Resource> getVideo(String title) {
return Mono.fromSupplier(() -> resourceLoader.getResource(String.format(FORMAT, title)));
}
}
The controller uses a configuration bean which is as follows:
package net.javaguides.springboot.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import net.javaguides.springboot.implementations.StreamingService;
import reactor.core.publisher.Mono;
#Configuration
public class EndPointConfig {
#Autowired
private StreamingService service;
#Bean
public RouterFunction<ServerResponse> router() {
return RouterFunctions.route().GET("video/{title}", this::videoHandler).build();
}
private Mono<ServerResponse> videoHandler(ServerRequest serverRequest) {
String title = serverRequest.pathVariable("title");
return ServerResponse.ok().contentType(MediaType.valueOf("video/mp4")).body(service.getVideo(title),
Resource.class);
}
}
And Controller endpoint that retrieves video stream is as follows:
#Controller
#AllArgsConstructor
public class VideoController {
private StreamingService streamingService;
#GetMapping(value = "video/{title}", produces = "video/mp4")
#ResponseBody
public Mono<Resource> getVideos(#PathVariable String title, #RequestHeader("Range") String range) {
System.out.println("Range in bytes = " + range);
return streamingService.getVideo(title);
}
#GetMapping("show")
public String show() {
return "video";
}
}
And finally, the application has an html file that has a video tag whose src attribute points to the show method of the controller to display the player as follows:
<!DOCTYPE html>
<html
lang="en"
xmlns:th="http://www.thymeleaf.org"
xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity5"
xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
layout:decorate="~{layout_navigation.html}">
<head>
<meta charset="UTF-8">
<title>OBR-VIDEOTHEQUE</title>
<meta
name="viewport"
content="width=device-width, initial-scale=1.0">
<!-- <link rel="stylesheet" href="styles.css"> -->
<style type="text/css">
#video-player {
display: none;
}
#video-form {
width: 60%;
}
.error {
color: red;
}
.success {
color: green;
}
</style>
</head>
<body>
<section layout:fragment="content">
<meta charset="utf-8">
<div class="container mt-5">
<h2>Video streaming</h2>
<video src="video/movie" type="video/mp4" width="720" height="480" controls preload="none">
</video>
</div>
</section>
<section layout:fragment="footer">
<footer class="container py-5 text-center footer">
<div class="row">
<div class="col-md-12">
<p class="text-muted">© 2022. Tous
droits réservés.</p>
</div>
</div>
</footer>
</section>
<section layout:fragment="scripts">
<script th:src="#{/js/jQuery-min.js}"></script>
<script
type="text/javascript"
th:src="#{/js/dropdown.js}"></script>
<script th:src="#{/js/bootstrap.bundle.js}"></script>
<script th:src="#{/js/bootstrap.min.js}"></script>
<script th:src="#{/js/select2.min.js}"></script>
<!-- <script th:src="#{/js/main.js}"></script> -->
</section>
</body>
</html>
After running the application, in the url i type http://localhost:8082/show
From that Url, the video player shows up. When I hit the play button, i get 500 Error saying this:
java.lang.NullPointerException: null
at net.javaguides.springboot.implementations.StreamingService.lambda$0(StreamingService.java:17)
This is third day i tried to spot where is the error with no success.
Can someone tell me where I'm getting things wrong.
I highly thank in advance anybody that will take time to help me.
Regards,
You have a not initialized ResourceLoader.
Change this line of code
private ResourceLoader resourceLoader;
in these ones:
#Autowired
private ResourceLoader resourceLoader;
This will tell Spring Context to inject an instance of ResourceLoader in your attribute.

Sending object from thymeleaf template to Rest Controller returns "Unsupported Media Type"

I'm trying to POST some object fields to a RestController using thymeleaf.
But the result of the post returns what looks like a parsing error :
There was an unexpected error (type=Unsupported Media Type, status=415). Content type
'application/x-www-form-urlencoded;charset=UTF-8' not supported
The index page sends two attributes to the controller which then calls the business service that builds the new object.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Simple Sidebar - Start Bootstrap Template</title>
<!-- Bootstrap core CSS -->
<link th:href="#{/index/vendor/bootstrap/css/bootstrap.min.css}"
rel="stylesheet">
<!-- Custom styles for this template -->
<link th:href="#{/index/css/simple-sidebar.css}" rel="stylesheet">
</head>
<body>
<!-- Page Content -->
<div id="page-content-wrapper">
<div class="container-fluid">
<form action="#" th:action="#{/accounts}" th:object="${account}" method="post" enctype="application/json">
<div class="form-row">
<div class="form-group col-md-4 ">
<label for="inputState">Departement</label>
<input type="text" th:field="*{owner}" class="form-control" placeholder="Type in the department ..." />
</div>
</div>
<div class="form-row">
<div class="form-group col-md-4 ">
<label for="inputState">Budget</label>
<input type="number" step="0.01" th:field="*{budget}" class="form-control" placeholder="Type in Budget ..." />
</div>
</div>
<button class="btn btn-primary" type="submit">Enregistrer</button>
</form>
</div>
</div>
<!-- /#page-content-wrapper -->
</body>
</html>
This is the Rest Controller :
#RestController
public class AccountController {
#Autowired
private AccountService accountService;
#RequestMapping(value="/accounts", method=RequestMethod.POST)
public void addAccount(#RequestBody Account account ) {
accountService.addAccount(account);
}
}
Account is a simple POJO :
public class Account {
private String id;
private String owner;
private double budget;
private double budgetInvest;
private double budgetFonction;
public Account() {
}
public Account(String id,String owner, double budget, double budgetInvest, double budgetFonction
) {
super();
this.id = id;
this.owner=owner;
this.budget = budget;
this.budgetInvest = budgetInvest;
this.budgetFonction = budgetFonction;
}
public Account (String owner, double budget) {
this.owner = owner;
this.budget=budget;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public double getBudget() {
return budget;
}
public void setBudget(double budget) {
this.budget = budget;
}
public double getBudgetInvest() {
return budgetInvest;
}
public void setBudgetInvest(double budgetInvest) {
this.budgetInvest = budgetInvest;
}
public double getBudgetFonction() {
return budgetFonction;
}
public void setBudgetFonction(double budgetFonction) {
this.budgetFonction = budgetFonction;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
}
And the add method simply adds the object to a list of objects.
What am i doing wrong here ?
I think problem in you controller. First it won't be #RestController. It will be #Controller. Second it won't be #RequestBody. It will be #ModelAttribute.So write your controller like
#Controller
public class AccountController {
#Autowired
private AccountService accountService;
#RequestMapping(value="/accounts", method=RequestMethod.POST)
public void addAccount(#ModelAttribute("account") Account account ) {
System.out.ptintln("Checking");
accountService.addAccount(account);
}
The most relevant to the discussion of REST, the #RestController annota- tion tells Spring that all handler methods in the controller should have their return value written directly to the body of the response, rather than being carried in the model to a view for rendering. This line from book spring in action. So here you should use #Controller annotation.
You can use restcontroller but u must using ajax post for run "/account"
Cmiiw

Property [id] not found on type [java.util.Optional]

I am trying to perform crud operation with spring boot and i am new to it. I have successfully performed delete and create part. The problem i am having when i am trying to edit my fields. I am using MYSQL as my database. I am having error mentioned in question title. Any help to resolve it and please check my logic i think my logic is wrong in /showUpdate method. When i press edit button then it is not taking me to edit page and throwing me this error.
My controller class is pasted below:
Snapshot of Actual error i am having
package com.bilal.location.controllers;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.RequestParam;
import com.bilal.location.entities.Location;
import com.bilal.location.service.LocationService;
#Controller
public class LocationController {
#Autowired
LocationService service;
#RequestMapping("/showCreate")
public String showCreate() {
return "createLocation";
}
#RequestMapping("/savLoc")
public String saveLocation(#ModelAttribute("location") Location location,ModelMap modelMap) {
Location locationSaved = service.saveLocation(location);
String msg = "Location saved with id: " + locationSaved.getId();
modelMap.addAttribute("msg", msg);
return "createLocation";
}
#RequestMapping("/displayLocations")
public String displayLocations(ModelMap modelMap) {
List<Location> locations = service.getAllLocations();
modelMap.addAttribute("locations", locations);
return "displayLocations";
}
#RequestMapping("/deleteLocation")
public String deleteLocation(#RequestParam("id")int id,ModelMap modelMap) {
Location location = new Location();
location.setId(id);
service.deleteLocation(location);
List<Location> locations = service.getAllLocations();
modelMap.addAttribute("locations", locations);
return "displayLocations";
}
#RequestMapping("/showUpdate")
public String showUpdate(#RequestParam("id")int id,ModelMap modelMap) {
Optional<Location> location = service.getLocationById(id);
modelMap.addAttribute("location", location);
return "updateLocation";
}
#RequestMapping("/updateLoc")
public String updateLocation(#ModelAttribute("location") Location location,ModelMap modelMap) {
service.updateLocation(location);
List<Location> locations = service.getAllLocations();
modelMap.addAttribute("locations", locations);
return "displayLocations";
}
}
Display Location JSP Page:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#page isELIgnored="false" %>
<!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>Display Locations</title>
</head>
<body>
<h2>Locations:</h2>
<%--Table Starting from here --%>
<table>
<tr>
<th>id</th>
<th>code</th>
<th>name</th>
<th>type</th>
</tr>
<c:forEach items = "${locations}" var="location" >
<tr>
<td>${location.id}</td>
<td>${location.code}</td>
<td>${location.name}</td>
<td>${location.type}</td>
<td>delete</td>
<td>edit</td>
</tr>
</c:forEach>
</table>
<%--Table Ending here --%>
Add Location
</body>
</html>
Update Location JSP Page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#page isELIgnored="false" %>
<!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>Create Location</title>
</head>
<body>
<form action="updateLoc" method="post">
<pre>
id: <input type="text" name="id" value = "${location.id}" readonly/>
code: <input type="text" name="code" value = "${location.code}"/>
name: <input type="text" name="name" value = "${location.name}"/>
type: rural <input type ="radio" name="type" value ="RURAL" ${location.type=='URBAN'?'checked':'' }/>
Urban <input type ="radio" name="type" value= "URBAN" ${location.type=='RURAL'?'checked':'' }/>
<input type="submit" name="save"/>
</pre>
</form>
</body>
</html>
Read the error message carefully. It says you are trying to acces .id, but not on your Location, but on an Optional instead - which doesn't have that property.
Check your code:
#RequestMapping("/showUpdate")
public String showUpdate(#RequestParam("id")int id,ModelMap modelMap) {
Optional<Location> location = service.getLocationById(id);
modelMap.addAttribute("location", location);
return "updateLocation";
}
You are not adding the location, but an Optional that might contain the location.
You can check whether an Optional holds a value by calling ìsPresent(), e.g.
if (location.isPresent()) {
modelMap.addAttribute("location", location.get());
} else {
// ERROR?
}
More on Optional, if you are not familiar: https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html
In my case it was solve by
In controller
ModelAndView modelAndView = new ModelAndView();
Optional<Employee> employee = employeeRepository.findById( employeeDto.getId());
if (employee.isPresent()) {
modelAndView.addObject("employeeDto", employee.get());
System.out.println(employee);
} else {
System.out.println("Error Found"); // error message
}
In views

Error message not showing in view page in JSR303, using Bootstrap in jsp

I am adding server side validation in my project. and somehow the error message from controller is not reaching view page.
I am using :
spring
jpa,
JSR303 for validation, and
bootstrap
Below is code for add.jsp
<!DOCTYPE html>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script
src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<style>
.error {
color: #ff0000;
}
.errorblock {
color: #000;
background-color: #ffEEEE;
border: 3px solid #ff0000;
padding: 8px;
margin: 16px;
}
</style>
<title>Add User</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="col-md-4">
<h2>Add User</h2>
<form:form action="user" method="post" role="form"
commandName="user">
<form:errors path="*" cssClass="errorblock" />
<div class="form-group ">
<label for="user">User Name:</label>
<form:input type="text" class="form-control" path="name"
id="name" placeholder="Enter User Name" required="requried"/>
</div>
<div class="form-group">
<label for="email">Email Address:</label>
<form:input type="email" path="emailAddress" class="form-control"
id="email" placeholder="Enter Email Address" required="requried"/>
</div>
<div class="form-group">
<label for="role">Role:</label>
<form:select path="role" class="form-control" id="role" required="requried">
<option disabled selected></option>
<c:forEach var="role" items="${roles}">
<option value="${role.value}">${role.name}</option>
</c:forEach>
</form:select>
</div>
<button type="submit" value="Submit" name="add"
class="btn btn-info active">Submit</button>
Back
</form:form>
</div>
<div class="col-md-4">
<div class="col-md-4"></div>
</div>
</div>
</div>
</div>
</body>
</html>
Below is code for Controller.java
#RequestMapping(value = "/user", params = "add", method = RequestMethod.GET)
public String getAddUser(Model model) {
ArrayList<Role> roles = new ArrayList<Role>();
// From user Add only admin and head of department can be added
roles.add(Role.ADMIN);
roles.add(Role.HEAD_OF_DEPARTMENT);
model.addAttribute("roles", roles);
model.addAttribute("user", new User());
return "user/add";
}
#RequestMapping(value = "/user", params = "add", method = RequestMethod.POST)
public String postAddUser(#ModelAttribute #Valid User user,
BindingResult result) {
if (result.hasErrors()) {
return "redirect:user?add";
} else {
System.out.println("Inside postAddUser");
user = userRepository.save(user);
return "redirect:user?id=" + user.getId();
}
}
Below is code for User.java
package in.ac.jmi.entities;
import in.ac.jmi.constants.Role;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
#Entity
#Table(name="USER")
public class User extends UrlEntity{
#Column(name="NAME", nullable = false)
#NotEmpty(message="Name can not be empty")
private String name;
#Column(name="ROLE", nullable = false)
#NotNull(message="Role can not be left blank")
private Role role;
#Column(name = "EMAIL_ADDRESS", nullable = false)
#NotEmpty(message="email address can not be empty")
private String emailAddress;
public User(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
#Override
public String toString() {
return "\nUser [name=" + name + ", role=" + role + ", emailAddress="
+ emailAddress + "]";
}
}
The reason is you are using return "redirect:user?add";, which cleared the error messages in model, try change it to return "user?add";

what should and where should i download for work with jsr-303 in spring?

what should i download for working with validation in spring.know annotations are unknown in my classes for example in blow code:
public String register2( #Valid User user , BindingResult br)
{
if(br.hasErrors())
{
return "edit";
}
//System.out.println("you registers!");
return "thanks";
}
#valid is unknown .which library should i download for work with jsr-303 standard in spring mcv?and where should i download?
and how i setup that in eclipse helious?
thanks
EDIT:MY CODE APPENDED=>
my controller=>
package codes;
import java.util.Map;
import javax.validation.Valid;
import javax.validation.Validator;
import org.apache.jasper.tagplugins.jstl.core.Out;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.BindingResultUtils;
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.portlet.ModelAndView;
#org.springframework.stereotype.Controller
public class Controller {
#RequestMapping(value="/register/" , method=RequestMethod.GET)
public String register(Model model)
{
model.addAttribute("myUser",new User());
return "edit";
}
#RequestMapping(value="/register/" , method=RequestMethod.POST)
public String register2( ModelAndView model,#Valid User myUser , BindingResult br)
{
try
{
if(br.hasErrors())
{
return "edit";
}
else
{
System.out.println(myUser);
System.out.println(myUser.getName());
System.out.println(myUser.getFamily());
System.out.println("salam");
return "thanks";
}
}
catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
return "thanks";
}
}
my edit.jsp page(form)=>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<!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>Register</title>
</head>
<body>
<div>
<sf:form method="post" modelAttribute="myUser" >
<label for="USER_NAME">name:</label>
<sf:input path="name" id="USER_NAME"/>
<sf:errors path="name" ></sf:errors>
<br>
<label for="USER_FAMILY">family:</label>
<sf:input path="family" id="USER_FAMILY"/>
<br>
<input type="submit" value="REGISTER" />
</sf:form>
</div>
</body>
</html>
NOTE:only when my user object is invalide i get exception and when thatz valid i give not exeption
You can use Hibernate Validator.
To run it, you need to add these jars to your project:
hibernate-validator*.jar
validation-api*.jar
slf4j-api*.jar
You can find all of them in the Hibernate Validator package.

Resources