view not display data in table using mysql spring mvc and jpa - java

i am follwing this tutorial https://www.codejava.net/frameworks/spring/spring-mvc-spring-data-jpa-hibernate-crud-example . I successfully save data into database using jpa but it not disply on index.jsp, index page show normal html tags data but not retrieving data from database. Please have a look into my code.
index.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page isELIgnored="false" %>
<html>
<head>
</head>
<title>
Student Manager
</title>
<body>
<div align="center">
<h1>Student Manager</h1>
<form method="get" action="search">
<input type="text" name="keyword"/>
<input type="submit" name="search"/>
</form>
<h2>Add new Student</h2>
<table border="1" cellpadding="5">
<tr>
<th>Id</th>
<th>Name</th>
<th>Age</th>
<th>Qualification</th>
<th>Mobile</th>
<th>Action</th>
</tr>
<c:forEach items="${ModelList}" var="listStudent">
<tr>
<td>${listStudent.id} </td>
<td>${listStudent.name} </td>
<td>${listStudent.age} </td>
<td>${listStudent.qualification} </td>
<td>${listStudent.mobile} </td>
<td>
Edit
Delete
</td>
</tr></c:forEach>
</table>
</div>
</body>
</html>
controller
package com.uc.student;
import java.util.List;
import java.util.Map;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class StudentController {
#Autowired
private StudentService studentservice;
#RequestMapping("/")
public ModelAndView home() {
List<Student> list=studentservice.listAll();
ModelAndView model=new ModelAndView();
model.addObject("ModelList",list);
return model;
}
#RequestMapping("/new")
public String newStudentForm(Map<String,Object> model) {
Student student=new Student();
model.put("student",student);
return "new_student";
}
#RequestMapping(value="/save", method=RequestMethod.POST)
public String saveStudent(#ModelAttribute("student") Student student) {
studentservice.save(student);
return "redirect:/";
}
}
new_student.jsp
<%# 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" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%# page isELIgnored="false" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Add new Student</title>
</head>
<body>
<h2>Add New Student</h2>
<br>
<div align="center">
<form:form method="post" action="save" modelAttribute="student">
<table>
<tr><td>Name : <form:input path="name"/></td></tr>
<tr><td>Age : <form:input path="age"/></td></tr>
<tr><td>Qualification : <form:input path="qualification"/></td></tr>
<tr><td>Mobile : <form:input path="mobile"/></td></tr>
<tr><td><input type="submit" value="save"/></td></tr>
</table>
</form:form>
</div>
</body>
</html>
StudentService .java
package com.uc.student;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service
#Transactional
public class StudentService {
#Autowired StudentRepository repo;
public void save(Student student) {
repo.save(student);
}
public List<Student> listAll(){
return (List<Student>)repo.findAll();
}
public Student getById(Long id) {
return repo.findById(id).get();
}
public void delete(Long id) {
repo.deleteById(id);
}
}

Related

I'm trying to build a E-commerce website using Spring. I have added the cart functionality. But when I click on order button the cart is not updated

