I am creating my first form with Java developing with Sprint Tool Suite on my local machine. I created an index.html page with a simple form with 3 input fields. I want to have the form submit to a results.html page which just displays the values entered into the form. The issue I am having is that when I launch the application, fill in some data, and click the submit button, I get a 404 error. Also, what I noticed is that when I click on the submit button, the url box of the browser changes to localhost:8080/person. I expected to see localhost:8080/results. I thank you in advance for any assistance.
My main application class code is this:
package com.baconbuddy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class BaconBuddyApplication {
public static void main(String[] args) {
SpringApplication.run(BaconBuddyApplication.class, args);
}
}
My index.html has the following code:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Home Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<h1>Hello world!</h1>
<form action="#" th:action="#{/person}" th:object="${person}" method="post" >
<input th:field="*{firstName}" placeholder="First Name" />
<input th:field="*{lastName}" placeholder="Last Name" />
<input th:field="*{age}" placeholder="Age" />
<button >Submit</button>
</form>
</body>
</html>
My results.html has the following code:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Insert title here</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<div>
<p>First Name:
<span th:text="${person.firstName}"></span>
</p>
<br />
<p>Last Name:
<span th:text="${person.lastName}"></span>
</p>
<br />
<p>Age:
<span th:text="${person.age}"></span>
</p>
</div>
</body>
</html>
My Person.java file looks like this:
package com.baconbuddy.models;
public class Person {
private String firstName;
private String lastName;
private int age;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
and my HomeController.java looks like this:
package com.baconbuddy.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.baconbuddy.models.Person;
#Controller
#RequestMapping({ "/", "/home" })
public class HomeController {
#GetMapping()
public String index(Model model) {
model.addAttribute("person", new Person());
// The string index will be looked for in src/main/resources/templates
return "index";
}
#PostMapping()
public String personSubmit(#ModelAttribute Person person) {
return "results";
}
}
You have #{/person} as your th:action in your <form> HTML, but your controller isn't mapping a method for it. The POST you have mapped right now is mapping to / and /home (inherited from your class-level #RequestMapping). Change your #PostMapping or modify your <form>, e.g.:
#PostMapping("person")
public String personSubmit(#ModelAttribute Person person) {
return "results";
}
Or update your form:
<form action="#" th:action="#{/}" th:object="${person}" method="post" >
Related
I can't pass a object Project without the object is null.
How do I pass the object to the spring controller from the html?
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<body>
<form action="/addproject" method="POST">
<input type="hidden" name="project" th:value="${project}"/>
<input type="submit" value="Save Project" class="submit">
</form>
</body>
</html>
#Controller
public class ProjectController {
#GetMapping("/")
public String indexPage(Model model) {
model.addAttribute("project", new Project("Test", "Test"));
return "index";
}
#PostMapping("/addproject")
public String add(WebRequest webRequest) {
Project p = (Project) webRequest.getAttribute("project", WebRequest.SCOPE_REQUEST);
return "index";
}
}
Please check this article. In short you need to pass required object to ModelAndView, not Model:
#GetMapping("/")
public ModelAndView indexPage(Model model) {
ModelAndView mav = new ModelAndView("index");
mav.addObject("project", new Project("Test", "Test"));
return mav;
}
and access it by name from template:
<b th:text="${project.attribute}">Text ...</b>
I would suggest you to proceed with the document here first.
You don't have a requirement or problem with ModelAndView.
The first time you call the /project page, the project class information will be loaded by #GetMapping, if you want, it will be captured by #PostMapping when you change and submit it.
project.html file:
<!DOCTYPE HTML>
<html xmlns:th="https://www.thymeleaf.org">
<head>
<title>Project Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Project Form</h1>
<form method="post" th:action="#{/project}" th:object="${project}">
<p>Name: <input type="text" th:field="*{name}" /></p>
<p>Description: <input type="text" th:field="*{description}" /></p>
<p><input type="submit" value="Submit" /> </p>
</form>
</body>
</html>
Project.java file:
public class Project {
private String name;
private String description;
public Project(String name, String description) {
this.name = name;
this.description = description;
}
// getter/setter ...
}
ProjectController.java file:
#Controller
public class ProjectController {
#GetMapping("/project")
public String greetingForm(Model model) {
model.addAttribute("project", new Project("PN1", "PD1"));
return "project";
}
#PostMapping("/project")
public String greetingSubmit(#ModelAttribute Project project, Model model) {
model.addAttribute("project", project);
return "project";
}
}
a group of friends and I create a Hotel website application in Spring. I am responsible for the room catalog part. I've created some classes in java, Room.java, RoomCategory.java, CatalogController.java, RoomCatalog.java, and 2 HTML files welcome.html and roomCatalog.html.
My problem is that when I want to save the input value-form user e.g th:field="*{name}" in roomCatalog.htmlthe website crashes.
<form method="post" role="form" th:action="#{/addNewCategory}" th:object="${roomCategory}" >
<div class="field">
<label for="name">Categories</label>
<input id="name" name="name" type="text" th:field="*{name}" required="required" />
</div>
</form>
The second problem is in RoomCatalog.java with the method findByCategory(), it returns null now, which is wrong, but when I delate the body of the function and default at the beginning, my application crashes while booting.
default Iterable<Room> findByCategory(RoomCategory roomCategory, Sort sort){
return null;
}
Could you help me find and eliminate the problem?
Room.java
package hotelwebsite.catalog;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import org.salespointframework.catalog.Product;
#Entity
public class Room extends Product {
private String name;
private int roomNumber, floor;
private String image;
private RoomCategory roomCategory;
private Room(){}
public Room(String name, int roomNumber, int floor, RoomCategory roomCategory) {
this.name = name;
this.roomNumber = roomNumber;
this.floor = floor;
this.roomCategory = roomCategory;
}
public int getRoomNumber() {
return roomNumber;
}
public int getFloor() {
return floor;
}
public RoomCategory getRoomCategory() {
return roomCategory;
}
public void editImage(String image){
this.image = image;
}
}
RoomCategory.java
package hotelwebsite.catalog;
import javax.persistence.*;
import org.javamoney.moneta.Money;
import org.salespointframework.catalog.Product;
import java.io.Serializable;
#Entity
public class RoomCategory implements Serializable {
private #Id #GeneratedValue long id;
private final int sleepingPlaces, addSleepingPlaces;
private String name;
private Money price;
public RoomCategory(String name, int sleepingPlaces, int addSleepingPlaces, Money price) {
this.sleepingPlaces = sleepingPlaces;
this.addSleepingPlaces = addSleepingPlaces;
this.name = name;
this.price = price;
}
public String getName(){ return name; }
public String getPrice(){
return this.price.toString();
}
public int getSleepingPlaces() {
return sleepingPlaces;
}
public int getAddSleepingPlaces() { return addSleepingPlaces; }
public int getMaxSleepingPlaces(){
return (sleepingPlaces + addSleepingPlaces);
}
}
RoomCatalog.java
package hotelwebsite.catalog;
import hotelwebsite.catalog.Room;
import org.salespointframework.catalog.Catalog;
import org.springframework.data.domain.Sort;
public interface RoomCatalog extends Catalog<Room> {
static final Sort DEFAULT_SORT = Sort.by("productName").descending();
default Iterable<Room> findByCategory(RoomCategory roomCategory, Sort sort){
return null;
}
default Iterable<Room> findByRoomCategory(RoomCategory roomCategory) {
return findByCategory(roomCategory, DEFAULT_SORT);
}
}
CatalogController.java
package hotelwebsite.catalog;
import hotelwebsite.*;
import java.time.LocalDateTime;
import org.salespointframework.inventory.InventoryItem;
import org.salespointframework.inventory.UniqueInventory;
import org.salespointframework.inventory.UniqueInventoryItem;
import org.salespointframework.time.BusinessTime;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
#Controller
public class CatalogController {
private final RoomCatalog catalog;
private final UniqueInventory<UniqueInventoryItem> inventory;
private final BusinessTime businessTime;
public CatalogController(RoomCatalog roomCatalog,
UniqueInventory<UniqueInventoryItem> inventory,
BusinessTime businessTime) {
this.catalog = roomCatalog;
this.inventory = inventory;
this.businessTime = businessTime;
}
#GetMapping("/categories")
String roomCategoryCatalog(Model model) {
model.addAttribute("catalog", catalog);
return "roomCatalog";
}
#GetMapping("/rooms")
String roomCatalog(Model model) {
model.addAttribute("catalog", catalog);
return "roomCatalog";
}
#GetMapping("/room/{room}")
String detail(#PathVariable Room room, Model model) {
model.addAttribute("room", room);
return "detail";
}
#PostMapping("/addNewCategory")
public String addRoomCategory(RoomCategory roomCategory, Model model) {
model.addAttribute("roomCategory",roomCategory);
model.addAttribute("catalog", roomCategory);
//System.out.println(roomCategory + " added to catalog.");
return "roomCatalog";
}
#DeleteMapping("/deleteCategory")
public String deleteRoomCategory(RoomCategory roomCategory, Model model){
//model.addAttribute("catalog", roomCategory);
return(roomCategory + " deleted from catalog.");
}
#PostMapping("/addNewRoom")
public String addRoom(Room room, Model model){
model.addAttribute("catalog", room);
//return(room + " added to catalog.");
return "redirect:/categories";
}
#DeleteMapping("/deleteRoom")
public String deleteRoom(Room room, Model model){
//model.deleteAttribute("catalog", room);
return(room + " deleted from catalog.");
}
#PostMapping("/editImage")
public String editImage(Room room, Model model, String image){
return null;
}
}
welcome.html
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" th:href="#{/resources/css/style.css}" />
<title>welcome</title>
</head>
<body>
<h1>Welcome!</h1>
<div class="roomCatalog">
Room Catalog
</div>
</body>
</html>
roomCatalog.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" type="text/css" th:href="#{/resources/css/style.css}" />
<title>Room Catalog</title>
</head>
<body>
<div class="ui container">
<header>
<h1> Willkommen im Hotel</h1>
</header>
<form method="post" role="form" th:action="#{/addNewCategory}" th:object="${roomCategory}" >
<div class="field">
<label for="name">Categories</label>
<input id="name" name="name" type="text" required="required" /> <!-- th:field="*{name}" -->
</div>
<div class="field">
<label for="sleepingPlaces">Sleeping places</label>
<input id="sleepingPlaces" name="sleepingPlaces" type="number" required="required" /> <!--th:field="*{sleepingPlaces}"-->
</div>
<div class="field">
<label for="addSleepingPlaces"> Extra sleeping places</label>
<input id="addSleepingPlaces" name="addSleepingPlaces" type="number"/> <!--th:field="*{addSleepingPlaces}"-->
</div>
<div class="field">
<label for="price">Price</label>
<input id="price" name="getPrice()" type="number" required="required" /> <!-- th:field="*{price}" -->
</div>
<button type="submit" class="ui button">Add Category</button>
</form>
</div>
</body>
</html>
I am trying send the data through controller to html page but unable data transmission is getting failed. Control is redirecting to the desired page along with labels but form data is not reflecting in the view page.
***HomeController***
package com.example.demo.web;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.example.demo.domain.User;
#Controller
public class HomeController {
User user = new User();
#RequestMapping("/")
public String home(Model model) {
model.addAttribute("formData", user);
return "index";
}
#RequestMapping(value="/create", method=RequestMethod.POST)
public String processFormData(User user, RedirectAttributes attr) {
attr.addFlashAttribute("user",user);
return "redirect:display";
}
#RequestMapping(value="/display", method=RequestMethod.GET)
public String displayFormData(User user) {
return "result";
}
}
index.html
<!DOCTYPE html>
<html xmlns:th="http://thymeleaf.org">
<head>
<meta charset="UTF-8">
<title> Home Page </title>
</head>
<body>
<p> Enter Data Below </p>
<form action="/create" method="post" th:object="${formData}">
<p>Full Name:<input type="text" th:feild="${formData.fullName}"/></p>
<p>Age:<input type="text" th:feild="${formData.age}"/></p>
<p>Employed?<input type="checkbox" th:feild="${formData.employed}" th:value="true"/></p>
<p>Gender:</p>
<p>Male<input type="radio" th:feild="${formData.gender}" th:value="Male"/>
Female<input type="radio" th:feild="${formData.gender}" th:value="Female"/></p>
<p><input type="submit" value="Submit"/> <input type="reset" value="Reset"/></p>
</form>
</body>
</html>
result.html
<html xmlns:th="https://thymeleaf.org">
<table>
<tr>
<td><h4>User Name: </h4></td>
<td><h4 th:text="${user.fullName}"></h4></td>
</tr>
<tr>
<td><h4>Age: </h4></td>
<td><h4 th:text="${user.age}"></h4></td>
</tr>
</table>
</html>
The controller class sends and reads a form view. The User data is passed as a parameter to the processForm() handler. Spring tries to fill the bean with the request data. The data is also automatically available for the Thymeleaf result view. The #Controller annotation allows the implementation classes to be autodetected through the classpath scanning.
#Controller is typically used in combination with a #RequestMapping annotation used on request handling methods. I used the #GetMapping and ##PostMapping` as a shortcut to #RequestMapping(method = RequestMethod.POST)
#Controller
public class HomeController {
//This responds to localhost:8080/
#GetMapping("/")
public String sendForm(User user){
return "index";
}
//This responds to localhost:8080/
#PostMapping("/")
public String processForm(User user){
return "result";
}
User Class. This is the User class. It is automatically filled with data from the form request. The attributes must match the form fields. You should be able to see the matching attribute names in the template views below.
public class User {
private String fullName;
private int age;
private String occupation;
public String getFullName() {
return fullName;
}
public void setFullName(String name) {
this.fullName = name;
}
public String getOccupation() {
return occupation;
}
public void setOccupation(String occupation) {
this.occupation = occupation;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
index.html
The th:object refers to the user form bean. This is not a class name, but a Spring bean name; therefore it is in lowercase. With the *{} syntax, we refer to the defined object. In this case its the user object. I noticed that you misspelled th:field, this can also create bugs.
<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title></title>
</head>
<body>
<p> Enter Data Below </p>
<form th:action="#{/}" th:object="${user}" method="post">
<p>Full Name:<input type="text" th:field="*{fullName}" id="fullName" name="fullname" autofocus="autofocus"></p>
<p>Age:<input type="number" th:field="*{age}" id="age" name="age" autofocus="autofocus" /></p>
<p><input type="submit" value="Submit"/> <input type="reset" value="Reset"/></p>
</form>
</body>
</html>
result.html
We identify the form attributes with the ${} syntax.
<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title></title>
</head>
<body>
<table>
<tr>
<td><h4>User Name: </h4></td>
<td><h4 th:text="${user.fullName}"></h4></td>
</tr>
<tr>
<td><h4>Age: </h4></td>
<td><h4 th:text="${user.age}"></h4></td>
</tr>
</table>
</body>
</html>
I'm trying to handle a simple JSP form, that accepts your first and last name, and then prints:
Your first name: entered_first_name
Your last name: entered_last_name
using jsp:useBean action tags, so far with no luck...
Let me first show what I have written so far, and then I'll explain the problem.
This is how the UserData class looks like:
package pack;
public class UserData {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
This is how the first form (index.jsp) looks like:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<jsp:useBean id="userinfo" class="pack.UserData" scope="session"></jsp:useBean>
<jsp:setProperty property="*" name="userinfo"/>
<body>
<form action="MyServlet" method="post">
First Name: <input type="text" name="firstName"><br>
Last Name: <input type="text" name="lastName"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
and this is the relevant part from MyServlet.java:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("another.jsp").forward(request, response);
}
and this is another.jsp:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<jsp:useBean id="userinfo" class="pack.UserData"></jsp:useBean>
<body>
Your first name: <%=userinfo.getFirstName() %><br>
Your last name: <%=userinfo.getLastName() %>
</body>
</html>
When I run index.jsp, enter my first and last name, and hit "Submit", I get:
Your first name: null
Your last name: null
Which is obviously bad.
First of all, and most importantly: what am I doing wrong? why aren't the setters invoked?
Second, as you might noticed, MyServlet.java doesn't do much. it only redirects to another.jsp, so do I really need it? is there a faster, more elegant way for redirecting from one jsp to another in cases where there is no much work to do between redirection?
You must put a UserData bean in a request attribute in your servlet before forwarding :
UserData userinfo;
userinfo.setFirstName(request.getParameter("firstName");
userinfo.setLastName(request.getParameter("lastName");
request.addAttribute("userinfo", userinfo);
request.getRequestDispatcher("another.jsp").forward(request, response);
If you want things to happen automatically, you will have to use a framework such as Struts2, Spring MVC, or ...
Simple form example to understand Bean properties
index.html
<form action="welcome.jsp">
Enter Name:<input type="text" name="firstName"/>
<input type="submit" value="go" />
</form>
welcome.jsp
<jsp:useBean id="obj" class="pack.UserData" />
<jsp:setProperty name="obj" property="*" />
Welcome, <jsp:getProperty name="obj" property="firstName" />
UserData.java
public class UserData {
private String firstName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
System.out.print("the values are"+firstName);
}
}
You will get the values entered in the html page .
i am new to spring mvc
i created a project using SpringTemplateProject and used hibernate in that.
i created a form and on post the values are getting inserted in database but the problem is i am not able to display those values on POST.
here is the code.
//Controller
package com.projects.data;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
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 com.projects.data.*;
#Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
#Autowired
ServiceImpl service;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String customer(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
return "home";
}
#RequestMapping(value = "/customer", method = RequestMethod.POST)
public String addCustomer(#ModelAttribute("customer") Customer customer,Model model)
{
service.addCustomer(customer);
return "customer/customer";
}
}
Home.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<spring:url var="customer" value="/customer"/>
<form:form action="${customer}" method="post" modelAttribute="customer" commandName="custform">
<form:label path="custid">Id:</form:label>
<form:input path="custid"/> <br>
<form:label path="name">Name:</form:label>
<form:input path="name"/> <br>
<form:label path="age">Age:</form:label>
<form:input path="age"/> <br>
<input type="submit" value="Save"/>
</form:form>
</html>
customer.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>Submitted Information</title>
</head>
<body>
<h2>Submitted Information</h2>
<table>
<tr>
<td>Customer id</td>
<td>${custform.custid}</td>
</tr>
<tr>
<td>Name</td>
<td>${custform.name}</td>
</tr>
<tr>
<td>Age</td>
<td>${custform.age}</td>
</tr>
</table>
</body>
</html>
Data is getting inserted in the database but it is not getting displayed.Please help me resolve this.
I tried using #modelAttribute
model.addAttribute("custid",customer.getCustId());
model.addAttribute("name", customer.getName());
model.addAttribute("age", customer.getAge());
But this also does not seem to work.
Model Class
package com.projects.data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="customer")
public class Customer {
#Id
#Column(name="CUST_ID")
int custId;
#Column(name="NAME")
String name;
#Column(name="AGE")
int age;
public Customer(int custId,String name,int age)
{
this.custId=custId;
this.name=name;
this.age=age;
}
//getter and setter methods
public Customer() {
// TODO Auto-generated constructor stub
}
public int getCustId() {
return custId;
}
public void setCustId(int custId) {
this.custId = custId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Remove custform. from ${custform.age},${custform.name} and ${custform.custid} in jsp and keep yout model.addAttribute as it is in controller. You should be able to access age from customer using ${age} in jsp.
Controller:
#RequestMapping(value = "/customer", method = RequestMethod.POST)
public String addCustomer(#ModelAttribute("customer") Customer customer,Model model)
{
service.addCustomer(customer);
model.addAttribute("custid",customer.getCustId());
model.addAttribute("name", customer.getName());
model.addAttribute("age", customer.getAge());
return "customer/customer";
}
JSP:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>Submitted Information</title>
</head>
<body>
<h2>Submitted Information</h2>
<table>
<tr>
<td>Customer id</td>
<td>${custid}</td>
</tr>
<tr>
<td>Name</td>
<td>${name}</td>
</tr>
<tr>
<td>Age</td>
<td>${age}</td>
</tr>
</table>
</body>
</html>
OR
simply do model.addAttribute("custform",customer); in controller and leave everything else as it is.
Controller
#RequestMapping(value = "/customer", method = RequestMethod.POST)
public String addCustomer(#ModelAttribute("customer") Customer customer,Model model)
{
service.addCustomer(customer);
model.addAttribute("custform",customer);
return "customer/customer";
}
JSP
Keep it same as in question.
Try
#RequestMapping(value = "/customer", method = RequestMethod.POST)
public ModelAndView addCustomer(#ModelAttribute("customer") Customer customer)
{
service.addCustomer(customer);
Model model = new ModelMap();
model.addAttribute("custid",customer.getCustId());
model.addAttribute("name", customer.getName());
model.addAttribute("age", customer.getAge());
return new ModelAndView("customer/customer", model);
}
BTW: A better approach is to redirect (http code 303) to a customer show page, after the post. Then the user can Reload the Page (F5) without creating a new customer while each refresh.