Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Controlling Spring MVC

See in this article several cases of the use of the @Controller annotation, and how comprehensive and flexible is that the Spring Framework Tool

Currently in software development, the big "bam bam bam" development models is the MVC ( "Model-View-Controller"), which was first described around 1970 by Trygve Reenskaug who worked with Smalltalk (Language of object-oriented programming). It was created to escape the old mess, where the code is mixed between the page and persistence. This model facilitates the maintainability of the code, since the change in view (page) does not affect the "Controller" or "model".

The Spring, as it could not be left out, was created based in Spring MVC, where we have @Controller (which will be discussed more thoroughly in this article), @Service (facilitator to access Models from a persistence framework of your choice or JDBC pure) and Views. Our views are JSP, it is not just that the framework has.

Now, let's delve in the Spring Controllers and understand what you can create with them.

Requirements

A Dynamic Web Project set up with the libraries of Spring and running properly. See reference at the end of the article to article with access configuration examples - we will use the same design contained in the article.

A Controller is responsible both for receiving requests and for sending the response to the user, something very similar to the Servlet. However, it is done more elegantly and easily. The Controller is responsible for informing the View, the attributes that will be visible to the same and also to receive coming parameters View. And lastly, to respond to the user what was required. See a sample in Listing 1.

Listing 1. Creating a controller

@Controller // Set my class is a controller
public class HomeController {
 
}

See how simple it is to create a Controller, but note that it has no "mapping" linked to it. Then we create one view (jsp) call "home.jsp" folder within the "/WEB-INF/views" and create the mapping "/home" to display the view created. See Listing 2.

Listing 2. Creating a RequestMapping to HomeController

 @Controller // Set my class is a controller
public class HomeController {
 
    @RequestMapping(“/ home") / / Set the URL that is requested when the called method public ModelAndView home() {
                // Returns the view that should be called, in case home (home.jsp) here the .jsp is omitted
                return new ModelAndView("home");
            }
 
        }

Now we know how to make a request and return a page, but let's assume my home session have multiple pages within it, for example /home/main and /home/secondary. For this, we make a small change in our "HomeController", as in Listing 3.

Listing 3. Modifying HomeController

 @Controller // Set my class is a controller
@RequestMapping("/home") // Set any action that must as controler/home
public class HomeController {
 
    // Set the URL that is requested when the called method /home/main or /home/ or /home
    // Note that it is not required only a url, you can map several for the same method
    @RequestMapping(value = {
        "/",
        "",
        "/ main"
    })
    public ModelAndView homeMain() {
        // Returns the view that should be called, in the main case (main.jsp) that is inside the folder/home
        return new ModelAndView("home/main");
    }
 
    // Set the URL that is requested when the called method
    @RequestMapping("/Secondary")
    public ModelAndView homeSecondary() {
        // Returns the view that should be called in the secondary case (secondary.jsp) that is inside the folder/home
        return new ModelAndView("home/secondary");
    }
}

Note: Not necessarily the views should be contained in the "/ home" is just a way to organize them better.

Passing parameters

Now we understand better how work requests and responses of the "Controller", now we will see how to receive parameters and pass attributes to the "View". For this, we will create a new "Controller" called "ParamController" and follow the same path of "HomeController" but now accessing the url "/param". Notice this in Listing 4.

Listing 4. Creating and mapping the ParamController

 @Controller
@RequestMapping("/param")
public class ParamController {
            
            @RequestMapping(value = { "" , "/" } )
            public ModelAndView receivesParam(@RequestParam String name , Model model){
                        //@RequestParam received indicates that a parameter "name" which is a String
                        //Model is a auxuliar that helped to add attributes to our view
                        model.addAttribute("name" , name);
                        return new ModelAndView("param/index");
            }
            
}

Do not forget to create in "WEB-INF/views" folder "param" and within it the view "index.jsp" as described inListing 5.

Listing 5. Creating a view param/index.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>Controllers Spring</title>
    </head>
 
    <body>
        <h1>Param - Index</h1>
 
        <p>Parameter name = "
            <%= request.getAttribute("name") %>"</p>
        <p>Page call from mapping in ParamController</p>
    </body>
 
    </html>

Explaining what was done: to map the @RequestParam i'm telling method that he should expect to name parameter "name" a String, or to access? "/ Param name = SeuNomeAqui" parameter name will be assigned to variable "name", and "Model" will be responsible for sending it to the screen attribute.

Very easy not? But wait: what if the parameter is not passed, what will happen? an error is returned: "Required String parameter 'name' is not present." For the safety and security of application operation that's great, but if you do not want the parameter is required, just map it as "@RequestParam (required = false)," and see how the name gets null, and no error is returned. The use depends on your needs.

Limiting the kinds of received Methods

Now we will see how we can limit a mapping to only receive requests via "POST" or "GET".

Note: There will be addressed RESTful this article.

