This post is part of Servlet to Spring series, so we recommend you follow the whole series to get the maximum out of it.

Spring MVC is possibly one of the most popular MVC (Model View Controller) currently used in java ecosystem today. It has become defacto choice of technology for creating everything from simple one page web application to complex web applications.

Why do we need a MVC?

This may seem like a very naive question but it still need to be addressed nevertheless. We almost assume that you cant build a web application without a MVC framework but it wasn’t always like this, as we have seen in our series, we can build a web application without a MVC. So what advantage would MVC bring to the table.

MVC provides a clean logical separation of component based on responsibilities. The presentation is handled by a view technology like JSP, Freemarker, Velocity or Thymeleaf. No other component should be responsible for rendering logic. The controller handles the flow of control of application, it would decide if the system should proceed to next view or show error and what the next view should be based on your role or some logic. The model is responsible for managing everything related to business logic, storing, retrieving the data. Since every application is quite different from other, each application would have very different model that other.

Spring MVC has controller classes to mange the flow of application, which would call some spring managed beans which would serve as model for the application, Spring MVC supports JSP, Freemarker, Velocity, Thymeleaf and lots of other technologies for view, which you can choose from.

Front Controller

In a typical MVC every request is handled by a single component which then delegates it to appropriate delegate class for handling, this pattern is known as FrontController. In Spring MVC the DispatcherServlet is an actual servlet much like our servlets from previous parts of the series. Once it receives a web request it looks for an appropriate handler which would be a controller. Spring essentially scans the classpath for all classes to see if any of them has @Controller annotation (there are other ways to specify a controller but this is by far most popular way) and a method which has @RequestMapping annotation. Each of these method gets registered with DispatcherServlet as a handler mapping, which is used appropriately to handle the request.

Lets add the basic config to our wine store application, we will do this by adding a front controller servlet in web.xml and map every request to this.

<servlet>
        <servlet-name>wine</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>wine</servlet-name>
        <url-pattern>/wines/*</url-pattern>
    </servlet-mapping>

By adding this config, we told the web server to send all the request matching /wine/* to spring via DispatcherServlet, it is usually a good idea to use a prefix to all the server request, this way any request for static resource like image or javascript file would not be routed to the spring servlet. Another popular way is to use a *.do suffix, in which case every server request ends with .do suffix.

By adding a default servlet named wine, Spring would expect a file name spring-servlet.xml in the path /WEB-INF/, so lets move the applicationContext.xml from our last post to spring-servlet.xml

<?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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>

    <context:component-scan base-package="com.learnithardway.web"/>


</beans>

Controller

Controllers are basic building block of any spring MVC application which receive the data from view and decide what should be done with the request. They usually hand over the request data to model and based on the response from model, they would decide the view.

In our example, we already have a front page for our wine store, we would add a few more pages to list all the wines and an admin page to create new wines. Let’s convert our servlet from our earlier example to a spring controller.

@Controller
public class IndexController {

    @Autowired
    WineService wineService;

    @RequestMapping(path = "/", method = RequestMethod.GET)
    public String getWineList(Model model) {
        List wines = new ArrayList<>();
        List listOfWines = wineService.getListOfWines();
        model.addAttribute("wines", listOfWines);
        return "/wines.jsp";
    }
}

Each controller is passed with Model object which the controller can put the model objects into, this is very similar to how we were putting our model in request. The controller also returns a string which is the name of the view which would map to the actual file based on the view resolver. In this case we are using the default jstl view resolver.

Notice that since this is a spring managed bean, we do not need to manually initialise the bean or do a look up, its all auto wired for us to use.

Now run the application using

mvn jetty:run

You should see the application working like this.

In the next post, we would see how to use spring to create a page to add more wine to our collection 🙂


Author

Nitiz

There are currently no comments.

Bitnami