Bring jsp form page after previous submit (java spring) - java

New to spring (and HTML/forms etc for that matter) and been stuck on this problem for long time.
So I want to have a front page where you enter a username. Then click submit, and takes you to a dashboard (ultimately, there will be a page with a list of connected users, a load of submit buttons to send predefined messages out - using qpid jms).
The front page is fine, but I click submit and I get an error (java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'dashboardModel' available as request attribute)
This only happens if I have a form:form in dashboard.jsp. I literally have no idea how to fix this and have tried everything I can find. My code is simple, and is just modified from a tutorial, so here it is:
login.jsp
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Login Page:</h2>
<form:form modelAttribute="loginModel" method="POST"
action="/HelloWeb/dashboard">
<table>
<tr>
<td><form:label path="username">Name</form:label></td>
<td><form:input path="username" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
Login.java
package com.tutorialspoint;
public class Login {
private String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
LoginController.java
package com.tutorialspoint;
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;
import org.springframework.ui.ModelMap;
#Controller
public class LoginController {
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login() {
return new ModelAndView("login", "loginModel", new Login());
}
#RequestMapping(value = "/loggedIn", method = RequestMethod.POST) //never actually used
public String loggedIn(#ModelAttribute("Login") Login login, ModelMap model) {
model.addAttribute("username", login.getUsername());
return "dashboard";
}
}
dashboard.jsp
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>DASHBOARD</title>
</head>
<body>
<table>
<tr>
<td>Dashboard</td>
<td>DASHBOARD</td>
</tr>
<tr>
<td>Username</td>
<td>${username}</td>
</tr>
<tr>
<td>variable</td>
<td>${variable}</td>
</tr>
</table>
<form:form modelAttribute="dashboardModel" method="POST"
action="/HelloWeb/dashboard">
<table>
<tr>
<td><form:label path="variable">Name</form:label></td>
<td><form:input path="variable" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</body>
</html>
Dashboard.java
package com.tutorialspoint;
public class Dashboard {
private String variable;
public String getVariable() {
return variable;
}
public void setVariable(String variable) {
this.variable = variable;
}
}
DashboardController.java
package com.tutorialspoint;
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;
import org.springframework.ui.ModelMap;
#Controller
public class DashboardController {
#RequestMapping(value = "/dashboard", method = RequestMethod.GET)
public ModelAndView dashboard() {
return new ModelAndView("dashboard", "dashboardModel", new Dashboard());
}
#RequestMapping(value = "/dashboard", method = RequestMethod.POST)
public String addVariable(#ModelAttribute("SpringWeb") Dashboard dashboard,
ModelMap model) {
model.addAttribute("variable", dashboard.getVariable());
return "dashboard";
}
}
Thanks for your time.

I think the problem is here:
<form:form modelAttribute="loginModel" method="POST" action="/HelloWeb/dashboard">
^^^^^^^^^^
and here:
#RequestMapping(value = "/loggedIn", method = RequestMethod.POST) //never actually used
public String loggedIn(#ModelAttribute("Login") Login login, ModelMap model) {
^^^^^
The modelAttribute value on form:form element and the #ModelAttribute argument should be the same.
I mean:
#RequestMapping(value = "/loggedIn", method = RequestMethod.POST) //never actually used
public String loggedIn(#ModelAttribute("loginModel") Login login, ModelMap model) {
^^^^^^^^^^
Edit:
Also, the form part should be like this:
<form:form modelAttribute="dashboardModel" method="POST" action="/loggedIn.htm">
<table>
<tr>
<td>Name</td>
<td><form:input path="username" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>

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...

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 />

HTTP Status 405 - Request method 'POST' not supported Spring Security Java Config

Hello I am facing the 'HTTP Status 405 - Request method 'POST' not supported'
exception when trying to do login using spring security.
Following is my code :
pgLogin.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
<script type="text/javascript">
function focusOnLoad() {
document.getElementById("username").focus();
}
</script>
</head>
<body onload="focusOnLoad()">
<div align="center">
<c:if test="${not empty error}">
<div>
<p style="color: red;">${error}</p>
</div>
</c:if>
<c:if test="${not empty message}">
<div>
<p style="color: red;">${message}</p>
</div>
</c:if>
<c:url var="loginUrl" value="/login" />
<form action="${loginUrl}" method="post">
<div>
<table>
<tr>
<td><label for="username">Email</label></td>
<td><input type="text" id="username" name="email" placeholder="Enter Email" required></td>
</tr>
<tr>
<td><label for="password">Password</label></td>
<td><input type="password" id="password" name="password" placeholder="Enter Password" required></td>
</tr>
</table>
</div>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
<div>
<input type="submit" value="Log In">
</div>
</form>
</div>
</body>
</html>
DesertLampSecurityConfiguration.java
package co.in.desertlamp.configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
#EnableWebSecurity
public class DesertLampSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(AuthenticationManagerBuilder authenticationMgr) throws Exception {
authenticationMgr.inMemoryAuthentication()
.withUser("subodh.ranadive#desertlamp.com")
.password("Dlpl123#")
.authorities("ROLE_SUPER_USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/home").access("hasRole('ROLE_SUPER_USER')")
.and()
.formLogin().loginPage("/loginPage")
.defaultSuccessUrl("/homePage")
.failureUrl("/loginPage?error")
.usernameParameter("email").passwordParameter("password")
.and()
.logout().logoutSuccessUrl("/loginPage?logout");
}
}
DefaultController.java
package co.in.desertlamp.controller;
import org.springframework.stereotype.Controller;
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;
#Controller
public class DefaultController {
#RequestMapping(value = { "/"}, method = RequestMethod.GET)
public ModelAndView welcomePage() {
ModelAndView model = new ModelAndView();
model.setViewName("common/pgDefault");
return model;
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView loginPage(#RequestParam(value = "error",required = false) String error) {
ModelAndView model = new ModelAndView();
if (error != null) {
model.addObject("error", "Invalid Email OR Password");
}
model.setViewName("common/pgLogin");
return model;
}
#RequestMapping(value = { "/home"}, method = RequestMethod.GET)
public ModelAndView homePage() {
ModelAndView model = new ModelAndView();
model.setViewName("common/pgWelcome");
return model;
}
}
Change your config as following to match your method handlers:
...
.formLogin().loginPage("/login")
.defaultSuccessUrl("/home")
.failureUrl("/login?error")

Spring MVC Add and Modification doesn't work properly as I want

Currently in my project, addEmployee.jsp show properly when "Add Employee" or "Edit" is clicked, but when I try to hit submit button in "Add Employee" page, page return "Http status 500 Request processing failed; nested exception is java.lang.NullPointerException", or when I try to hit submit button in "Add Employee" page for update employee info, I will get "HTTP Status 405 - Request method 'POST' not supported"
The way I want is when I add a new employee or update the existing employee info, I will still using addEmployee.jsp page. If it is add a new one, all the field will be empty, otherwise, all the field will contain the existing information for update.
Here is the code for employee.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Employee List</title>
</head>
<body>
<div align="center">
<h1 style="background-color: lightgreen; color: darkgreen">Employee
Page</h1>
<table align="center" width="80%" cellspacing="0" cellpadding="5">
<tr>
<td align="center">
<table cellspacing="0" cellpadding="6" border="0" width="100%">
<tr bgcolor="lightblue">
<td align="left"><a
href="${pageContext.request.contextPath}/employee/addEmployee"
style="background-color: lightblue;"> Add Employee </a></td>
</table>
</td>
</tr>
<tr>
<td>
<table cellspacing="0" cellpadding="6" border="1" width="100%">
<tr>
<td colspan="8"
style="background-color: lightblue; color: darkgreen; font-size: 16pt"
align="center">Employee List</td>
</tr>
<tr bgcolor="grey" style="color: white">
<th>No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Job Title</th>
<th>Department</th>
<th>Salary</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<c:forEach var="employee" items="${employeesList}"
varStatus="status">
<tr bgcolor="lightyellow">
<td><b>${status.index + 1}</b></td>
<td>${employee.firstName}</td>
<td>${employee.lastName}</td>
<td>${employee.jobTitle}</td>
<td>${employee.department}</td>
<td>${employee.salary}</td>
<td>Edit</td>
<td>Delete</td>
</tr>
</c:forEach>
</table>
</td>
</tr>
</table>
</div>
</body>
</html>
And Here is the code for addEmployee.jsp page
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%#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>Add Employee</title>
</head>
<body>
<div align="center">
<h1 style="background-color: lightgreen; color: darkgreen">Add
New Employee Page</h1>
<table width="80%" align="center">
<tr bgcolor="lightblue">
<td align="left"><a href="listEmployees"
style="background-color: lightblue;">List Employee</a></td>
</table>
</div>
<br />
<div align="center">
<table cellspacing="0" cellpadding="6" border="1" width="80%">
<tr>
<td colspan="8"
style="background-color: lightblue; color: darkgreen; font-size: 16pt"
align="center">Employee Information</td>
</tr>
<tr>
<td><form:form method="POST" action="updateEmployee">
<table width="100%">
<tr>
<td><form:label path="firstName">First Name</form:label></td>
<td align="left" width="70%"><form:input path="firstName" /></td>
</tr>
<tr>
<td><form:label path="lastName">Last Name</form:label></td>
<td align="left" width="70%"><form:input path="lastName" /></td>
</tr>
<tr>
<td><form:label path="jobTitle">Job Title</form:label></td>
<td align="left" width="70%"><form:input path="jobTitle" /></td>
</tr>
<tr>
<td><form:label path="department">Department</form:label></td>
<td align="left" width="70%"><form:input path="department" /></td>
</tr>
<tr>
<td><form:label path="salary">Salary</form:label></td>
<td align="left" width="70%"><form:input path="salary" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form></td>
</tr>
</table>
</div>
</body>
</html>
Here is the code for EmployeeController.java
package com.vincent.springmvc.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.vincent.springmvc.model.Employee;
import com.vincent.springmvc.service.EmployeeService;
#Controller
#RequestMapping("/employee")
public class EmployeeController {
//Logger file
private static Logger logger = LoggerFactory.getLogger(EmployeeController.class);
#Autowired
private EmployeeService employeeService;
#RequestMapping(method = RequestMethod.GET)
public String welcomeEmployee(ModelMap model){
model.addAttribute("name", "Hello World!");
model.addAttribute("greetings", "Welcome to Spring MVC");
return "hello";
}
#RequestMapping(value = "/listEmployees", method = RequestMethod.GET)
public String listEmployees(ModelMap model){
model.addAttribute("employeesList", this.employeeService.listEmployee());
return "employee";
}
#RequestMapping(value = "/addEmployee", method = RequestMethod.GET)
public ModelAndView addEmployee(ModelMap model){
return new ModelAndView("addEmployee", "command", new Employee());
}
#RequestMapping(value = "/updateEmployee", method = RequestMethod.POST)
public String updateEmployee(#ModelAttribute("employee") Employee employee, ModelMap model){
if(employee.getId() == 0)
this.employeeService.insertEmployee(employee);
else
this.employeeService.updateEmployee(employee);
model.addAttribute("employeesList", this.employeeService.listEmployee());
return "employee";
}
#RequestMapping(value = "/delete/{empId}", method = RequestMethod.GET)
public String deleteEmployee(#PathVariable("empId") Integer empId, ModelMap model){
this.employeeService.deleteEmployee(empId);
model.addAttribute("employeesList", this.employeeService.listEmployee());
return "employee";
}
#RequestMapping(value = "/edit/{empId}", method=RequestMethod.GET)
public ModelAndView editEmployee(#PathVariable("empId") int id, ModelMap model){
return new ModelAndView("addEmployee", "command", this.employeeService.getEmployeeById(id));
}
}
Here is the project structure
Project Structure
and the rest of the code you can find in https://github.com/zhengye1/SpringMVC
Thank you for the help
Kind of resolve for now.... but seems like not a very good idea, it is time to looking for good advice..
The way I fix is, in my controller class, I change the annotation in updateEmployee with following annotation #RequestMapping(value = {"/updateEmployee", "/edit/updateEmployee"}, method = RequestMethod.POST). This because when I tracing the log, I realize somehow the server try to mapping the page called edit/updateEmployee, originally is not exists, that is why it raising the 504 error for update.
For adding issue is causing by the form, since the form return the null id, therefore when I try to compare the null object with 0, it raise the null pointer exception. The way I fix is, change that line to if (employee.getId() == null), and also in addEmployee.jsp page, I add the this line to my form, <form:hidden path="id" />. That is resolve the issue.

completing read CRUD sql in jsp servlet

I asked this questions last night, and was kind of foolish not to ask how to complete the coding on it. I now have a dropdown box in a JSP populated with some data from an SQL database. I am trying to get the selected data to direct to the final viewing page, but again am running into some difficulty with this.
When I run the program, it either populates the page with all the data from the list database, or will give me an unfriendly error.
My current coding is as such:
the Bean:
package com.login.read;
public class ReadBean {
protected int id;
protected String title;
protected String author;
protected String text;
public int getId(){
return id;
}
public void setId(int newID){
id = newID;
}
public String getTitle(){
return title;
}
public void setTitle(String newTitle){
title = newTitle;
}
public String getAuthor(){
return author;
}
public void setAuthor(String newAuthor){
author = newAuthor;
}
public String getText(){
return text;
}
public void setText(String newText){
text = newText;
}
}
The Controller:
package com.login.read;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet (urlPatterns={"/com/defaultValidate/ReadController"})
public class ReadController extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String address;
List<ReadBean> myList = new ArrayList<ReadBean>();
if(request.getParameter("ReadConfirm") != null){
try {
Connection connect = ConnectionManager.getConnection();
String SQL = "SELECT * FROM prayers ORDER BY prayerTitle DESC";
PreparedStatement ps = connect.prepareStatement(SQL);
ResultSet rs = ps.executeQuery();
while(rs.next()){
ReadBean reader = new ReadBean();
reader.setTitle(rs.getString("prayerTitle"));
reader.setAuthor(rs.getString("author"));
reader.setText(rs.getString("text"));
myList.add(reader);
}
request.getSession().setAttribute("ref", myList);
rs.close();
ps.close();
connect.close();
} catch (Exception e) {
}
address = "ReadConfirm.jsp";
} else if(request.getParameter("ReadView") != null){
address = "ReadView.jsp";
} else{
address = null;
}
RequestDispatcher dispatcher = request.getRequestDispatcher(address);
dispatcher.forward(request, response);
}
}
And my jsp pages that link the drop-down box to the selected material:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
%#include file="MenuHeader.jsp"%>
</div>
<div id="mainBorder"> </div>
<div id="mainBody">
<table id="mainTable">
<tr>
<td id="sidebar">
<h2>Options</h2>
<ul>
</ul>
</td>
<td id="mainContent">
<h2 id="contentHeader">Select a prayer</h2>
<form action="ReadController">
<table border="1" width="1" cellspacing="5" cellpadding="5">
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><select name="prayer_id">
<c:forEach var="view" items="${ref}">
<h2>${view.title}</h2>
<h3>${view.author}</h3>
<p>${view.text}</p>
</c:forEach>
</select>
</td>
</tr>
<tr>
<td><input type="submit" name="ReadView" value="View"> </td>
</tr>
</tbody>
</table>
</form>
<td id="imageBar">
</td>
</table>
<%# include file="../menuHeaderAndFooter/MenuFooter.jsp" %>
and the final viewing page:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
%#include file="MenuHeader.jsp"%>
</div>
<div id="mainBorder"> </div>
<div id="mainBody">
<table id="mainTable">
<tr>
<td id="sidebar">
<h2>Options</h2>
<ul>
</ul>
</td>
<td id="mainContent">
<c:forEach var="view" items="${res}">
<h2>${view.title}</h2>
<h3>${view.author}</h3>
<p>${view.text}</p>
</c:forEach>
<form action="../Read.jsp">
<p>Click on the return button to return to the main menu</p>
<input type="submit" name="return" value="Return">
</form>
<td id="imageBar">
</td>
</table>
<%# include file="../menuHeaderAndFooter/MenuFooter.jsp" %>
As always, any and all assistance in this regard is incredibly helpful. I am a relative newbie to the world of jsp and servlets.
If one needs any reference as to the continuation of this sequence, kindly view the previous question I posted regarding dynamically displaying data in a jsp combo-box.
Thank you for your time and help.
By reading above code, I can just ask you that where you have stored your session attribute in variable "var", which is being used in c:foreach loop ?

Categories

Resources