Now we are good at basics of Spring MVC. We will see some frequently used operations with form handling.
What we need to know if we want to create any project is as below. In spring there are many concepts and very difficult to remember. To pass interview below working knowledge with concepts is enough.
Add Form data
Update Form data
Searching option for form
Delete form data
Show Data from controller
We will see all these operations in below example.
welcome-page.jsp
<html>
<head>
<title>Spring MVC Demo</title>
</head>
<body>
<h2>${message}</h2>
<form action="user/newuser">
<input type="submit" value="Add New User"></input>
</form>
<form action="user/showallusers">
<input type="submit" value="Show All Users"></input>
</form>
<form action="user/searchuserpage">
<input type="submit" value="Search/Edit Any User"></input>
</form>
</body>
</html>
User.java
package com.javabykiran;
public class User {
private String name;
private Integer id;
public User(String name, Integer id) {
super();
this.name = name;
this.id = id;
}
public User() {
super();
// TODO Auto-generated constructor stub
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
WelcomeController.java
package com.javabykiran;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
@RequestMapping("/")
public class WelcomeController {
@RequestMapping(value = "/", method = RequestMethod.GET)
public String welcome(Model model) {
model.addAttribute("message", "Hello Spring MVC Framework!");
return "welcome-page";
}
}
userController.java
package com.javabykiran;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
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.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/newuser")
public String newUser(Model model) {
System.out.println("I am in new User method..");
model.addAttribute("user", new User());
return "userForm";
}
@RequestMapping(value = "/showuser", method = RequestMethod.GET)
public ModelAndView showUser(@RequestParam("idtosearch") int idtosearch ) {
System.out.println("Id to receive.." + idtosearch);
Map<String, Object> model = new HashMap<String, Object>();
User user = new User("kiran", idtosearch);
model.put("userKey", user);
return new ModelAndView("userpage", model);
}
/* @RequestMapping("/showuser")
public ModelAndView showUser(HttpServletRequest request) {
int id = Integer.parseInt(request.getParameter("idtosearch"));
User user = new User("kiran", 12);
System.out.println("Id to receive.." + id);
Map<String, Object> model = new HashMap<String, Object>();
model.put("userKey", user);
return new ModelAndView("userpage", model);
}
*/
@RequestMapping("/searchuserpage")
public String searchUserPage() {
return "searchuserpage";
}
@RequestMapping("/showallusers")
public ModelAndView showAllUser(HttpServletRequest request) {
ArrayList<User> userList = new ArrayList<>();
User user1 = new User("kiran", 12);
User user2 = new User("kiran1", 11);
userList.add(user1);
userList.add(user2);
Map<String, Object> model = new HashMap<String, Object>();
model.put("employees", userList);
return new ModelAndView("employeesList", model);
}
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser(@ModelAttribute("user") User user) {
System.out.println("I am in add user");
System.out.println(user.getName());
System.out.println(user.getId());
return "result";
}
@RequestMapping(value = "/updateuser", method = RequestMethod.POST)
public String updateuser(User user) {
System.out.println("I am in update user");
System.out.println(user.getName());
System.out.println(user.getId());
return "result";
}
}
We can pass and use the HttpServletRequest object in a controller method to get access to all request parameters (i.e. GET request).
@RequestMapping("/user")
public String showUser(HttpServletRequest request){
int id = Integer.parseInt(request.getParameter("id"));
/*...*/
}
We can also read form data using @RequestParam annotation. This is a different way for reading form data in the request parameters.
Here, we bind a variable with a value fetched from@RequestParam annotation.
result.jsp
<h2>User Data Received..</h2>
<table>
<tr>
<td>Name</td>
<td>${user.name}</td>
</tr>
<tr>
<td>ID</td>
<td>${user.id}</td>
</tr>
</table>
There are set of object made available in JSP pages such as request, response, param, paramValues, cookie, etc.
The param object maps a request parameter name to a single value, while the paramValues maps a request parameter name to an array of values.
When the form is submitted (let’s say for adding a new user), we can bind the user object with form data submitted. How? The model attribute that come with @ModelAttribute annotation is bind-ed to the data submitted.
So, we can bind the user object with the model attribute (call it user for example), and access all the data submitted using the user object
The @ModelAttribute annotation makes the model attribute user available to view pages to access and display it.
This is the method we will be using in our example.
If the data is passed in the request body (i.e. POST request), then, we can access the data using@RequestBody instead.
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser(@RequestBody User user){/*...*/}
userForm.jsp
<h2>User Data</h2>
<form action="addUser" method="POST">
Name : <input type="text" name="name" /> </br>
ID : <input type="text" name="id"></br>
<input type="submit" value="Click" />
</form>
You can use spring tags as well here like below.
<%@taglib uri="http://www.springframework.org/tags/form"
prefix="springform"%>
<springform:form action="addUser" modelAttribute="user" method="POST">
<br><br>
<springform:label path="name" >Name</springform:label>
<springform:input path="name" />
<br>
<br>
<springform:label path="id">Id</springform:label>
<springform:input path="id" />
<br>
<br>
<input type="submit" value="Submit" />
</springform:form>
employeesList.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<h1>List Employees</h1>
<h3>
<a href="newuser">Add More Employee</a>
</h3>
<c:if test="${!empty employees}">
<table align="left" border="1">
<tr>
<th>Employee ID</th>
<th>Employee Name</th>
</tr>
<c:forEach items="${employees}" var="employee">
<tr>
<td><c:out value="${employee.id}" /></td>
<td><c:out value="${employee.name}" /></td>
</tr>
</c:forEach>
</table>
</c:if>
Searchuserpage.jsp
<form action="showuser" method="get">
ID to search : <input type="text" name="idtosearch"/><br>
<input type="submit" value="Search / Edit Student"/>
</form>
userpage.jsp
<form action="updateuser" method="post">
name : <input type="text" name="name" value="${userKey.name}"/>
<br>
Id :<input type="text" name="id" value="${userKey.id}"/>
<br>
<input type="submit" value="Update Student Data">
</form>
spring-mvc-demo-servlet.xml keep as it is as previous program.
web.xml keep as it is as previous program.
pom.xml will be as below.
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>JBK_Spring_MVC</groupId>
<artifactId>JBK_Spring_MVC</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<!-- Generic properties -->
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!-- Spring -->
<spring-framework.version>5.1.3.RELEASE</spring-framework.version>
</properties>
<dependencies>
<!-- Spring IOC start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Spring IOC end -->
<!-- Servlet+JSP+JSTL start -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Servlet+JSP+JSTL end -->
<!-- Spring MVC start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring-framework.version}</version>
</dependency>
<!-- Spring MVC end -->
<!-- thymeleaf UI theme start -->
<!-- <dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.0.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.9.RELEASE</version>
</dependency> -->
<!-- thymeleaf UI theme end -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
See complete project structure it will look like this.