Retrive object from controller class to jsp file [duplicate] - java

This question already has answers here:
Using for loop inside of a JSP
(2 answers)
Closed 6 years ago.
I'm developing an ecommerce store using spring mvc. Suddenly I need to user some information in the jsp file (view) from controller class. In controller class I create a ModelAndView object and use addAttribute to use objext in my jsp file. Then I got stuck. I can not use the object in jsp file.
Hi this is my user class
//package com.ecommerce.demo
package com.ecommerce.demo;
import javax.persistence.*;
#Entity
#Table(name="USER")
public class User {
#Id
private String userName;
private String userPassword;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
}
and this is my controller class
package com.ecommerce.controller;
import java.io.IOException;
import java.util.List;
import javax.websocket.Session;
import org.hibernate.*;
import org.hibernate.cfg.*;
import org.json.JSONArray;
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;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.ecommerce.demo.User;
#Controller
#RequestMapping(value="mainPageController")
public class MainPageController {
#RequestMapping(value="/mainPage.html")
public ModelAndView getLogInForm(#ModelAttribute("user") User userInput, BindingResult result) throws IOException {
List<User> userDatabase = null;
userDatabase = session.createQuery("from User").list();
session.beginTransaction();
session.close();
ModelAndView model = new ModelAndView("MainPage");
model.addObject("userNameAndPasswordList", userDatabase);
return model;
}
}
Now how can I print userName and userPassword in my mainPage.jsp file?
<%# page import="com.ecommerce.demo.User" %>
<%
Usinf java code(i.e for loop)
I need to print all userName and userPassword of user class here.
%>

You should write your mainPage.jsp like this and avoid the java code in it:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<table>
<c:forEach items="${userNameAndPasswordList}" var="user">
<tr>
<td>${user.userName}</td>
<td>${user.userPassword}</td>
</tr>
</c:forEach>
</table>

Use JSTL to print the result in your JSP file.
In this case you need to use foreach tag in JSTL
Here, your result is in object userNameAndPasswordList
Using $ syntax you can access the data of your object.
<c:forEach items="${userNameAndPasswordList}" var="userdetails">
<c:out value="${userdetails.userName}" />
<c:out value="${userdetails.userPassword}"/>
</c:forEach>

Use below code to fetch and print the data.
import JSTL tag in jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<table>
<c:if test="${userNameAndPasswordList!= null}">
<c:forEach items="${userNameAndPasswordList}" var="user">
<tr>
<td><c:out value="${user.userName}" /></td>
<td><c:out value="${user.userPassword}" /></td>
</tr>
</c:forEach>
</c:if>
</table>

Related

How do I display todos that are associated with a TodoList on Theymeleaf?

I am making a todo app in which there are TodoLists on the index page and when you click the TodoList, you can see all of the todos that are associated with it.
e.g. When you click the TodoList "Shopping" on the index page, you can see a show page which has "todos" like clothes, food etc.
TodoListController.java
package com.teamlab.todolist.web;
import com.teamlab.todolist.domain.TodoList;
import com.teamlab.todolist.repository.TodoListRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
#Controller
#RequestMapping("/todoLists")
public class TodoListController {
#Autowired
TodoListRepository todoListRepository;
#GetMapping
public String getAllTodoLists(Model model) {
List<TodoList> todoLists = todoListRepository.findAll();
model.addAttribute("todoLists", todoLists);
return "todoLists/index";
}
#GetMapping("{id}")
public String showAllTodos(#PathVariable Long id, Model model) {
TodoList todoList = todoListRepository.findOne(id);
model.addAttribute("todoList", todoList);
return "todoLists/show";
}
#PostMapping
public String createTodoList(#ModelAttribute TodoList todoList) {
todoListRepository.save(todoList);
return "redirect:/todoLists";
}
}
I don`t have any code written in my show.html page.
I previously worked on a Rails app where I had a course object and within that course object were lesson objects. I was able to display all the lessons associated with a single course by just pulling the associated views out in the view template as shown below.
<% #course.lessons.each do |lesson| %>
<h2><%= link_to lesson.title, lesson_path(lesson.id) %></h2>
<% end %>
I am not sure how to do it in Spring Boot and I`m also not sure whether this is the right approach to solving this issue.
You can do the same in thymeleaf using th:each. You are returning all the todoList using model.addAttribute("todoLists", todoLists);. You can process the data in todoLists in UI using
<table >
<tr th:each="todoList: ${todoLists}">
<td th:text="${todoList.name}"></td>
<td th:text="${todoList.priority}"></td>
<td th:text="${todoList.status}"></td>
</tr>
</table>

unable to link resource with controller class by using PathVariable technique in spring mvc

