Spring MVC配置JSP及配置thymeleaf

版权声明:本文为博主原创文章,转载需注明出处。 https://blog.csdn.net/jay100500/article/details/84844260

作者:谭东

环境为:IntelliJ Idea 2018.3版本

目前都是使用更加方便的Spring boot进行开发后端了,因为不用像Spring MVC这样配置很多的配置文件了。但是学习Spring MVC的常用配置,有助于我们更好的理解Spring boot为我们做了哪些免配置工作,有利于我们更好的拓展学习。那么我就把自己整理的教程步骤分享下。

1、新建项目。使用Maven构建新建项目。

一直下一步,新建后的结构如下:

2、配置Tomcat及完善目录结构。

在WEB-INF文件夹下新建两个xml配置文件,一个是applicationContext.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 http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="com.web.mvc"/>
</beans>

一个是dispatcher-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"
       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">
    <!--此文件负责整个mvc中的配置-->
    <!-- 自动扫描装配,开启组件扫描,请确保所有的控制器都在基本包下,并且不要制定一个太宽泛的基本包 -->
    <context:component-scan base-package="com.web.mvc"/>
    <!--启用spring的一些annotation -->
    <context:annotation-config/>
    <!-- 配置注解驱动 可以将request参数与绑定到controller参数上 -->
    <mvc:annotation-driven/>
    <mvc:default-servlet-handler/>
    <!--静态资源映射-->
    <mvc:resources mapping="/statics/**" location="/statics/"/>
    <!-- 模型视图视图解析器- -->
    <bean id="defaultViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/views/"/><!--设置JSP文件的目录位置-->
        <property name="suffix" value=".jsp"/>
        <property name="exposeContextBeansAsAttributes" value="true"/>
    </bean>

</beans>

配置完善web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

  <display-name>Archetype Created Web Application</display-name>

  <!--welcome pages-->
  <welcome-file-list>
    <welcome-file>/views/view/index.jsp</welcome-file>
    <!--<welcome-file>/statics/html/page.html</welcome-file>-->
  </welcome-file-list>

  <!--配置springmvc DispatcherServlet-->
  <servlet>
    <servlet-name>springMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <!--配置dispatcher.xml作为mvc的配置文件-->
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    <async-supported>true</async-supported>
  </servlet>
  <servlet-mapping>
    <servlet-name>springMVC</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <!--把applicationContext.xml加入到配置文件中-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
</web-app>

接下来完善pom.xml,引入相关包文件,我们这里把后面要用到的thymeleaf也引入了:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.web.mvc</groupId>
    <artifactId>SpringMVC</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>SpringMVC Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
        <spring.version>4.3.3.RELEASE</spring.version>
        <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <!--J2EE-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!--springframework-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring4</artifactId>
            <version>${thymeleaf.version}</version>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf</artifactId>
            <version>${thymeleaf.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>SpringMVC</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.0.0</version>
                </plugin>
                <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.7.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.20.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

完善目录结构后如图:

接下来配置下相关文件夹,如源码文件夹,和资源文件夹:

通过以上配置就可以访问我们的index.jsp了。

我们再写个Controller,通过Controller访问index.jsp页面。

package com.web.mvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/p")
public class BaseController {
    @RequestMapping("/getPage")
    public String getPage(Model model) {
        return "view/index";
    }
}

运行后,通过Controller地址访问:

那么我们配置Spring MVC与JSP页面就完成了。

接下来,我们配置下Spring MVC与thymeleaf模板引擎。这是如果使用thymeleaf模板引擎就要把jsp的模型视图解析器配置注视掉。

修改dispatcher-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"
       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">
    <!--此文件负责整个mvc中的配置-->
    <!-- 自动扫描装配,开启组件扫描,请确保所有的控制器都在基本包下,并且不要制定一个太宽泛的基本包 -->
    <context:component-scan base-package="com.web.mvc"/>
    <!--启用spring的一些annotation -->
    <context:annotation-config/>
    <!-- 配置注解驱动 可以将request参数与绑定到controller参数上 -->
    <mvc:annotation-driven/>
    <mvc:default-servlet-handler/>
    <!--静态资源映射-->
    <mvc:resources mapping="/statics/**" location="/statics/"/>
    <!-- 模型视图视图解析器- -->
    <!--<bean id="defaultViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">-->
    <!--<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>-->
    <!--<property name="prefix" value="/views/"/>&lt;!&ndash;设置JSP文件的目录位置&ndash;&gt;-->
    <!--<property name="suffix" value=".jsp"/>-->
    <!--<property name="exposeContextBeansAsAttributes" value="true"/>-->
    <!--</bean>-->
    <!-- 模板解析器  -->
    <bean id="templateResolver"
          class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
        <property name="prefix" value="/statics/html/"/>
        <property name="suffix" value=".html"/>
        <property name="templateMode" value="HTML"/>
        <property name="cacheable" value="true"/>
        <property name="characterEncoding" value="UTF-8"/>
    </bean>

    <bean id="templateEngine"
          class="org.thymeleaf.spring4.SpringTemplateEngine">
        <property name="templateResolver" ref="templateResolver"/>
        <property name="enableSpringELCompiler" value="true"/>
    </bean>

    <bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
        <property name="templateEngine" ref="templateEngine"/>
        <property name="characterEncoding" value="UTF-8"/>
        <property name="order" value="1"/>
        <!--<property name="viewNames" value="*.html,*.xhtml"/>-->
    </bean>
</beans>

编写我们的page.html文件:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8"></meta>
    <title>Insert title here</title>
</head>
<body>
<span th:text="'Hello, '+${text}"></span>
</body>
</html>

修改编写Controller:

package com.web.mvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/p")
public class BaseController {
    @RequestMapping("/getPage")
    public String getPage(Model model) {
        return "view/index";
    }

    @RequestMapping(value = "/page", method = RequestMethod.GET)
    public String page(Model model) {
        model.addAttribute("text", "This is MyTest page with Thymeleaf!");
        return "page";//return "page.html"需要配置<!--<property name="suffix" value=".html"/>--> ,<property name="viewNames" value="*.html,*.xhtml"/>
    }
}

然后运行:

这样,Spring MVC和thymeleaf就配置好了。

如果想实现thymeleaf和jsp双模板引擎的话,dispatcher-servlet.xml部分内容修改为这样:

<!-- 双模板引擎 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="viewNames" value="*.jsp"/>
    </bean>

    <bean id="templateResolver" class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
        <property name="prefix" value="/WEB-INF/thymeleaf/"/>
        <property name="templateMode" value="HTML5"/>
        <property name="characterEncoding" value="utf-8"/>
    </bean>
    <bean id="templateEngine" class="org.thymeleaf.spring3.SpringTemplateEngine">
        <property name="templateResolver" ref="templateResolver"/>
    </bean>
    <bean class="org.thymeleaf.spring3.view.ThymeleafViewResolver">
        <property name="templateEngine" ref="templateEngine"/>
        <property name="viewNames" value="*.html"/>
        <property name="characterEncoding" value="utf-8"/>
    </bean>

关键地方:

<property name="viewNames" value="*.jsp"/>
<property name="viewNames" value="*.html"/>

而不是原来的:

<property name="suffix" value=".jsp"/>

还有一点需要注意的是:

这句话如果不注释的话,那么下图这句就要注释掉:

然后Controller的return写法也要修改下,从原来的:

return "page";

改为:

return "page.html";

项目Github地址为:https://github.com/jaychou2012/SpringMVC

猜你喜欢

转载自blog.csdn.net/jay100500/article/details/84844260
今日推荐