Creating a spring MVC project using Gradle

Keywords: Java Spring mvc

1. New Grande project

Click file - > New - > project, create a new project, select Gradle, check Java and Web as shown in the figure below, and click Next to proceed to the Next step

Set the name of the project. In this case, it is called gradle_mvc

Click Finish to complete the setting, and the project starts to be created, waiting for the project to be created.

2. Add dependency

Edit the build.gradle file and add the dependency of spring webmvc in dependencies:

implementation 'org.springframework:spring-webmvc:5.3.10'

Save and click Reload in the Gradle panel to Reload the dependency. Finally, you can see the dependency as shown in the figure.

3. Add mvc related files

The document structure is as follows:

① First add a Controller:

package cn.flylolo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author FlyLolo
 * @date 2021/10/9 16:42
 */
@RestController
@RequestMapping("user")
public class UserController {
    @GetMapping("")
    public String helloWorld(){
        return "Hello World!";
    }
}

② Create a new springmvc.xml file in the resources directory:

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

    <context:component-scan base-package="cn.flylolo"/>
    <mvc:annotation-driven />
    <mvc:default-servlet-handler />
</beans>

③ Create a new WEB-INF folder under the webapp directory, where a new web.xml file is created:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         id="WebApp_ID" version="3.0">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:springmvc.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!--to configure springmvc core servlet-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.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>
</web-app>

4. Project setting

Open file - > Project struts settings,

Select the with "expanded" suffix and modify the contents in the box in the figure:

The Name is relatively long and can be modified or not. In this example, it is changed to gradlemvc

There is a problem with the path automatically generated by the Output directory. Remove "exploded". For example, this example is changed to: F:\gradle_mvc\build\libs\gradle_mvc-1.0-SNAPSHOT.war.

5. Configure Tomcat

Configure Tomcat service, open Run/Debug Configuration, click the plus sign in the upper left corner, and select Tomcat server - > local.

HTTP prot defaults to 8080. If it has been used, it will be changed to another port.

Select artifacts, click the Fix button in the lower right corner, jump to the Deployment tab, and select the gradle MVC just configured.

Save and start the project, access HelloController, address: http://localhost:8081/gradlemvc/user

6. Add json parsing:

It's ok if you just return the String type, but most of the time you need to return the Json type.

Create a new User class:

package cn.flylolo.model;

import lombok.Data;

/**
 * @author FlyLolo
 * @date 2021/10/11 11:18
 */
@Data
public class User {
    private String userId;
    private String userName;
}

lombok is used here. You need to add a reference in build.gradle.

implementation 'org.projectlombok:lombok:1.18.20'
annotationProcessor 'org.projectlombok:lombok:1.18.20'

Note that the second line needs to be added, otherwise an error of "error: no symbol found" will appear when calling the corresponding get and set methods.

Add a new method in UserController:

@GetMapping("/{userId}")
public User getName(@PathVariable String userId){
    User user = new User();
    user.setUserId(userId);
    user.setUserName(userId + "Name of");
    return user;
}

A User object is returned.

visit http://localhost:8081/gradlemvc/user/testid , returned 406, unacceptable error.

Because the Json type is returned, the corresponding message converters need to be added. In this example, FastJson is used. Replace < MVC: annotation driven / > in springmvc.xml with the following code

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="true">
        <!-- to configure Fastjson support -->
        <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>application/json</value>
                    <value>text/html;charset=UTF-8</value>
                </list>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

This requires adding a reference to fastjason in build.gradle:

implementation 'com.alibaba:fastjson:1.2.78'

Visit again http://localhost:8081/gradlemvc/user/testid , the expected results are obtained.

7. Project GitHub address

https://github.com/FlyLolo/JavaSimple/tree/main/src/gradle_mvc

Posted by BenInBlack on Mon, 11 Oct 2021 21:25:58 -0700