본문 바로가기

DevOps/Project management

Simple Spring 4 MVC Hello world Example with gradle

This tutorial shows Spring 4 Hello world example using Spring Annotation (aka javaConfig) configuration, explains Spring 4 basic concepts & usage. We will be creating a Gradle based project using Spring 4.0.0.RELEASE. Let’s get started.


Following technologies being used: 



Following will be the final project directory structure for this example:


Step 1: Provide Spring dependencies in Gradle build.gradle 

Being a gradle based project, we will provide all required dependencies via Gradle build.gradle.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
group 'com.gradle.test'
version '1.0-SNAPSHOT'
 
apply plugin: 'java'
apply plugin: 'war'
 
repositories {
    mavenCentral()
}
 
dependencies {
    compile 'org.springframework:spring-webmvc:4.0.0.RELEASE'
}
 
cs



Step 2: Add Controller and View 

Add a package under src/main/java. Then create a Controller class(shown below) which simply adds a string into model which will be accessible to the view for our example.


com.plalab.controller.HelloController

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.plalab.controller;
 
import com.plalab.service.HelloWorldService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
 
import java.util.Map;
 
@Controller
public class HelloController {
 
    private final HelloWorldService helloWorldService;
 
    @Autowired
    public HelloController(HelloWorldService helloWorldService) {
        this.helloWorldService = helloWorldService;
    }
 
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(Map<String, Object> model) {
 
 
        model.put("title", helloWorldService.getTitle(""));
        model.put("msg", helloWorldService.getDesc());
 
        return "hello";
    }
 
    @RequestMapping(value = "/hello/{name:.+}", method = RequestMethod.GET)
    public ModelAndView hello(@PathVariable("name"String name) {
 
 
        ModelAndView model = new ModelAndView();
        model.setViewName("hello");
 
        model.addObject("name", helloWorldService.getTitle(name));
        model.addObject("msg", helloWorldService.getDesc());
 
        return model;
 
    }
 
}
cs


Create a new folder named views under WEB-INF and add in a Simple JSP page hello.jsp ( WEB-INF/jsp/hello.jsp) which in our example will simply access the model value sent from controller.


hello.jsp

1
2
3
4
5
6
7
8
9
10
<!DOCTYPE HTML>
<html>
<head>
    <title>Sample Application</title>
</head>
<body>
<h1>Hello, ${name}!</h1>
<h2>${msg}!</h2>
</body>
</html>
cs



Step 3: Create Spring configuration file 

Spring configuration file contains instructions for Spring to operate. Let’s create a file named spring-servlet.xml with below content in WEB-INF folder. Note that you can name this file anything you like but be sure to declare it in web.xml.


spring-servlet.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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-4.0.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
 
    <context:component-scan base-package="com.plalab" />
 
    <mvc:annotation-driven />
 
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/jsp/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
 
</beans>
cs



Step 4: Update web configuration (web.xml) file

Things to take from here are DispatcherServlet & contextConfigLocation. DispatcherServlet is the front controller which receives each request(see the url pattern) and direct the request to appropriate controller. It is also responsible for directing the response from controller to appropriate views. Look carefully at contextConfigLocation init-param. Thanks to this parameter, you can name your spring configuration file anything you want and place anywhere you want, even you can provide multiple files. In absence of this parameter, you are obliged to name the file as ABC-servlet.xml where ABC is the dispatcher servlet name.


web.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<web-app id="WebApp_ID" version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 
    <display-name>Spring Mvc Simple Gradle</display-name>
 
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
 
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
 
 
</web-app>
cs



Step 5: Build & Deploy & Run

Gradle -> Build then build the project automatically.


Run -> Edit Configuration then set project like below screenshot.(Choose your tomcat and add Artifact)

Let's run~


Step 6: Check your web application

http://localhost:8080



http://localhost:8080/hello/wonyoung


End of Document


반응형