持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第6天,点击查看活动详情
开发环境
创建maven工程
打包方式改成war,install之后会自动生成web模块
<packaging>war</packaging>
pom依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.22</version>
</dependency>
<!--日志文件-->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<!--ServletAPI-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--Spring5和thymeleaf整合包-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.12.RELEASE</version>
</dependency>
web.xml
url-patten中/和/*的区别:
- /:匹配浏览器向服务器发送的所有请求(不包括.jsp)
- /*:匹配浏览器向服务器发送的所有请求(包括.jsp)
<!--配置SpringMVC的前端控制器DispatcherServlet-->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
创建配置文件
配置文件的命名规则:<servlet-name>+-servlet.xml
SpringMVC-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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<context:component-scan base-package="com.sentiment.controller"></context:component-scan>
<bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
<property name="order" value="1"/>
<property name="characterEncoding" value="UTF-8"/>
<property name="templateEngine">
<bean class="org.thymeleaf.spring5.SpringTemplateEngine">
<property name="templateResolver">
<bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
<property name="prefix" value="/WEB-INF/templates/"/>
<property name="suffix" value=".html"/>
<property name="templateMode" value="HTML5"/>
<property name="characterEncoding" value="UTF-8"/>
</bean>
</property>
</bean>
</property>
</bean>
</beans>
测试HelloWorld
启动一个tomcat环境,默认路径设置为/SpringMVC
@RequestMapping("/"),环境启动后,会默认访问/WEB-INF/templates/下的index.html
@Controller
public class HelloController {
@RequestMapping("/")
public String protal(){
return "index";
}
@RequestMapping("/hello")
public String hello(){
return "success";
}
}
在index设置一个链接,th表示thymeleaf标签需要导入命名空间xmlns:th="http://www.thymeleaf.org"
<a th:href="@{/hello}">测试</a>
此时当点链接"测试"后,thymeleaf会根据当前路径访问/SpringMVC/hello,并且返回success,之后跳转到/WEB-INF/templates/下的success.html中
这里如果用的是如下标签,则会默认访问绝对路径即:localhost:808/hello,故请求错误(404)
<a href="/hello">测试</a>