this is my index page:
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<h1>Employee List</h1>
<table border="2" width="70%" cellpadding="2">
<tr><th>Name</th><th>Address</th>
<th>City</th><th>Cars</th></tr>
<c:forEach var="emp" items="${list}">
<tr>
<td>${emp.name }</td>
<td>${emp.address }</td>
<td>${emp.city }</td>
<td>${emp.cars}</td>
<td>Edit
<td>Delete
</tr></c:forEach>
</table>
Add New Employee"
problem is when i click on other link than it works fine but when i click on editemp or deleteemp link,than it shows me error:The requested resource is not available
This is my controller class:
package first;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class EmpController {
#Autowired
EmployeeDao dao;
#RequestMapping("/empform")
public ModelAndView showForm()
{
return new ModelAndView("empform","command",new Employee());
}
#RequestMapping(value="/save",method=RequestMethod.POST)
public ModelAndView save(#ModelAttribute("emp") Employee employee)
{
dao.saveEmployee(employee);
return new ModelAndView("redirect:/viewemp");
}
#RequestMapping("/viewemp")
public ModelAndView viewemp()
{
List<Employee> list=dao.getAllEmployee();
return new ModelAndView("viewemp","list",list);
}
#RequestMapping(value="/editemp/{name}",method=RequestMethod.GET)
public ModelAndView edit(#PathVariable String name)
{
Employee e=dao.getbyName(name);
return new ModelAndView("empeditform","command",e);
}
#RequestMapping(value="/saveedit",method=RequestMethod.POST)
public ModelAndView saveedit(#ModelAttribute("emp")Employee employee)
{
dao.updateEmployee(employee);
return new ModelAndView("redirect:/viewemp");
}
#RequestMapping(value="/deleteemp/{name}",method=RequestMethod.GET)
public ModelAndView delete(#PathVariable String name)
{
dao.delete(name);
return new ModelAndView("redirect:/viewemp");
}
}
Please tell me,why it is unable to map with controller method specified in controller class.....thanks in advance
One thing to try for your links to to update them to use the context path:
<td>Edit
<td>Delete
This post has a few other ways that you can specify your routes in a jsp page:
[How to use relative paths without including the context root name?
Also, for the controller routes to be registered, you will need to set component scan to look for any annotations:
<context:component-scan base-package="namespace to controller class" />

Spring Boot JSP Resolution Error

So I've been playing around with Spring Boot and it's going fairly well. However, I've found myself in a weird situation and need help with it. All of my request mapping works with exception to one, for which I'm getting a 404.
My project structure is:
+Project Name
-src/main/java - Code
-src/main/resources - Resources
-src/main/webapp/views - Jsp Pages
Important java code:
Application.java
package com.demo.faisal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import com.demo.faisal.model.Task;
import com.demo.faisal.service.TaskService;
#Configuration
#ComponentScan()
//#EnableAutoConfiguration
#EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class})
public class Application {
private static final Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String args[]) {
SpringApplication.run(Application.class, args);
}
#Bean
public CommandLineRunner demo(TaskService taskService) {
return (args) -> {
// save a couple of customers
taskService.addTask(new Task("Learn Java"));
taskService.addTask(new Task("Learn Hibernate"));
taskService.addTask(new Task("Learn Spring"));
taskService.addTask(new Task("Learn SpringBoot"));
// fetch all tasks
log.info("Finding all tasks with getTasks():");
log.info("-------------------------------");
for (Task task : taskService.getAllTasks()) {
log.info(task.toString());
}
log.info("");
// fetch an individual customer by ID
Task task = taskService.findTask(1L);
log.info("Task found with findTask(1L):");
log.info("--------------------------------");
log.info(task.toString());
log.info("");
// fetch an individual customer by ID
task.setDescription("Learn Java Done");
log.info("Updated task description to: " + task.getDescription());
taskService.updateTask(task);
log.info("");
// Updated task
task = taskService.findTask(1L);
log.info("Updated Task (1L):");
log.info("--------------------------------");
log.info(task.toString());
log.info("");
};
}
}
Model:
package com.demo.faisal.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
//#Table(name = "${table_name})
public class Task {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String description;
public Task() {}
public Task(String description) {
this.description = description;
}
public Long getId() {
return id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return String.format("Task[id=%d, description='%s']", id, description);
}
}
Repository:
package com.demo.faisal.model;
import org.springframework.data.repository.CrudRepository;
public interface TaskRepository extends CrudRepository<Task, Long> {
}
Service:
package com.demo.faisal.service;
import java.util.List;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.demo.faisal.model.Task;
import com.demo.faisal.model.TaskRepository;
#Service
public class TaskServiceImpl implements TaskService {
#Autowired
private TaskRepository taskRepository;
#Override
#Transactional
public void addTask(Task task) {
taskRepository.save(task);
}
#Override
#Transactional
public void deleteTask(Long id) {
Task task = taskRepository.findOne(id);
taskRepository.delete(task);
}
#Override
#Transactional
public void updateTask(Task task) {
Task retrieved = taskRepository.findOne(task.getId());
retrieved.setDescription(task.getDescription());
taskRepository.save(retrieved);
}
#Override
#Transactional
public Task findTask(Long id) {
return taskRepository.findOne(id);
}
#Override
#Transactional
public List<Task> getAllTasks() {
return (List<Task>) taskRepository.findAll();
}
}
MVC Config File (Replacement for web.xml):
package com.demo.faisal.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
#Configuration
#EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("WEB-INF/pages/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("/index");
}
}
Controller:
package com.demo.faisal.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.demo.faisal.model.Task;
import com.demo.faisal.service.TaskService;
#Controller
public class TaskController {
#Autowired
private TaskService taskService;
#RequestMapping(value = "/tasks", method = RequestMethod.GET)
public ModelAndView getTasks() {
ModelAndView mav = new ModelAndView();
mav.setViewName("tasks");
List<Task> tasks = taskService.getAllTasks();
mav.addObject("tasks", tasks);
return mav;
}
#RequestMapping("/taskform")
public ModelAndView showform() {
return new ModelAndView("taskform","task",new Task());
}
#RequestMapping(value="/save",method = RequestMethod.POST)
public ModelAndView save(#ModelAttribute("task") Task task) {
taskService.addTask(task);;
return new ModelAndView("redirect:/tasks");//will redirect to viewemp request mapping
}
#RequestMapping(value="/delete_task/{id}",method = RequestMethod.GET)
public ModelAndView delete(#PathVariable long id) {
taskService.deleteTask(id);;
return new ModelAndView("redirect:/tasks");//will redirect to viewemp request mapping
}
#RequestMapping(value="/edit_task/{id}")
public ModelAndView update(#PathVariable long id) {
Task task = taskService.findTask(id);
System.out.println("Returning taskeditform jsp with task: " + task.toString());
return new ModelAndView("taskeditform","task",task);
}
#RequestMapping(value="/editsave",method = RequestMethod.POST)
public ModelAndView editsave(#ModelAttribute("task") Task task) {
taskService.updateTask(task);
return new ModelAndView("redirect:/tasks");//will redirect to viewemp request mapping
}
}
VIEW:
taskform.jsp
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Add New Task</h1>
<form:form method="post" action="save" commandName="task">
<table>
<tr>
<td>Task Description :</td>
<td><form:input path="description" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Update" /></td>
</tr>
</table>
</form:form>
taskeditform.jsp
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Edit Task</h1>
<form:form method="post" action="/editsave" commandName="task">
<table>
<tr>
<td>Id</td>
<td><form:hidden path="id" /></td>
</tr>
<tr>
<td>Task Description :</td>
<td><form:input path="desciption" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Update" /></td>
</tr>
</table>
</form:form>
tasks.jsp
<%# page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>Tasks List</h1>
<c:set var="contextPath" value="${pageContext.request.contextPath}" />
<table border="2" width="70%" cellpadding="2">
<tr>
<th>Id</th>
<th>Description</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<c:forEach var="task" items="${tasks}">
<tr>
<td>${task.id}</td>
<td>${task.description}</td>
<td>Edit</td>
<td>Delete</td>
</tr>
</c:forEach>
</table>
<br />
Add New Task
From my controller, all of my RequestMappings work fine, except /edit_task/{id}.
Everytime I call this url, I hit the breakpoint and can see it returning a new ModelAndView with the view pointing to taskeditform.jsp
However, I get a 404 error saying it cannot find the view. The error message is below:
type Status report
message /edit_task/WEB-INF/pages/taskeditform.jsp
description The requested resource is not available.
What I don't understand is the URL it's looking for : /edit_task/WEB-INF/pages/taskeditform.jsp. It looks like it is using the request mapping url and appending the view to it.
Can someone please point out what's going on here?
Thanks.

Spring MVC error validation error

index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<body>
<div align="center" style="margin-top:100px;">
<font face="verdana" size="2">
${welcomeMessage} <BR><BR>
${result}
<form:form action="${pageContext.request.contextPath}/login.html" method="POST" modelAttribute="loginForm">
<table>
<tr>
<td colspan="2" align="center">Spring MVC Form Demo - Login</td>
</tr>
<tr>
<td>User Name</td>
<td><form:input path="username" /> <form:errors path="username"></form:errors></td>
</tr>
<tr>
<td>Password</td>
<td><form:password path="password" /> <form:errors path="password"></form:errors></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Login" style="background-color:white;" /></td>
</tr>
</table>
</form:form>
Register if not already registered
</font>
</div>
</body>
</html>
HelloController.java
package java4s;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.annotation.Scope;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
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.servlet.ModelAndView;
import java4s.model.Login;
#Controller
public class LoginSuccessController {
#Autowired
EmployeeService emp_service;
#RequestMapping(value = "/login", method=RequestMethod.POST)
public ModelAndView loginvalidateForm(ModelMap model, #ModelAttribute("loginForm") Login login, BindingResult result, HttpSession session) {
if(result.hasErrors()){
model.addAttribute("result", "All Fields are neccessary");
return new ModelAndView("index",model);
}
if(emp_service.validateLogin(login.getUsername(), login.getPassword()))
{
List<Employee> user_info = emp_service.getUserinfo(login.getUsername());
session.setAttribute("session_username", login.getUsername()); //Add value to session variable
model.addAttribute("result", "Login Success");
model.addAttribute("user_info", user_info);
return new ModelAndView("LoginSuccess",model);
}
else
{
model.addAttribute("result", "Login Failure");
return new ModelAndView("index",model);
}
}
}
Login.java
package java4s.model;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Login {
#NotNull
#Size(min = 3, max = 20)
private String username;
#NotNull
#Size(min = 3, max = 20)
private String password;
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
}
I am trying to put validation on the login fields when they are empty, but errors are not showing on the index page the the login fields are empty. What is the problem in the code?
You have to add the annotation #Valid ( see the spring doc for more details) :
public ModelAndView loginvalidateForm(ModelMap model, #Valid #ModelAttribute("loginForm") Login login, BindingResult result, HttpSession session) {
....
}
Don't forget to enable “mvc:annotation-driven” to make Spring MVC supports #Valid annotation.
Add the following tag to your application context XML file.
<mvc:annotation-driven />

Spring Mvc 4 - <form:errors/> Not Working

I am new to Spring MVC
I am using in my application & it is not showing error along with field.
Please look into the following code
Employee.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="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>Zaptech</title>
</head>
<body>
<form action="save">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name" id="name"></td>
<td><form:errors path="name"></form:errors></td>
</tr>
<tr>
<td>Blood Group</td>
<td><input type="text" name="bloodGroup" id="bloodGroup"></td>
<td><form:errors path="bloodGroup"></form:errors></td>
</tr>
<tr>
<td><input type="submit" value="Save"></td>
</tr>
</table>
</form>
</body>
</html>
EmployeeController.java
import java.io.IOException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.jagir.hrm.Validator.EmployeeValidator;
import com.jagir.hrm.model.Employee;
import com.jagir.hrm.service.EmployeeService;
#Controller
public class EmployeeController
{
#Autowired
EmployeeService empService;
#Autowired
EmployeeValidator empValidator;
#RequestMapping(value="/")
public String homePage()
{
System.out.println("Inside intel");
return "employee";
}
#RequestMapping(value="employee")
public String showEmployee()
{
return "employee";
}
#RequestMapping(value="save")
public String saveEmployee(#ModelAttribute("command") #Validated Employee e , BindingResult result) throws IOException
{
System.out.println("Inside employee :: " + e.getName());
//throw new IOException("Excption");
System.out.println(result);
empValidator.validate(e, result);
System.out.println(result);
System.out.println(result.hasErrors());
if(result.hasErrors())
{
System.out.println("Error has occured");
}
else
{
System.out.println("No Errors continue to save records");
empService.saveEmployee(e);
}
return "employee";
}
}
EmployeeValidator.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.jagir.hrm.model.Employee;
import com.jagir.hrm.service.EmployeeService;
#Component
public class EmployeeValidator implements Validator
{
#Autowired
EmployeeService employeeService;
public boolean supports(Class<?> clazz)
{
return Employee.class.equals(clazz);
}
public void validate(Object target, Errors errors)
{
System.out.println("validation of objects");
Employee employee = (Employee) target;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "employee.name.notempty");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "bloodGroup", "employee.bloodGroup.size");
if(employee.getBloodGroup().length()>=2)
{
System.out.println("Inside blood groups");
errors.rejectValue("bloodGroup", "employee.bloodGroup.size");
}
}
}
If i input proper values then it working properly and goes to database but,
When i input 5 characters in blood group it throws error which i can see in console but in my web page i am not able to see error along with blood group field.
Employee.jsp uses plain HTML form element + Spring form:errors tag.
form:errors tag is supposed to be used inside form:form tag (or spring:bind tag to be precise).
Try to use form:form tag and see how it works. I also suggest to use form:input instead of plain HTML input.
<form:form modelAttribute="command" action="save"
...
<form:input path="name"/>
<form:errors path="name"/>
...
</form>

Categories

Resources