Java and J2EE Tutorials, Jsp and Servlet Tutorials, Spring MVC, Solr, XML, JSON Examples, Hibernate & Struts 2 Hello World projects



Sunday, 17 March 2013

Spring Form Tags - How to use Text Box, Radio Button, Check Box and Drop Down List in Spring

In our previous discussion we came across the basic Spring MVC features, we created a simple Hello World application using Spring MVC in eclipse, than we came to know how to integrate Spring with Hibernate. We have also implemented Tiles with Spring MVC. In this particular blog we will be concentrating on Basic spring form tags and their implementation.

Project Structure
Before we dive into spring form tags and their usage, lets take a look at overall project structure for today's discussion.


Libraries User
Following are the library files that we have to add in our lib folder, please copy all required jar files and add the code files according to project structure as shown in the later part of the tutorial.


/WebContent/WEB-INF/web.xml
We all knows it already that every web application starts with a web.xml file in java. Here we have added a servlet entry with name DispatcherServlet this will tell the container that every request that ends up with '.html' will be handled by spring itself.
<?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_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>Spring3MVC</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
</web-app>


/WebContent/index.jsp
This is the welcome file for our example project, we have added a send redirect here so that the application control can be transfered to spring.
<html>
<head>
<title>Being Java Guys | Hello World</title>
</head>
<body>
    <%
        response.sendRedirect("getSpringForm.html");
    %>
</body>
</html>


/WebContent/WEB-INF/spring-servlet.xml
This file is the core of spring MVC projects, all related configurations and setting goes here.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    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">


    <context:component-scan base-package="com.beingjavaguys.controller" />

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>


/src/com/beingjavaguys/domain/User.java
This is a simple java file that indicated the details and attributes of User, we have to add user's details through spring form tags and w'll associate those values to User bean.
package com.beingjavaguys.domain;

public class User {

    private String name;
    private String gender;
    private String city;
    private String interest[];

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String[] getInterest() {
        return interest;
    }

    public void setInterest(String[] interest) {
        this.interest = interest;
    }

}


/src/com/beingjavaguys/controller/Home.java
Ths is the controller for our application, here we have added two request mappings according to our project need."/getSpringForm" is responsible to render a jsp page with form elements to add up details there. When user clicks on submit button the control is transfered to '/showDetails' mapping to show entered details in correct format.
package com.beingjavaguys.controller;

import java.util.ArrayList;
import java.util.HashMap;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.beingjavaguys.domain.User;

@Controller
public class Home {
    private ArrayList<String> cityNames;
    private ArrayList<String> interests;
    private HashMap<String, ArrayList<String>> model;

    @RequestMapping("/getSpringForm")
    public ModelAndView hello(@ModelAttribute User user, BindingResult result) {

        ArrayList<String> cityNames = new ArrayList<String>();
        cityNames.add("Delhi");
        cityNames.add("Gurgaon");
        cityNames.add("Ghaziabad");
        cityNames.add("Noida");
        cityNames.add("New Delhi");
        ArrayList<String> interests = new ArrayList<String>();
        interests.add("Man");
        interests.add("Women");
        interests.add("Both");
        HashMap<String, ArrayList<String>> model = new HashMap<String, ArrayList<String>>();
        model.put("cityNames", cityNames);
        model.put("interests", interests);

        return new ModelAndView("SpringForm", "model", model);
    }

    @RequestMapping("/showDetails")
    public ModelAndView showDetails(@ModelAttribute("user") User user,
            BindingResult result) {

        System.out.println("Name : " + user.getName());
        System.out.println("Gender : " + user.getGender());
        System.out.println("City : " + user.getCity());
        System.out.println("Interest : " + user.getInterest().length);
        return new ModelAndView("Details", "user", user);

    }

    public ArrayList<String> getCityNames() {
        return cityNames;
    }

    public void setCityNames(ArrayList<String> cityNames) {
        this.cityNames = cityNames;
    }

    public ArrayList<String> getInterests() {
        return interests;
    }

    public void setInterests(ArrayList<String> interests) {
        this.interests = interests;
    }

    public HashMap<String, ArrayList<String>> getModel() {
        return model;
    }

    public void setModel(HashMap<String, ArrayList<String>> model) {
        this.model = model;
    }

}


/WebContent/WEB-INF/jsp/SpringForm.jsp
This is the actual jsp file which contains all spring tags so that the registration form with mentioned fields can be rendered against the user.
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<html>
<head>
<title>Being Java Guys | Spring Form</title>
</head>
<body>
    <center>

        <h2>Being Java Guys | Registration Form</h2>

        <c:url var="showDetails" value="showDetails.html" />
        <form:form method="get" action="${showDetails}" modelAttribute="user">
            <table>
                <tr>
                    <td>Name</td>
                    <td><form:input path="name" />
                    </td>
                </tr>
                <tr>
                    <td>Name</td>
                    <td><form:radiobutton path="gender" value="Male" />Male<form:radiobutton
                            path="gender" value="Female" />Female</td>
                </tr>
                <tr>
                    <td>Name</td>
                    <td><form:select path="city" items="${model.cityNames}" />
                    </td>
                </tr>
                <tr>
                    <td>Name</td>
                    <td><form:checkboxes items="${model.interests}"
                            path="interest" />
                    </td>
                </tr>
                <tr>
                    <td>Name</td>
                    <td><input type="submit" value="Submit" />
                    </td>
                </tr>
            </table>
        </form:form>
    </center>
</body>
</html>


/WebContent/WEB-INF/jsp/Details.jsp
This is the jsp file which cotains code to show up all user details and values that are being added to spring form at the time of registration.
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>Being Java Guys | Registration Form</title>
</head>
<body>
    <center>

        <h2>Being Java Guys | User Details</h2>

        <table border="1">
            <tr>
                <td>Name :</td>
                <td>${user.name}</td>
            </tr>
            <tr>
                <td>Gender :</td>
                <td>${user.gender}</td>
            </tr>
            <tr>
                <td>City :</td>
                <td>${user.city}</td>
            </tr>
            <c:forEach items="${user.interest}" var="interset">
                <tr>
                    <td>Interest :</td>
                    <td>${interset}</td>
                </tr>
            </c:forEach>
        </table>
    </center>
</body>
</html>

Here we are done with all configurations and coding, just run the application on server and you will get a registration spring form something like this screen.


Once all fields values are filled and the user clicks on submit button, all those details are handled over the request url and submitted values can be seen as shown in next figure.

Today we have created a spring form tags simple hello wold application in eclipse. In our next tutorials we will come to know more about spring and other java web frameworks and technologies.









Thanks for reading !
Being Java Guys Team


3 comments:

  1. Nice example !!!

    ReplyDelete
  2. Please explain for me why my result URL when click submit it's "http://localhost:8080/springformhanding/showDetails?city=Ghaziabad" not like your result. Thank you so much!

    ReplyDelete
  3. good example of beginners

    ReplyDelete

Like Us on Facebook


Like Us On Google+



Contact

Email: neel4soft@gmail.com
Skype: neel4soft