创建springmvc.xml

本文详细介绍了如何创建并配置Spring MVC的springmvc.xml文件,包括导入头文件、设置Handler注解扫描、配置注解映射器和适配器、定义视图解析器以及配置静态资源的步骤。
摘要由CSDN通过智能技术生成

1,创建srpingmvc.xml导入头文件

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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">
<beans>

2,配置Handler注解扫描

<!-- 扫描controller -->
    <context:component-scan base-package="com.sxt.controller"></context:component-scan>

3,配置注解映射器和适配器

<!--注解映射器
1. 首先,在Spring配置文件中添加Thymeleaf依赖: ```xml <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> <version>3.0.11.RELEASE</version> </dependency> ``` 2. 然后,在Spring MVC配置文件中配置Thymeleaf视图解析器: ```xml <!-- 配置Thymeleaf视图解析器 --> <bean id="templateResolver" class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver"> <property name="prefix" value="/WEB-INF/views/" /> <property name="suffix" value=".html" /> <property name="templateMode" value="HTML" /> </bean> <bean id="templateEngine" class="org.thymeleaf.spring5.SpringTemplateEngine"> <property name="templateResolver" ref="templateResolver" /> <property name="enableSpringELCompiler" value="true" /> </bean> <bean class="org.thymeleaf.spring5.view.ThymeleafViewResolver"> <property name="templateEngine" ref="templateEngine" /> <property name="characterEncoding" value="UTF-8" /> </bean> ``` 在上面的配置中,我们定义了一个Thymeleaf的模板解析器(templateResolver),用于解析模板文件。我们指定了模板文件的前缀和后缀,以及模板文件的类型(HTML)。接着,我们创建一个Thymeleaf的模板引擎(templateEngine),并将模板解析器注入到该引擎中。最后,我们定义了一个Thymeleaf的视图解析器(ThymeleafViewResolver),并将模板引擎注入到该解析器中。 3. 在Controller中返回Thymeleaf视图: ```java @RequestMapping("/hello") public String hello(Model model) { model.addAttribute("name", "Thymeleaf"); return "hello"; } ``` 在上面的Controller中,我们使用Model对象将一个名为“name”的属性值设置为“Thymeleaf”,并将视图名设置为“hello”。由于我们在Spring MVC配置文件中配置了Thymeleaf视图解析器,因此,Spring会自动将该视图名解析成“/WEB-INF/views/hello.html”文件,并将模板文件中的变量替换成具体的值,最终生成HTML页面。 4. 在Thymeleaf模板文件中使用变量: ```html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Hello Thymeleaf</title> </head> <body> <h1>Hello, <span th:text="${name}"></span>!</h1> </body> </html> ``` 在上面的模板文件中,我们使用了Thymeleaf的语法,在页面中输出了变量“name”的值。在Thymeleaf中,我们可以使用“${变量名}”的语法来输出变量的值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值