Programming     Travel Logs     Life Is Good     Surfing Online     About Me
When specific knowledge is taught, it’s through apprenticeships, not schools.
-Naval Ravikant
2018-05-12 16:35:27

Copy this link when reproducing:
http://www.casperlee.com/en/y/blog/88

To learn the Spring MVC framework, I'm going to create a web application named "Today in History", which has only one web page and it will display what happened today in history, such as historical facts, events, famous birthdays, world history, etc.

As usual, let's take it easy and enjoy some beautiful photos first.

/Images/20170905/01.jpg

/Images/20170905/02.jpg

/Images/20170905/03.jpg

/Images/20170905/04.jpg

/Images/20170905/05.jpg

Let's start.

 

Setup the Development Environment for Spring MVC

1. Make sure JDK, Tomcat server, and Eclipse have been installed to the computer and configured properly. Please see http://www.casperlee.com/x/y/blog/78 for detail steps.

2. Download Spring framework.

    I. Open a web browser and navigate to http://projects.spring.io/spring-framework/#quick-start

/Images/20170905/06.jpg

    II. Scroll to the "Quick Start" section, you will find the recommended way to download the spring framework.

    III. Use maven project and the following dependencies to download Spring framework and other related libraries:

<dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context</artifactId>
         <version>4.3.10.RELEASE</version>
     </dependency>
     <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-webmvc</artifactId>
         <version>4.3.10.RELEASE</version>
     </dependency>

FYI: Check the link http://www.casperlee.com/x/y/blog/82 for more information about using Maven project to download libraries.

3. Create the "Today in History" project.

    I. Select "File -> New -> Project..." from the main menu.

/Images/20170905/15.jpg

    II. Select "Web -> Dynamic Web Project", and click "Next >" to continue.

/Images/20170905/16.jpg

    III: Type in the Project name and click "Next >" to continue.

/Images/20170905/17.jpg

    IV: Click "Next >" to continue.

/Images/20170905/18.jpg

    V. Tick "Generate web.xml deployment descriptor" and click "Finish", a new project will be created.

    VI. Right click on the project, select "Properties" on the popped menu.

/Images/20170905/19.jpg

    VII. Switch to "Java Build Path" tab, change the "Default output folder" to the ".../WEB-INF/classes" directory, and click "Apply and Close" to save the settings.

4. Copy the following .jar files into the "WebContent\WEB-INF\lib" folder:

    commons-logging-1.2.jar
    spring-aop-4.3.10.RELEASE.jar
    spring-beans-4.3.10.RELEASE.jar
    spring-context-4.3.10.RELEASE.jar
    spring-core-4.3.10.RELEASE.jar
    spring-expression-4.3.10.RELEASE.jar
    spring-web-4.3.10.RELEASE.jar
    spring-webmvc-4.3.10.RELEASE.jar

5. Right click on the project, select "Refresh" from the popped menu to refresh the project.

6. Input the following lines into "web.xml" to indicate that:
    I.  we want to use the built-in servlet "org.springframework.web.servlet.DispatcherServlet".
    II. The configuration file for the DispatcherServlet is located in "WEB-INF/config" folder and named "springmvc-config.xml".
    III. All the requests will be mapped to this servlet. (<url-pattern>/</url-pattern>)

<servlet>
         <servlet-name>springmvc</servlet-name>
         <servlet-class>
             org.springframework.web.servlet.DispatcherServlet
         </servlet-class>
 	    <init-param>
 			<param-name>contextConfigLocation</param-name>
 			<param-value>/WEB-INF/config/springmvc-config.xml</param-value>
 		</init-param>
         <load-on-startup>1</load-on-startup>    
 	</servlet>
 
     <servlet-mapping>
         <servlet-name>springmvc</servlet-name>
         <url-pattern>/</url-pattern>
     </servlet-mapping>

7. Create a folder named "config" in the "WEB-INF" directory, and put into a file named "springmvc-config.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:p="http://www.springframework.org/schema/p"
     xmlns:mvc="http://www.springframework.org/schema/mvc"
     xmlns:context="http://www.springframework.org/schema/context"
     xsi:schemaLocation="
         http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/mvc
         http://www.springframework.org/schema/mvc/spring-mvc.xsd     
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd">
 		
 	<!-- Indicate to scan all controllers in the base-package -->
     <context:component-scan base-package="com.casperlee.today.controller"/>
     <mvc:annotation-driven/>
 	
 	<!-- Indicate these are static resources -->
     <mvc:resources mapping="/css/**" location="/css/"/>
     <mvc:resources mapping="/*.html" location="/"/>
     
     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 	    <!-- With prefix and suffix, we can refer to the view name itself -->
         <property name="prefix" value="/WEB-INF/jsp/"/>
         <property name="suffix" value=".jsp"/>
     </bean>
 </beans>

