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

Step-By-Step: Creating a Spring MVC Application

In this tutorial, we shall take a look at how one can make use of Spring MVC and create a rather simple web application based in Java. We shall we taking the help of Spring Tool Suite to achieve our purpose.

In today’s world of the Internet and a large variety of applications, developing them is always in demand. There are many languages and platforms that make the development of such applications easier. However, one of the primary languages used for application development is Java, with the model-view-controller architecture. For this, the Spring MVC framework is a perfect combination to build such applications.

What is Spring MVC?

Spring MVC happens to be a cross-platform application framework that is written in Java and also meant for use with it. The framework belongs to the open source community and its core features can be largely used in all types of Java applications. Over the years, it has become a very popular framework within the Java community and is seen as an alternative to several other frameworks.

What is MVC?

MVC is an architecture which expands to model-view-architecture. This is largely employed for the development of flexible and loosely coupled web applications. The MVC layout mainly divides the different parts of the applications in to three main categories, as mentioned. These parts make up the input logic, the business logic and the user interface. At the same time, there is some sort of a loose coupling between these elements.

  • Model – The model is responsible for the encapsulation of the application data and mainly consists of Java objects.
  • View – This part is meant for presenting the model data and so, it is made up of the HTML data which the browser can interpret.
  • Controller – The controller processes user requests and builds up the required models. These are then passed on to the view for rendering purpose.

Following image shows the Spring MVC workflow.

Figure 1. Spring MVC workflow

Spring Tool Suite (STS)

For the development of Spring projects, one can make use of Eclipse or IntelliJ IDE. However, Spring Tool Suite, which is an IDE based on Eclipse, come with several features besides being well-optimized for Spring-based applications.

The Spring Tool Suite can be easily downloaded from the IDE’s official download page http://spring.io/tools/sts/all. One can simply install it after downloading.

Note – If you do not prefer the use of Spring Tool Suite but want to get its facilities in Eclipse, you can install the STS plug-in from the Eclipse Marketplace. Also, if you do not wish to use the SpringSource server, you can use any other Java EE container like JBoss or Tomcat, and deploy the application in it.

Now that we have gotten the server and the IDE ready, we shall go ahead and create a Spring MVC project.

Creation of Spring application in Spring Tool Suite or Eclipse

From the File option in the Menu Bar, select New and then Spring Project.

In the new project window, give a name to the project and then for the template, choose Spring MVC Project. When you use this template for the first time, STS downloads it from the SpringSource website. From then on it can be used in any project.

Once the template has been downloaded, you will be required to provide the name for the top-level package. This is then used as the base package for the Spring components.

The project is hen created by the Spring MVC template.

Now, if you happen to see some errors after your project hasn’t compiled, you will need to run Maven/UpdateProject. When doing this, do not forget to tick the option “Force update of Snapshots/Releases”.

The dependencies used in the above code are –

  • Spring-content: This is the Spring Core dependency.
  • Spring-webmvc: This is the Spring MVC for artifact support.
  • Aspectjrt: Reference for AspectJ API
  • Log4J or SLF4J: WWe need these for logging purposes.
  • Java.inject: This is meant for dependency injection.

Now, we will look at the different components of the application one by one. Let’s start with the Log4J configuration.

Configuring Log4J

Listing 1. Sample log.xml file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration PUBLIC "-//APACHE//DTD LOG4J 1.2//EN" "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
       <!-- Appenders -->
       <appender name="console" class="org.apache.log4j.ConsoleAppender">
             <param name="Target" value="System.out" />
             <layout class="org.apache.log4j.PatternLayout">
                    <param name="ConversionPattern" value="%-5p: %c - %m%n" />
             </layout>
       </appender>  
       <!-- Application Loggers -->
       <logger name="example.spring">
             <level value="info" />
       </logger>    
       <!-- 3rdparty Loggers -->
       <logger name="org.springframework.core">
             <level value="info" />
       </logger>    
       <logger name="org.springframework.beans">
             <level value="info" />
       </logger>    
       <logger name="org.springframework.context">
             <level value="info" />
       </logger>
       <logger name="org.springframework.web">
             <level value="info" />
       </logger>
 
       <!-- Root Logger -->
       <root>
             <priority value="warn" />
             <appender-ref ref="console" />
       </root>      
</log4j:configuration>

Note that everything here is printed to the console. This can easily be changed. Adding appenders will redirect the logging to the files.

Configuration of Deployment Descriptor