CartItemController
package com.emusicstore.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
#Controller
#RequestMapping("/cart")
public class CartItemController {
#RequestMapping
public String get(HttpServletRequest request)
{
return "redirect:/cart/"+request.getSession(true).getId(); //Session id is used as cart Id
}
#RequestMapping(value="/{cartId}",method= RequestMethod.GET)
public String getCart(#PathVariable(value="cartId") String cartId, Model model)
{
model.addAttribute("cartId",cartId);
return "cart";
}
}
CartController.java
package com.emusicstore.controller;
import com.emusicstore.dao.CartDao;
import com.emusicstore.dao.ProductDao;
import com.emusicstore.model.Cart;
import com.emusicstore.model.CartItem;
import com.emusicstore.model.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
#Controller
#RequestMapping("/rest/cart")
//Rest services we need to start,starts with rest in path
public class CartController {
#Autowired
private CartDao cartDao;
#Autowired
private ProductDao productDao;
#RequestMapping(value="/{cartId}",method= RequestMethod.GET)
public #ResponseBody Cart read(#PathVariable(value ="cartId") String cartId)
{
return cartDao.read(cartId);
}
//#Response Body returns a model object in JSON Format
//Cart object which is returned is put into #ResponseBody and because of jackson deendendency The sping converts the object
//to JSON format and puts in #ResponseBody
//Reverse Process
#RequestMapping(value="/{cartId}",method=RequestMethod.PUT)
#ResponseStatus(value= HttpStatus.NO_CONTENT)
public void update(#PathVariable(value="cartId") String cartId, #RequestBody Cart cart)
{
cartDao.update(cartId,cart);
}
//Read something-GET
//Post something in UrL=POST
//Update info-PUT
#RequestMapping(value="/{cartId}",method=RequestMethod.DELETE)
#ResponseStatus(value=HttpStatus.NO_CONTENT)
public void delete(#PathVariable(value="cartId")String cartId)
{
cartDao.delete(cartId);
}
#RequestMapping(value="/add/{productId}",method=RequestMethod.PUT)
#ResponseStatus(value=HttpStatus.NO_CONTENT)
public void addItem(#PathVariable(value="productId")String productId, HttpServletRequest request)
{
String sessionId=request.getSession(true).getId();
Cart cart=cartDao.read(sessionId);
if(cart==null)
{
cart=cartDao.create(new Cart(sessionId));
}
Product product=productDao.getProductById(productId);
if(product==null)
{
throw new IllegalArgumentException(new Exception());
}
cart.addCartItem(new CartItem(product));
cartDao.update(sessionId,cart);
}
#RequestMapping(value="/remove/{productId}",method = RequestMethod.PUT)
#ResponseStatus(value=HttpStatus.NO_CONTENT)
public void removeItem(#PathVariable String productId, HttpServletRequest request)
{
String sessionId=request.getSession(true).getId();
Cart cart=cartDao.read(sessionId);
if(cart==null)
{
cart=cartDao.create(new Cart(sessionId));
}
Product product=productDao.getProductById(productId);
if(product==null)
{
throw new IllegalArgumentException(new Exception());
}
cart.removeCartItem(new CartItem(product));
cartDao.update(sessionId,cart);
}
#ExceptionHandler(IllegalArgumentException.class)
#ResponseStatus(value= HttpStatus.BAD_REQUEST,reason="Illegal request, Please your verify your payload")
public void handleClientErrors(Exception e)
{
}
#ExceptionHandler(Exception.class)
#ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR,reason="Internal Server Error")
public void handleServerErrors(Exception e)
{
}
}
CartDaoImpl.java
package com.emusicstore.dao.impl;
import com.emusicstore.dao.CartDao;
import com.emusicstore.model.Cart;
import org.springframework.stereotype.Repository;
import java.util.HashMap;
import java.util.Map;
#Repository
public class CartDaoImpl implements CartDao {
private Map<String, Cart> listOfCarts;
public CartDaoImpl()
{
listOfCarts=new HashMap<String, Cart>();
}
#Override
public Cart create(Cart cart) {
if(listOfCarts.keySet().contains(cart.getCartId())){
throw new IllegalArgumentException(String.format("Cannot create a cart. A cart " +
"with given id(%)"+"already"+"exists",cart.getCartId()));
}
listOfCarts.put(cart.getCartId(),cart);
return cart;
}
#Override
public Cart read(String cartId) {
return listOfCarts.get(cartId);
}
#Override
public void update(String cartId, Cart cart) {
if(!listOfCarts.keySet().contains(cartId))
{
throw new IllegalArgumentException(String.format("Cannot update cart. The cart with the given id(%)" +
"does not"+"exists.",cart.getCartId()));
}
listOfCarts.put(cartId,cart);
}
#Override
public void delete(String cartId) {
if(!listOfCarts.keySet().contains(cartId))
{
throw new IllegalArgumentException(String.format("Cannot delete cart. A cart with the given id(%)"
+"does not exists",cartId));
}
listOfCarts.remove(cartId);
}
}
viewProduct.jsp
<%#taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%#taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#include file="/WEB-INF/views/template/header.jsp" %>
<div class="container-wrapper">
<div class="container">
<div class="page-header">
<h1>Product Detail</h1>
<p class="lead">Here is the detailed information of the products</p>
</div>
<div class="container-fluid" ng-app="cartApp">
<div class="row">
<div class="col-md-5">
<img src="<c:url value="/resources/images/${product.productId}.png"/>" alt="image" style="width:100%"/>
<!-- ;height:300px-->
</div>
<div class="col-md-5">
<h3>${product.productName}</h3>
<p>${product.productDescription}</p>
<p>
<strong>Manufacturer</strong>:${product.productManufacturer}
</p>
<p>
<strong>Category</strong>:${product.productCategory}
</p>
<p>
<strong>Condition</strong>:${product.productCondition}
</p>
<p>
<h4>${product.productPrice} USD</h4>
</p>
<br/>
<c:set var="role" scope="page" value="${param.role}"/>
<c:set var="url" scope="page" value="/productList"/>
<c:if test="${role='admin'}">
<c:set var="url" scope="page" value="/admin/productInventory"/>
</c:if>
<p ng-controller="cartCtrl">
Back
<a href="#" class="btn btn-warning btn-large"
ng-click="addToCart('${product.productId}')"><span class="glyphicon glyphicon-shopping-cart"></span>Order Now</a>
<span class="glyphicon glyphicon-hand-right"></span>View Cart
</p>
</div>
</div>
</div>
</div>
</div>
<script scr="<c:url value="/resources/js/controller.js"/>"></script>
<%#include file="/WEB-INF/views/template/footer.jsp" %>
cart.jsp
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#include file="/WEB-INF/views/template/header.jsp" %>
<div class="container-wrapper">
<div class="container">
<section>
<div class="jumbotron">
<div class="container">
<h1>Cart</h1>
<p>All the selected products in your shopping cart</p>
</div>
</div>
</section>
<section class="container" ng-app="cartApp">
<div ng-controller="cartCtrl" ng-init="initCartId('${cartId}')">
<div>
<a class="bnt btn-danger pull-left" ng-click="clearCart()"><span class="glyphicon glyphicon-remove-sign"></span>Clear Cart</a>
</div>
<table class="table table-hover">
<tr>
<th>Product</th>
<th>Unit Price</th>
<th>Quantity</th>
<th>Price</th>
<th>Action</th>
</tr>
<tr ng-repeat="item in cart.cartItems">
<td>{{item.product.ProductName}}</td>
<td>{{item.product.ProductPrice}}</td>
<td>{{item.quantity}}</td>
<td>{{item.totalPrice}}</td>
<td><a href="#" class="label label-danger" ng-click="removeFromCart(item.product.productId)">
<span class="glyphicon glyphicon-remove"></span>remove</a></td>
</tr>
<tr>
<th></th>
<th></th>
<th>Grand Total</th>
<th>grandTotal</th>
</tr>
</table>
Continue Shopping
</div>
</section>
</div>
</div>
<script src="<c:url value="/resources/js/controller.js"/>"></script>
<%#include file="/WEB-INF/views/template/footer.jsp" %>
controller.js
var cartApp=angular.module("cartApp",[]);
cartApp.controller("cartCtrl",function($scope,$http){
$scope.refreshCart=function(cartId){
$http.get('/eMusicStore_war_exploded/rest/cart/'+$scope.cartId).success(function (data){
$scope.cart=data;
});
};
$scope.clearCart=function(){
$http.delete('/eMusicStore_war_exploded/rest/cart/'+$scope.cartId).success($scope.refreshCart($scope.cartId));
};
$scope.initCartId=function(cartId){
$scope.cartId=cartId;
$scope.refreshCart(cartId);
};
$scope.addToCart=function(productId)
{
$http.put('/eMusicStore_war_exploded/rest/cart/add/'+productId).success(function (data){
$scope.refreshCart($http.get('/eMusicStore_war_exploded/rest/cart/cartId'));
alert('Product successfully added to cart!')
});
};
$scope.removeFromCart=function(productId){
$http.put('/eMusicStore_war_exploded/rest/cart/remove/'+productId).success(function(data){
$scope.refreshCart($http.get('eMusicStore_war_exploded/rest/cart/cartId'));
});
};
});
When I try to execute it, I'm getting the product page but after presssing the order now button the url changes to http://localhost:8004/eMusicStore_war_exploded/productList/viewProduct/1#
where 1 is productId but after that there isn't any popup stating that order has been placed and when I view the cart I'm getting only the varibale name which I used in jsp script and not the value. When I tried to debug I found that the ng-click from viewProduct.jsp is not performing any action. Please help me fix this...

Successful login with Custom login page in spring boot starter security not getting to next page

I have been studying spring boot. When using spring-boot-starter-security for a todo application,I tried to login with custom user id and password and custom login page.When I tried login , it is not taking me to next page. Note : user name is required parameter for next page.
I tried using below but after login it again takes me to login page as error
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/login").permitAll()
.antMatchers("/", "/*Todo*/**").access("hasRole('USER')").and()
.formLogin().loginPage("/login").permitAll();
}
This is my securityConfig code
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/login").permitAll()
.antMatchers("/listTodo").hasAnyRole("USER","ADMIN")
.anyRequest().authenticated()
.and().formLogin().loginPage("/login").permitAll().and()
.logout().permitAll();
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("Sudhakar").password("qwe123").roles("USER","ADMIN");
}
}
I would need to login with user name and get the todo details of the user who logged in. But I am not able to get to next page, after trying many times I am getting below error
java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"
Below is my controller
package com.example.SpringLogin.Controller;
import org.springframework.beans.factory.annotation.Autowired;
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.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import com.example.SpringLogin.service.loginService;
#Controller
#SessionAttributes("name")
public class LoginController {
#Autowired
loginService service;
#RequestMapping(value="/login",method = RequestMethod.POST)
public String loginMessage(ModelMap model,#RequestParam String name,#RequestParam String password) {
boolean isValidUser=service.validateUser(name, password);
if(!isValidUser) {
model.put("message", "Invalid Credentials");
return"Room";
}
model.put("name", name);
model.put("password",password);
return "redirect:/todoList";
}
#RequestMapping(value="/login",method = RequestMethod.GET)
public String roomLogin(ModelMap model, String error) {
//model.put("name", name);
if(error!=null) {
model.addAttribute("errorMsg","UserName or Password is invalid");
}
return "Room";
}
/*#RequestMapping(value="/login",method = RequestMethod.GET)
public String showLogin(ModelMap model) {
//model.put("name", name);
return "Welcome";
}*/
#RequestMapping(value = "/welcome")
public String showWelcome(ModelMap model) {
return "login";
}
}
My login page
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<c:set var="contextPath" value=""/>
<!DOCTYPE html>
<html>
<head>
<link href="webjars/bootstrap/3.3.6/css/bootstrap.min.css"
rel="stylesheet">
<title>Todo Application</title>
</head>
<body>
<div class="container">
<font color="red">${message}</font>
<form:form method="post" action="/login">
<fieldset class="form-group">
Name : <input type="text" name="username" class="form-control" placeholder="Username"
autofocus="true"/>
Password: <input type="password" name="password"
class="form-control" placeholder="Password" />
</fieldset>
<button type="submit" class="btn btn-success">Submit</button>
</form:form>
</div>
<script src="webjars/jquery/1.9.1/jquery.min.js"></script>
<script src="webjars/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
After successful login it should go to below page
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<c:set var="contextPath" value=""/>
<!DOCTYPE html>
<html>
<head>
<link href="webjars/bootstrap/3.3.6/css/bootstrap.min.css"
rel="stylesheet">
<title>Todo Application</title>
</head>
<body>
<div class="container">
<table class="table table-striped">
<H1>Name : ${pageContext.request.userPrincipal.name}</H1>
<thead>
<tr>
<th>Id</th>
<th>Course</th>
<th>End Date</th>
<th>Is it Done</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<c:forEach items="${todo}" var="item">
<tr>
<td>${item.id}</td>
<td>${item.course}</td>
<td><fmt:formatDate value="${item.date}" pattern="MM/dd/yyyy" /></td>
<td>${item.isdone?'Yes':'No'}</td>
<td><a type="button" class="btn btn-success"
href="/update-Todo?id=${item.id}">Update</a></td>
<td><a type="button" class="btn btn-warning"
href="/delete-Todo?id=${item.id}">Delete</a></td>
</tr>
</c:forEach>
</tbody>
</table>
<div>
<a type="button" href="/add-Todo" class="btn btn-success">Add a
Todo</a>
</div>
</div>
<script src="webjars/jquery/1.9.1/jquery.min.js"></script>
<script src="webjars/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
Service class
package com.example.SpringLogin.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.springframework.stereotype.Service;
import com.example.SpringLogin.model.todoList;
#Service
public class TodoService {
public static List<todoList> todos=new ArrayList<todoList>();
public static int todoCount=5;
static {
todos.add(new todoList(1, "Sudhakar", "Study history", new Date(), false));
todos.add(new todoList(2,"Sudhakar","Study geography",new Date(),false));
todos.add(new todoList(3,"Sudhakar","Study GK",new Date(),false));
todos.add(new todoList(4,"Mani","Study Java",new Date(),false));
todos.add(new todoList(5,"Mani","Study script",new Date(),false));
}
public List<todoList> retrievetodos(String name){
List<todoList> retrieved=new ArrayList<todoList>();
for (todoList todo : todos) {
if(todo.getName().equalsIgnoreCase(name)) {
retrieved.add(todo);
}
}
return retrieved;
}
public void addTodo(String name,String Course,Date date,boolean isDone) {
todos.add(new todoList(++todoCount,name,Course,date,isDone));
}
public todoList retrieveTodo(int id){
for (todoList todo : todos) {
if(todo.getId()==id) {
return todo;
}
}
return null;
}
public List<todoList> UpdateTodo(todoList todo){
/*for (todoList td : todos) {
if(td.getId()==todo.getId()) {
td.setCourse(todo.getCourse());
td.setDate(todo.getDate());
}
}*/
todos.remove(todo);
todos.add(todo);
return todos;
}
//it will delete the todo
public void deleteTodo(int id) {
Iterator<todoList> it = todos.iterator();
while(it.hasNext()){
todoList td=it.next();
if(td.getId()==id) {
it.remove();
}
}
}
}
my expectation is to login application using user name and get the todolist of the user
Try adding a loginProcessUrl and a defaultSuccessUrl. Something like this:
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/do_login")
.defaultSuccessUrl("/index")
index in this example is the page you want to be taken to upon successful login.
Use this one
.formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/perform_login")
.defaultSuccessUrl("/homepage.html", true)

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>

error Neither BindingResult nor plain target object for bean name 'XXX' available as request attribute

I am getting this error, I am sure I have matched with the same name.
please help me
"Neither BindingResult nor plain target object for bean name 'userForm' available as request attribute"
this is index.jsp
<%# include file="/WEB-INF/jsp/taglibs.jsp" %>
<div class="row">
<div class="panel panel-default">
<div class="panel-body">
<form:form action="dummy" method="post" commandName="userForm">
<table border="0">
<tr>
<td colspan="2" align="center"><h2>Spring MVC Form Demo - Registration</h2></td>
</tr>
<tr>
<td>User Name:</td>
<td>
<form:input path="username" />
</td>
</tr>
<tr>
<td>Profession:</td>
<td><form:select path="profession" items="${professionList}" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Register" /></td>
</tr>
</table>
</form:form>
</form>
</div>
</div>
</div>
This is the file DummyControllor.java
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* #author ***
*/
#Controller
#RequestMapping("/dummy.htm")
public class DummyController extends AbstractGCEController {
protected static Logger logger = Logger.getLogger("controller");
#RequestMapping(method = RequestMethod.GET)
public String viewRegistration(Model model) {
User userForm = new User();
model.addAttribute("userForm", userForm);
List<String> professionList = new ArrayList<>();
professionList.add("Developer");
professionList.add("Designer");
professionList.add("IT Manager");
model.addAttribute("professionList", professionList);
return "index";
}
#RequestMapping(method = RequestMethod.POST)
public String processRegistration(#ModelAttribute("userForm") User user, Map<String, Object> model) {
// implement your own registration logic here...
// for testing purpose:
System.out.println("username: " + user.getUsername());
System.out.println("profession: " + user.getProfession());
return "RegistrationSuccess";
}
}
The User.java
public class User {
private String username;
private String profession;
public User() {
// TODO Auto-generated constructor stub
}
public User(String username, String profession) {
this.username = username;
this.profession = profession;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getProfession() {
return profession;
}
public void setProfession(String profession) {
this.profession = profession;
}
}
the registrationSuccess.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>Insert title here</title>
</head>
<body>
</body><%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib prefix="form" 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=UTF-8">
<title>Registration Success</title>
</head>
<body>
<div align="center">
<table border="0">
<tr>
<td colspan="2" align="center"><h2>Registration Succeeded!</h2></td>
</tr>
<tr>
<td colspan="2" align="center">
<h3>Thank you for registering! Here's the review of your details:</h3>
</td>
</tr>
<tr>
<td>User Name:</td>
<td>${userForm.username}</td>
</tr>
<tr>
<td>Profession:</td>
<td>${userForm.profession}</td>
</tr>
</table>
</div>
</body>
</html>
</html>

Spring unable to get form values

Im using the below servlet to get the form values, when the form is posted im able to get the username and password but unable to access it in the mainpage.jsp which displays the username/password.
Servlet
package com.school.controller;
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.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.school.beans.Login;
#Controller
public class Logincontroller {
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView login() {
return new ModelAndView("login", "loginform", new Login());
}
#RequestMapping(value = "/validatelogin", method = RequestMethod.POST)
public String validatelogin(#ModelAttribute("SchoolManagement")Login login,
ModelMap model) {
model.addAttribute("username", login.getUsername());
model.addAttribute("password", login.getPassword());
System.out.println("useranme = " + login.getUsername());
System.out.println("password = " + login.getPassword());
return "mainpage";
}
}
login.jsp
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<!--
<script src="javascript/login.js"></script>
<link rel="stylesheet" type="text/css" href="css/login.css"/>
http://www.mkyong.com/spring-mvc/spring-mvc-how-to-include-js-or-css-files-in-a-jsp-page/
-->
<!--<script src="<c:url value="/resources/js/jquery.1.10.2.min.js" />"></script>-->
<link href="<c:url value="/resources/css/login.css" />" rel="stylesheet">
<script src="<c:url value="/resources/js/login.js" />"></script>
<script
src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div id="top"></div>
<div id="middle">
<form:form method="POST" id="loginform" commandName="loginform"
action="/SchoolManagement/validatelogin">
<form:label path="username"> Username:</form:label>
<form:input path="username" /> <br>
<form:label path="password"> Password:</form:label>
<form:input path="password" />
<input type="submit" value="submit">
</form:form>
</div>
<div id="bottom"></div>
</body>
</html>
mainpage.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="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>MainPage</title>
</head>
<body>
<h2>Submitted Student Information</h2>
<table>
<tr>
<td>Name</td>
<td>${username}</td>
</tr>
<tr>
<td>Password</td>
<td>${password}</td>
</tr>
</table>
</body>
</html>
Try getting the values directly out of the request.
<%
String username = (String) request.getAttribute("username");
String password = (String) request.getAttribute("password");
%>
<table>
<tr>
<td>Name</td>
<td><%= username %></td>
</tr>
<tr>
<td>Password</td>
<td><%= password %></td>
</tr>
</table>
That should definitely work... if not, something's wrong with the setup.
your command name
commandName="loginform"
is different than model attribute
#ModelAttribute("SchoolManagement")
try to use same names

Categories

Resources