/Images/20170905/20.jpg

8. Right click on the "Src" item, select "New -> Package" from the popped menu.

/Images/20170905/21.jpg

9. Type in the package name and click "Finish" to create the package.

    Note: the name must be the same to the one in the "springmvc-config.xml".

10. Following the step No. 8 and No. 9, create another packages:

    com.casperlee.today.domain
    com.casperlee.today.service

11. Create a class named "Day" in the package "com.casperlee.today.domain", and put the following source code in:

package com.casperlee.today.domain;
 
 import java.io.Serializable;
 
 public class Day implements Serializable {
 
 	private static final long serialVersionUID = 1978924851058396786L;
 	
 	private int id;
 	private String key;
 	private String name;
 	private String description;
 
 	public Day() {
 		
 	}
 	
 	public int getId() {
 		return id;
 	}
 	public void setId(int id) {
 		this.id = id;
 	}
 	public String getKey() {
 		return key;
 	}
 	public void setKey(String key) {
 		this.key = key;
 	}
 	public String getName() {
 		return name;
 	}
 	public void setName(String name) {
 		this.name = name;
 	}
 	public String getDescription() {
 		return description;
 	}
 	public void setDescription(String description) {
 		this.description = description;
 	}
 }

12.Create an interface named "DayService" in the package "com.casperlee.today.service", and put the following source code in:

package com.casperlee.today.service;
 
 import com.casperlee.today.domain.Day;
 
 public interface DayService {
 
 	Day GetByKey(String aKey);
 }

13. Create another class named "DayServiceImpl" in the package "com.casperlee.today.service", and put the following source code in:

package com.casperlee.today.service;
 
 import org.springframework.stereotype.Service;
 
 import com.casperlee.today.domain.Day;
 
 @Service
 public class DayServiceImpl implements DayService {
 
 	@Override
 	public Day GetByKey(String aKey) {
 
         Day day = new Day();
         day.setId(1);
         day.setKey(aKey);
         day.setDescription("A good day!");
 		return day;
 	}
 }

14. Put the following text into the "springmvc-config.xml":

<context:component-scan base-package="com.casperlee.today.service"/>

15. Create a class named "DayController" in the package "com.casperlee.today.controller", and put the following source code in:

package com.casperlee.today.controller;
 
 import java.text.SimpleDateFormat;
 import java.util.Date;
 
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Controller;
 import org.springframework.ui.Model;
 import org.springframework.web.bind.annotation.RequestMapping;
 
 import com.casperlee.today.domain.Day;
 import com.casperlee.today.service.DayService;
 
 @Controller
 public class DayController {
 
 	@Autowired
     private DayService dayService;
 	
 	@RequestMapping(value = "/")
 	public String Index(Model model) {
 		
 	    Date today = new Date();
 	    SimpleDateFormat format = new SimpleDateFormat("MMdd");
 	    String key = format.format(today);
 	    Day day = dayService.GetByKey(key);
 	    model.addAttribute(day);
 	    return "DayForm";
 	}
 }

16. Create a folder named "jsp" in the "WebContent/WEB-INF" folder, and create a .jsp file named "DayForm.jsp" in the "jsp" folder which was just created. Here is the content of "DayForm.jsp":

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 <!DOCTYPE HTML>
 <html>
 <head>
 <title>Today in History</title>
 </head>
 <body>
 
 <div>
 ${day.id}
 </div>
 <div>
 ${day.name}
 </div>
 <div>
 ${day.description}
 </div>
 </body>
 </html>

17. Oops! Encountered an error in this jsp file: "Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"".

18. Fix the error.

    I. Following the instruction in the step No. 1, use maven to download the "jstl" library. Here is the dependency you need to put into "pom.xml":

<dependency>
       <groupId>javax.servlet</groupId>
       <artifactId>jstl</artifactId>
       <version>1.2</version>
     </dependency>

    II. Copy the downloaded library file "jstl-1.2.jar" into the "WebContent/WEB-INF/lib" folder, and refresh the project.

    III. It works! The error message disappeared.

19. Right click on the project, select "Run as -> Run on Server" from the popped menu.

/Images/20170905/22.jpg

20. Done! It works!