To confine a Mapping to only receive requests "GET" or "POST", add to our "ParamController" two new methods (Mappings). See in Listing 6.

Listing 6. Adding GET and POST limitations

 @Controller
@RequestMapping("/param")
public class ParamController {
 
    @RequestMapping(value = {  "", "/" })
    public ModelAndView receivesParam(@RequestParam(required = false) String name, Model model) {
        //@RequestParam received indicates that a parameter "name" which is a String
        //Model is a auxuliar that helped to add attributes to our view
        model.addAttribute("name", name);
        return new ModelAndView("param/index");
    }
 
    @RequestMapping(value = "/postonly", method = RequestMethod.POST)
    public ModelAndView postOnly() {
        // the method defines what kind of request this mapping will accept
        return new ModelAndView("param/postonly");
    }
 
    @RequestMapping(value = "/getonly", method = RequestMethod.GET)
    public ModelAndView getOnly() {
        return new ModelAndView("param/getonly");
    }
}

By setting the "method" we tell our controller that will only run if the method is a request of the specified type. If no "method" is defined in @RequestMapping, by default it will receive as much GET as POST. If you try to access a POST mapping via GET, an error is returned: "Request method 'GET' not supported". The receiving parameters and sending attributes to the view remain the same without any changes.

Access the URL on your server "param/getonly" and see everything that occurs normally. Now try to access "param/postonly" and see the error.

Receiving completed forms

We have seen how to receive parameters, such as limiting the type of request accepted. And the forms? Calm, not a giant list of @RequestParam is required, unless you like to write!

Spring provides a notation called @ModelAttribute which can be a POJO, a domain etc... Will use a POJO (Plain Old Java Object - class containing only a default constructor, attributes and getters and setters) as an example and will also use the tag Spring form to assist us in sending. Then we create a call controller "FormController", as in Listing 7.

Listing 7. FormController

 @Controller
@RequestMapping("/form")
public class FormController {
   
       @RequestMapping(value = { "/" , ""  } , method = RequestMethod.GET)
       public ModelAndView carriesForm(Model model){
             model.addAttribute("form", new Form());
             return new ModelAndView("form/form");
       }      
       
       @RequestMapping(value = { "/" , "" } , method = RequestMethod.POST)
       public ModelAndView receivesForm(@ModelAttribute("form") Form form, Model model){
             model.addAttribute("msg", "You sent: " + form.getName() + " " + form.getLastname() );
             return new ModelAndView("form/form");
       }
       
}

As you may have noticed, we have two @RequestMapping pointing the same way. The Spring will make the difference that method will be called by the type of request being made. See also being added to our view an object "Form". Now we will create our Form object, as in Listing 8.

Listing 8. POJO Form

 public class Form {
 
    private String name;
 
    private String lastname;
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getLastName() {
        return lastname;
    }
 
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
 
}

Now we will create our view containing the form. To this, add a jsp in "/WEB-INF/views/form/" with the name "form.jsp". See Listing 9.

Listing 9. View form.jsp

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<!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>Controllers Spring</title>
</head>
<body>
          <jsp:include page="/WEB-INF/views/_menu.jsp" />
 
     <h1>Form</h1>
         
         <p>Page call from mapping in FormController</p>
         
         <form:form id="frmForm" action="" method="post" modelAttribute="form">
                 <div>
                          <form:label path="name" cssStyle="width:80px; text-align:right;display:inline-block">Nome:</form:label>
                          <form:input path="name"/>
                 </div>
                 <div>
                          <form:label path="lastname" cssStyle="width:80px; text-align:right;display:inline-block">Lastname:</form:label>
                          <form:input path="sobrenome"/>
                 </div>
                 
                 <form:button>Enviar</form:button>
         </form:form>
         
         <%= (request.getAttribute("msg") != null) ? request.getAttribute("msg") : "" %>
         
</body>
</html>

See we import the taglib "form" of Spring. It will help us to read an object that has been passed by "Controller". Let's dissect our form:

Listing 10. Form tag: form

 <form:form id="frmForm" action="" method="post" modelAttribute="form">

Note the attribute "modelAttribute = 'form' 'with it we tell our form with that object are working in casso object" form "that was added by calling the view.

Listing 11. Form tag: label

 <form:label path="name" cssStyle="width:80px; text-align:right;display:inline-block">Name:</form:label>

The form tag: label will create a label for the attribute "name" as specified by "path". "CssStyle" is the same as the "style" of HTML and was added just to let a little more presentable form.

Listing 12. Form tag: input

 <form:input path="name"/>

The tag "form:input" will create a field for the "name" attribute of our "form" object.

Listing 13. Tag form: button

 <form:button>Send</form:button>

The tag "form: button" create a form submit button.

Now all set to run your application, go to the form and see the result.

The Spring provides us with several easy to use and quick learning tools. See it's a very fast and without much weight to our server framework.

Unit the next one! :)



Web developer and passioned for web design, SEO and front end technologies.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login