DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux
  • Graceful Shutdown: Spring Framework vs Golang Web Services
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4

Trending

  • Cosmos DB Disaster Recovery: Multi-Region Write Pitfalls and How to Evade Them
  • Agile and Quality Engineering: A Holistic Perspective
  • How Trustworthy Is Big Data?
  • Infrastructure as Code (IaC) Beyond the Basics
  1. DZone
  2. Coding
  3. Frameworks
  4. Converting a Spring SimpleFormController into an @Controller

Converting a Spring SimpleFormController into an @Controller

By 
David Salter user avatar
David Salter
·
Apr. 20, 11 · Interview
Likes (8)
Comment
Save
Tweet
Share
59.7K Views

Join the DZone community and get the full member experience.

Join For Free

In my previous post, I showed how to convert a Spring web controller class to use the @Controller annotation. In this post, I aim to show how forms in a Spring MVC application can also be converted to using annotations.

Forms in Spring are typically modelled by extending the org.springframework.web.servlet.mvc.SimpleFormController class, but using Spring annotations, they can also be simplified and defined by the @Controller annotation.Without annotations, a SimpleFormController would be defined as below as in both a Java class and as a bean in XML.

import org.springframework.web.servlet.mvc.SimpleFormController 
   
public class PriceIncreaseFormController extends SimpleFormController { 
   
    public ModelAndView onSubmit(Object command) { 
        // Submit the form 
    } 
       
    protected Object formBackingObject(HttpServletRequest request) 
        throws ServletException { 
        // Initialize the form 
    } 
}
<bean name="/priceincrease.htm" class="springapp.web.PriceIncreaseFormController"> 
    <property name="commandName" value="priceIncrease"/> 
    <property name="commandClass" value="springapp.service.PriceIncrease"/> 
    <property name="validator"> 
        <bean class="springapp.service.PriceIncreaseValidator"/> 
    </property> 
    <property name="formView" value="priceincrease"/> 
    <property name="successView" value="home.htm"/> 
</bean>

 To convert the class to use annotations, we need to add an @Controller and @RequestMapping annotation.  We can then define a simple POJO controller that does not need to extend Spring's classes.

@Controller 
@RequestMapping("/priceincrease.htm") 
public class PriceIncreaseFormController { 
  
    @Autowired
    private PriceIncreaseValidator priceIncreaseValidator; 
   
    @RequestMapping(method=RequestMethod.POST) 
    public String onSubmit(@ModelAttribute("priceIncrease")PriceIncrease priceIncrease, 
        BindingResult result) { 
           
        int increase = priceIncrease.getPercentage(); 
        priceIncreaseValidator.validate(increase, result); 
        if (result.hasErrors()) 
            return "priceIncrease"; 
           
        // Validator has succeeded. 
        // Perform necessary actions and return to success page. 
        return "redirect:home.htm"; 
    } 
       
    @RequestMapping(method=RequestMethod.GET) 
    public String initializeForm(ModelMap model) { 
        // Perform and Model / Form initialization
        Map<Integer, String> priority = new LinkedHashMap<Integer, String>();
        priority.put(1, "Low");
        priority.put(2, "Normal");
        priority.put(3, "High");
  
        model.addAttribute("priorityList", priority);
   
        return "priceincrease"; 
    } 
   
    // Other getters and setters an needed. 
}

After defining the class like this, there is no need for the class to be defined within the Spring Context XML file.

The two methods outlined above in this simple class show how the initializeForm() method is called when an HTTP GET request is made to the form and how the form is submitted in the onSubmit() method via a HTTP POST request.  The method called on a GET request is used to initialize the form, whereas the method called on a POST request is called when the form is submitted.

The final thing to notice from this class is that the validation has to be explicitly called within the onSubmit() method.  In this example, the PriceValidator is injected into the class via the @Autowired annotation.

 

From http://www.davidsalter.co.uk/1/post/2011/04/converting-a-spring-simpleformcontroller-into-an-controller.html

Spring Framework

Opinions expressed by DZone contributors are their own.

Related

  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux
  • Graceful Shutdown: Spring Framework vs Golang Web Services
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!