what should and where should i download for work with jsr-303 in spring? - 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.

Related

Why is it not showing data from controller in jsp file?

HomeController.java
package myapp;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
#EnableWebMvc
#Configuration
#Controller
public class HomeController {
#GetMapping(value = "/")
public ModelAndView index(ModelMap model) {
ModelAndView mav = new ModelAndView("index");
mav.addObject("greeting", "Welcomes you to Spring!");
model.addAttribute("message", "Hello world");
return mav;
//return "index";
}
}
index.jsp file
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String name = (String) request.getAttribute("message");
%>
<p><%= name %></p>
${message}
${greeting }
<%#include file='body.html'%>
</body>
</html>
In index.jsp file, it is not showing the data for ${message} and ${greeting}. How can I solve this? I am using Tomcat 9.

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

Spring and Hibernate Form Validation Error not show

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.

$() not working in jsp file

I have a Controller called Leave Controller which looks as follows.
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class LeaveController {
#RequestMapping("/")
public ModelAndView loginPage()
{
return new ModelAndView("jsp/login.jsp", "command", new Employee());
}
#RequestMapping(value="verify" ,method=RequestMethod.POST)
public String verify(Employee eform,ModelMap model)
{
System.out.println(EmployeeAccessService.verify(eform));
model.addAttribute("uname",eform.getName());
model.addAttribute("pass",eform.getPassword());
return "jsp/home.jsp";
}
}
The method login.jsp page sends an Employee pojo received as 'eform'. I add the two attributes to (ModelMap)model before going to home.jsp page.
Here is my home.jsp page.
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<title>Home</title>
</head>
<body>
$(uname)<br>
$(pass)
</body>
</html>
The thing is the $(uname) and $(pass) are displayed as text instead of variables. How do I display them as variables?
It's not $(), it's ${}:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<title>Home</title>
</head>
<body>
${uname}<br>
${pass}
</body>
</html>

I wonder connection between spring form tag & controller #RequestMapping() method

This jsp file 'selectDetail.jsp' for client inputs their information
and clicks 'update' button to 'update.do'
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><spring:message code="member.detail.title" arguments="${member.id}"/></title>
</head>
<body>
아이디 : ${member.id}<br>
비밀번호 : ${member.passwd }<br>
이름 : ${member.name }<br>
날짜 : ${member.reg_date }<br>
목록보기 |
update |
삭제 |
</body>
</html>
'UpdateController.java' is get 'update.do' command by '#RequestMapping'.
first, 'updateForm() is worked. b/c of method is get. go to 'updateForm.jsp'
package dr.mini.controller;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
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.servlet.ModelAndView;
import dr.mini.dao.MemberDao;
import dr.mini.domain.MemberCommand;
import dr.mini.validator.MemberValidator;
#Controller
public class UpdateController {
private Logger log = Logger.getLogger(this.getClass());
#Autowired
private MemberDao memberDao;
public void setMemberDao(MemberDao memberDao) {
this.memberDao = memberDao;
System.out.println("UpdateController의 setMemberDao()호출");
}
//1) Get방식: value(요청명령어), method(방식종류)
#RequestMapping(value="/update.do", method=RequestMethod.GET)
public ModelAndView updateForm(#RequestParam("id") String id){
MemberCommand memberCommand = memberDao.getMember(id);
System.out.println("1updateForm()");
return new ModelAndView("updateForm", "memberCommand", memberCommand);
}
//2) Post방식
#RequestMapping(value="/update.do", method=RequestMethod.POST)
public String submit(MemberCommand memberCommand, BindingResult result){
if(log.isDebugEnabled()){
log.debug("3memberCommand="+memberCommand);
}
MemberValidator mv = new MemberValidator();
System.out.println("validate 실행 전 ");
mv.validate(memberCommand, result);
System.out.println("validate 실행 후 ");
if(result.hasErrors()){
System.out.println("updateForm()으로 페이지 이동");
return "updateForm";
}
memberDao.updateMember(memberCommand);
return "redirect:/list.do";
}
}
'updateForm.jsp' outputs memberCommand information. client changes his infomation. He clicks '보내기' button. then go for 'UpdateController.java' again to call 'submit()'
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><spring:message code="member.update.title"/></title>
</head>
<body>
<h2>레코드 수정</h2>
<form:form commandName="memberCommand">
<form:errors element="div"/>
아이디 : ${memberCommand.id}<br>
비밀번호 : <form:password path="passwd" showPassword="false"/><font color="red"><form:errors path="passwd"/></font><br>
이름 : <form:input path="name"/><font color="red"><form:errors path="name"/></font> <br>
<input type="submit" value="보내기">
</form:form>
</body>
</html>
everyone,
I don't know how to call submit(). when client clicked '보내기' button with no 'update.do' path. Where is it to add this path.

Resources