Listing 2. Sample web.xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
       <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
       <context-param>
             <param-name>contextConfigurationLoc</param-name>
             <param-value>/WEB-INF/spring/rootcont.xml</param-value>
       </context-param>    
       <!—This creates the Spring Container shared by all Servlets and Filters -->
       <listener>
             <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
       </listener>
       <!-- Processes application requests -->
       <servlet>
             <servlet-name>applicationservlet</servlet-name>
             <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
             <init-param>
                    <param-name>contextConfigurationLoc</param-name>
                    <param-value>/WEB-INF/spring/appServlet/servletcont.xml</param-value>
             </init-param>
             <load-on-startup>1</load-on-startup>
       </servlet>          
       <servlet-mapping>
             <servlet-name>applicationservlet</servlet-name>
             <url-pattern>/</url-pattern>
       </servlet-mapping>
</web-app> 

The ContextLoaderListener is responsible for tying the ApplicationContext to the ServletContext and then automate the creation of the former.

DispatcherServlet is the class of controller for SpringMVC applications and all client requests are handled by it.

Files for configuration

Listing 3. Sample rootcont.xml file

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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.xsd">     
       <!-- Root Context: defines shared resources visible to all other web components -->    
</beans> 

The shared beans can be defined here.

Listing 4. Code for servletcont.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:beans="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
             http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
             http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
       <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->  
       <!-- Enables the Spring MVC @Controller programming model -->
       <annotation-driven />
       <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
       <resources mapping="/resources/**" location="/resources/" />
       <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
       <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
             <beans:property name="prefix" value="/WEB-INF/views/" />
             <beans:property name="suffix" value=".jsp" />
       </beans:bean> 
       <context:component-scan base-package="com.journaldev.spring" />    
       </beans:beans> 

The standard Spring configuration looks pretty much like this.

The Controller Class

HomeController is automatically created for the home() method.

Listing 5. Sample Controller classes

package example.spring;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
 * Handling of requests for the application home page.
 */
@Controller
public class HomeController {     
       private static final Logger logger = LoggerFactory.getLogger(HomeController.class);    
       /**
        * Simply selects the home view to render by returning its name.
        */
       @RequestMapping(value = "/", method = RequestMethod.GET)
       public String home(Locale local, Model mode) {
             logger.info("Welcome! The client locale is {}.", local);           
             Date dat = new Date();
             DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, local);          
             String formattedDate = dateFormat.format(dat);        
             mode.addAttribute("serverTime", formattedDate );
             return "home";
       }      
       @RequestMapping(value = "/login", method = RequestMethod.GET)
       public String loginPage(Locale local, Model mode) {
             return "login";
       }      
       @RequestMapping(value = "/home", method = RequestMethod.POST)
       public String login(@Validated User user, Model mode) {
             model.addAttribute("userName", user.getusername());
             return "user";
       }
} 

The @Controller annotation is fore the indication of a web controller class.

The @RequestMapping is being used with methods and classes for the specific handler methods.

The login() method is called with the HTTP method as POST and thus expects data. Likewise, it is also marked for validation with @Validation.

The Model Classes

Model classes are largely meant for holding form variables.

Listing 6. Sample Model classes

package example.spring;
public class User {
       private String user_name;
       public String getusername() {
             return user_name;
       }
       public void setusername(String user_name) {
             this.user_name = user_name;
       }      
}

The View Pages

There are three JSP pages here.

Listing 7. Sample home.jsp file

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
       <title>Home</title>
</head>
<body>
<h1>
       Hello to the world!  
</h1>
<P>  The time on the server is ${serverTime}. </p>
</body>
</html>

Listing 8. Sample login.jsp file

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>The Login Page</title>
</head>
<body>
<form action="home" method="post">
<input type="text" name="user_name"><br>
<input type="submit" value="Login">
</form>
</body>
</html>

This simple JSP page accepts username as input from the user. The form action is home and the method is post, so the login() method of the HomeController will handle this request.

Listing 9. Sample user.jsp file

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>User Home Page</title>
</head>
<body>
<h3>Hello ${user_name}</h3>
</body>
</html>

This is a very simple home page for the user where we have just displayed the name entered.

Conclusion

Seeing this tutorial, you must have learnt how easy it is for developers to use Spring MVC and develop applications for businesses. It is particularly lightweight in nature and much of the configuration is taken over by Spring itself, thus making it hassle-free for the coder.



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

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