Spring MVC Hidden Value Example
This is an example of how to make use of a hidden value in Spring MVC. Spring MVC provides tags that are very similar to HTML tags and can offer the same functionality. When creating a form, there is sometimes a need to keep a value in a view and use it in a next step, without making it visible to the client. In this case we must make the component that renders the value hidden. In order to do so we can make use of the simple input
tag, and set its type
to hidden
.
Below, we create a simple class, with a String property. It will be used as the Model. We also create a Controller and a view to render the hidden value.
You may skip project creation and jump directly to the beginning of the example below.
Our preferred development environment is Eclipse. We are using Eclipse Juno (4.2) version, along with Maven Integration plugin version 3.1.0. You can download Eclipse from here and Maven Plugin for Eclipse from here. The installation of Maven plugin for Eclipse is out of the scope of this tutorial and will not be discussed. We are also using JDK 7_u_21. Tomcat 7 is the application server used.
Let’s begin,
1. Create a new Maven project
Go to File -> Project ->Maven -> Maven Project.
In the “Select project name and location” page of the wizard, make sure that “Create a simple project (skip archetype selection)” option is unchecked, hit “Next” to continue with default values.
Here the maven archetype for creating a web application must be added. Click on “Add Archetype” and add the archetype. Set the “Archetype Group Id” variable to "org.apache.maven.archetypes"
, the “Archetype artifact Id” variable to "maven-archetype-webapp"
and the “Archetype Version” to "1.0"
. Click on “OK” to continue.
In the “Enter an artifact id” page of the wizard, you can define the name and main package of your project. Set the “Group Id” variable to "com.javacodegeeks.snippets.enterprise"
and the “Artifact Id” variable to "springexample"
. The aforementioned selections compose the main project package as "com.javacodegeeks.snippets.enterprise.springexample"
and the project name as "springexample"
. Set the “Package” variable to "war"
, so that a war file will be created to be deployed to tomcat server. Hit “Finish” to exit the wizard and to create your project.
The Maven project structure is shown below:
- It consists of the following folders:
- /src/main/java folder, that contains source files for the dynamic content of the application,
- /src/test/java folder contains all source files for unit tests,
- /src/main/resources folder contains configurations files,
- /target folder contains the compiled and packaged deliverables,
- /src/main/resources/webapp/WEB-INF folder contains the deployment descriptors for the Web application ,
- the pom.xml is the project object model (POM) file. The single file that contains all project related configuration.
2. Add Spring-MVC dependencies
Add the dependencies in Maven’s pom.xml
file, by editing it at the “Pom.xml” page of the POM editor. The dependency needed for MVC is the spring-webmvc
package.
pom.xml
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.javacodegeeks.snippets.enterprise</groupId> <artifactId>springexample</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>springexample Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> </dependencies> <build> <finalName>springexample</finalName> </build> <properties> <spring.version>3.2.9.RELEASE</spring.version> </properties> </project>
3. Create the model
The HiddenMessage.java
class is the class created to be used as the Model. It has a String property, which is the message
. This field will be used for the hidden value. It has getter and setter methods, so that its value is rendered by the view.
HiddenMessage.java
package com.javacodegeeks.snippets.enterprise.hidden.model; public class HiddenMessage { private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
4. Create the Controller
The Controller
is where the DispatcherServlet
will delegate requests. The @Controller
annotation indicates that the class serves the role of a Controller. The @RequestMapping
annotation is used to map a URL to either an entire class or a particular handler method.
The Controller consists of two basic methods, a GET method, which is String initForm(Model model)
and a POST method, which is String submitForm(Model model, HiddenMessage hiddenMsg, BindingResult result)
. The first method creates and returns to the "hidden"
view a new instance of the HiddenMessage.java
class.
The second method also gets the Model
, and the HiddenMessage
object created, which now consists of the values passed in the form. The successHidden.jsp
page is the page rendered when the button is pressed, after the hiddenMsg
object is passed at the Model
.
HiddenController.java
package com.javacodegeeks.snippets.enterprise.hidden; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.javacodegeeks.snippets.enterprise.hidden.model.HiddenMessage; @Controller @RequestMapping("/hidden.htm") public class HiddenController { @RequestMapping(method = RequestMethod.GET) public String initForm(Model model) { HiddenMessage hiddenMsg = new HiddenMessage(); model.addAttribute("message", hiddenMsg); return "hidden"; } @RequestMapping(method = RequestMethod.POST) public String submitForm(Model model, HiddenMessage hiddenMsg, BindingResult result) { model.addAttribute("message", hiddenMsg); return "successHidden"; } }
5. Create the view with the hidden value
The view below is a simple example of how to create a form with a hidden value. It is a simple html view consisting of the head
and body
html tags. In order to create a form in Spring MVC, we make use of the form:form
tag. Its method
property is set to POST, and the commandName
property is set to the name of the backing bean that is binded to the Model, which is the HiddenMessage.java
class.
In order to create a hidden value, we are using the simple input
tag, with name
property set to the message
, which is the field bound to it. Its type
parameter is set to hidden
, so this component is not visible in the view. It also has a value
parameter set to a String message.
hidden.jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <html> <title>Spring MVC hidden value</title> </head> <body> <form:form method="POST" commandName="hiddenMessage"> <h2>Do you know what the hidden message is? </h2> <table> <tr> <input name="message" type="hidden" value="Hello Geeks!!"/> </tr> <tr> <td><input type="submit" name="submit" value="Click here to see"></td> </tr> <tr> </table> </form:form> </body> </html>
This page will be rendered when the button is pressed:
successHidden.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <html> <head> <title>Spring MVC hidden value</title> </head> <body> <h2>${hiddenMessage.message}</h2> </body> </html>
6. Configure the application
The files that we must configure in the application are the web.xml
file and the mvc-dispatcher-servlet.xml
file.
The web.xml
file is the file that defines everything about the application that a server needs to know. It is placed in the /WEB-INF/
directory of the application. The <servlet>
element declares the DispatcherServlet
. When the DispatcherServlet
is initialized, the framework will try to load the application context from a file named [servlet-name]-servlet.xml
located in /WEB-INF/
directory. So, we have created the mvc-dispatcher-servlet.xml
file, that will be explained below. The <servlet-mapping>
element of web.xml
file specifies what URLs will be handled by the DispatcherServlet
.
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Archetype Created Web Application</display-name> <servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
The mvc-dispatcher-servlet.xml
file is also placed in WebContent/WEB-INF
directory. The org.springframework.web.servlet.view.InternalResourceViewResolver
bean is used as internal resource views resolver, meaning that it will find the jsp
and html
files in the WebContent/WEB-INF/
folder. We can also set properties such as prefix
or suffix
to the view name to generate the final view page URL. This is the file where all beans created, such as Controllers are placed and defined.
The <context:component-scan>
tag is used, so that the Spring container will search for all annotated classes under the com.javacodegeeks.snippets.enterprise
package. The <mvc:annotation-driven>
tag is used, so that the container searches for annotated classes, to resolve MVC.
mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <context:component-scan base-package="com.javacodegeeks.snippets.enterprise" /> <mvc:annotation-driven /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>
7. Run the application
Now, let’s run the application. We first build the project with Maven. All we have to do is right click on the project and select -> Run As: Maven build. The goal must be set to package. The .war
file produced must be placed in webapps
folder of tomcat. Then, we can start the server.
Hit on:
http://localhost:8080/springexample/hidden.htm
The page rendered is the one below:
Click on the “Click here to see” button:
The result is the hidden value.
This was an example of how to make use of a hidden value in Spring MVC.
Download the eclipse part of this tutorial: SpringMVCHiddenValue