【JAVAEE框架】SpringMVC 项目起步讲解(二)

举报
追zhui 发表于 2025/11/13 20:40:54 2025/11/13
【摘要】 ### SpringMVC 页面传值ModelAndView 详解前面写到,当控制器处理完请求时,通常会将包含视图名称或视图对象以及一些模型属性的ModelAndView对象返回到DispatcherServlet。ModelAndView 当中包含了一个model属性和一个view属性,model其实是一个 ModelMap 类型,它是一个LinkedHashMap的子类,view包含了一...
### SpringMVC 页面传值



ModelAndView 详解

前面写到,当控制器处理完请求时,通常会将包含视图名称或视图对象以及一些模型属性的ModelAndView对象返回到DispatcherServlet。

ModelAndView 当中包含了一个model属性和一个view属性,model其实是一个 ModelMap 类型,它是一个LinkedHashMap的子类,view包含了一些视图信息。

如何使用?

ModelAndView  通过 **setViewName**方法来实现跳转的页面。

eg:跳转的页面 mv.setViewName("user/userInfo"); 就是跳转到 user的userInfo页面

addObject

addObject 该方法用于设置【前端页面要显示的数据是什么】;该方法的参数:可以是任何一个有效的Java对象;该方法默认把对象,存放在当前请求中的;

通过设置键值对的方式来实现传给页面的值。

eg:

```html
<body class="login_bg">
    <section class="loginBox">
        <header class="loginHeader">
            <h1>超市订单管理系统</h1>
        </header>
        <section class="loginCont">
        <form class="loginForm" action="${pageContext.request.contextPath }/user/login"  name="actionForm" id="actionForm"  method="post" >
<div class="info">${error }</div>
<div class="inputbox">
                    <label for="user">用户名:</label>
<input type="text" class="input-text" id="userCode" name="usercode" placeholder="请输入用户名" required/>
</div>
<div class="inputbox">
                    <label for="mima">密码:</label>
                    <input type="password" id="userPassword" name="userpassword" placeholder="请输入密码" required/>
                </div>
<div class="subBtn">

                    <input type="submit" value="登录"/>
                    <input type="reset" value="重置"/>
                </div>
</form>
        </section>
    </section>
</body>
```

该页面是超市管理系统的登录页面,看 input 里面的name属性,用户名的name属性是usercode,那么addObject传值是 mv.addObject(“usercode”,xxx)来传值,`注:记得大小写一定要对上`



Servlet重定向forward与redirect

使用servlet重定向有两种方式,一种是forward,另一种就是redirect。forward是服务器内部重定向,客户端并不知道服务器把你当前请求重定向到哪里去了,地址栏的url与你之前访问的url保持不变。redirect则是客户端重定向,是服务器将你当前请求返回,然后给个状态标示给你,告诉你应该去重新请求另外一个url,具体表现就是地址栏的url变成了新的url。

eg:

```java
ModelAndView mv = new ModelAndView("/user/save/result");//默认为forward模式  

ModelAndView mv = new ModelAndView("redirect:/user/save/result");//redirect模式  
```



Model

Model 作用: 作为数据流转的载体,相当于前端的一个数据库,就好比后端中的user实体类所对应的数据库User,
从Model中获取数据比从后端的User实体类中获取数据更加方便。

![img](https://img-blog.csdnimg.cn/20210518101803367.png)

如图,这是一个简单的实例,简单展示一下Model是怎么存储数据然后展示到前段页面的。



控制层

```java
@Controller
// 在Spring MVC 中使用 @RequestMapping 来映射请求,也就是通过它来指定控制器可以处理哪些URL请求,相当于Servlet中在web.xml中配置
@RequestMapping("/user")
public class UserAction {

    @RequestMapping("/test04")
    public String test02(Model model){

        User user = new User("Lucy","123456",18);
        // return "userInfo";
        System.out.println(user);
        model.addAttribute("user",user);
        return "userDetail";
    }
}
```

前台页面

```html
<html>
<head>
    <title>Title</title>
</head>
<body>

    <h1>用户详情页</h1>
    <h1>姓名:${user.username}</h1>
    <h1>密码:${user.password}</h1>
    <h1>年龄:${user.age}</h1>

</body>
</html>

```



访问地址

http://localhost:8080/day09_SpringMvc01/user/test04

效果

![image-20220927151829445](C:\Users\小熊\AppData\Roaming\Typora\typora-user-images\image-20220927151829445.png)

如果使用 HttpServletRequest 或 HttpSession 来传数据呢?



```java
    @RequestMapping("/test05")
    public String test03(User user, Model model, HttpServletRequest request, HttpSession session){
        user = new User("Lucy","123456",18);
        // return "userInfo";

        // user放入Session
        // 用到ServletAPI
        request.setAttribute("requestKey","requestValue");
        session.setAttribute("sessionKey","sessionValue");

        model.addAttribute("user",user);
        return "userDetail";
    }
```



前台页面

```html
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>用户信息页面</h1>
    姓名:${user.name} <br>
    年龄:${user.age} <br>
    requestValue:${requestKey} <br>
    sessionValue:${sessionKey} <br>
</body>
</html>
```



springMVC.xml 配置说明

```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-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
">

<!--    spring注解-->
<!--    作用:扫描包内及其子包内的所有“类”(不包含接口),并为添加了@Service、@Component、@Controller、@Repository修饰的类创建对象并存入IOC容器-->
<!--    @Service、@Component、@Controller、@Repository修饰的类中含有@Autowired修饰的成员变量,则创建对象时会从IOC容器中取值为该成员变量赋值-->
    <context:component-scan base-package="com.itxzw">
        <context:exclude-filter type="regex" expression="com.itxzw.util"/>
    </context:component-scan>

    <!--SpringMVC相关配置-->
    <!--视图解析器,他的作用是在Controller返回的时候进行解析视图-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/"/>
        <property name="suffix" value=".jsp" />
    </bean>

    <!--启动SpringMVC注解-->
<!--    主要用于spring mvc 中的annotation注解功能,作用是帮我们注入一些内置bean,例如RequestMappingHandlerMapping
        和 RequestMappingHandlerAdapter等,这些类是Aware的子类,能完成特定的供能,例如:
        RequestMappingHandlerMapping负责解析@RequestMapping("/helloworld")注解。
        主要是解析spring mvc的一些标签和语法!
-->
    <mvc:annotation-driven />
<!--    <mvc:default-servlet-handler/>-->
</beans>
```

web.xml 配置说明

```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_4_0.xsd"
         version="4.0">

  <servlet>
    <servlet-name>dispatcherServlet</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>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>


</web-app>
```





主要理解 DispatcherServlet 的流程理解,控制层传前台可以理解为使用了类似于键值对的方式进行获取值的。



thymeleaf 的用法

Thymeleaf 是新一代 Java 模板引擎,与 Velocity、FreeMarker 等传统 Java 模板引擎不同,Thymeleaf 支持 HTML 原型,其文件后缀为“.html”,因此它可以直接被浏览器打开,此时浏览器会忽略未定义的 Thymeleaf 标签属性,展示 thymeleaf 模板的静态页面效果;当通过 Web 应用程序访问时,Thymeleaf 会动态地替换掉静态内容,使页面动态显示。

使用它,需要在 html 标签中,增加额外属性来达到 “模板+数据” 的展示方式,示例代码如下。

```html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--th:text 为 Thymeleaf 属性,用于在展示文本-->
<h1 th:text="迎您来到Thymeleaf">欢迎您访问静态页面 HTML</h1>
</body>
</html>
```

效果

![image-20221014102842074](C:\Users\小熊\AppData\Roaming\Typora\typora-user-images\image-20221014102842074.png)

#### Thymeleaf 的特点

Thymeleaf 模板引擎具有以下特点:

**动静结合:**Thymeleaf 既可以直接使用浏览器打开,查看页面的静态效果,也可以通过 Web 应用程序进行访问,查看动态页面效果。

**开箱即用:**Thymeleaf 提供了 Spring 标准方言以及一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。

**多方言支持:**它提供了 Thymeleaf 标准和 Spring 标准两种方言,可以直接套用模板实现 JSTL、 OGNL 表达式;必要时,开发人员也可以扩展和创建自定义的方言。

**与 SpringBoot 完美整合:**SpringBoot 为 Thymeleaf 提供了的默认配置,并且还为 Thymeleaf 设置了视图解析器,因此 Thymeleaf 可以与 Spring Boot 完美整合。

注:要使用 Thymeleaf  就要在 html  导入额外属性

```html
xmlns:th="http://www.thymeleaf.org"
```

常用的语法

表达式

**变量表达式:**${...}

**选择变量表达式**:*{...}

**链接表达式:**@{...}

**国际化表达式:**#{...}

**片段引用表达式:**~{...}



本人常用的是变量表达式

假设获取 person 对象的 name属性,表达式形式如下:

```java
${person.name}
```



th属性

| 属性        | 描述                                                         | 示例                                                         |
| ----------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| th:id       | 替换 HTML 的 id 属性                                         | `<input  id="html-id"  th:id="thymeleaf-id"  />`             |
| th:text     | 文本替换,转义特殊字符                                       | `<h1 th:text="hello,bianchengbang" >hello</h1>`             |
| th:utext    | 文本替换,不转义特殊字符                                     | `<div th:utext="'<h1>欢迎来到编程帮!</h1>'" >欢迎你</div>`  |
| th:object   | 在父标签选择对象,子标签使用 *{…} 选择表达式选取值。 没有选择对象,那子标签使用选择表达式和 ${…} 变量表达式是一样的效果。 同时即使选择了对象,子标签仍然可以使用变量表达式。 | `<div th:object="${session.user}" >    <p th:text="*{fisrtName}">firstname</p></div>` |
| th:value    | 替换 value 属性                                              | `<input th:value = "${user.name}" />`                        |
| th:with     | 局部变量赋值运算                                             | `<div th:with="isEvens = ${prodStat.count}%2 == 0"  th:text="${isEvens}"></div>` |
| th:style    | 设置样式                                                     | `<div th:style="'color:#F00; font-weight:bold'">编程帮 www.biancheng.net</div>` |
| th:onclick  | 点击事件                                                     | `<td th:onclick = "'getInfo()'"></td>`                       |
| th:each     | 遍历,支持 Iterable、Map、数组等。                           | `<table>    <tr th:each="m:${session.map}">        <td th:text="${m.getKey()}"></td>        <td th:text="${m.getValue()}"></td>    </tr></table>` |
| th:if       | 根据条件判断是否需要展示此标签                               | `<a th:if ="${userId == collect.userId}">`                   |
| th:unless   | 和 th:if 判断相反,满足条件时不显示                          | ` <div th:unless="${m.getKey()=='name'}" ></div>`            |
| th:switch   | 与 Java 的 switch case语句类似 通常与 th:case 配合使用,根据不同的条件展示不同的内容 | `<div th:switch="${name}">    <span th:case="a">编程帮</span>    <span th:case="b">www.biancheng.net</span></div>` |
| th:fragment | 模板布局,类似 JSP 的 tag,用来定义一段被引用或包含的模板片段 | `<footer th:fragment="footer">插入的内容</footer>`           |
| th:insert   | 布局标签; 将使用 th:fragment 属性指定的模板片段(包含标签)插入到当前标签中。 | `<div th:insert="commons/bar::footer"></div>`                |
| th:replace  | 布局标签; 使用 th:fragment 属性指定的模板片段(包含标签)替换当前整个标签。 | `<div th:replace="commons/bar::footer"></div>`               |
| th:selected | select 选择框选中                                            | `<select>    <option>---</option>    <option th:selected="${name=='a'}">        编程帮    </option>    <option th:selected="${name=='b'}">        www.biancheng.net    </option></select>` |
| th:src      | 替换 HTML 中的 src 属性                                      | `<img  th:src="@{/asserts/img/bootstrap-solid.svg}" src="asserts/img/bootstrap-solid.svg" />` |
| th:inline   | 内联属性; 该属性有 text、none、javascript 三种取值, 在 <script> 标签中使用时,js 代码中可以获取到后台传递页面的对象。 | `<script type="text/javascript" th:inline="javascript">    var name = /*[[${name}]]*/ 'bianchengbang';    alert(name)</script>` |
| th:action   | 替换表单提交地址                                             | `<form th:action="@{/user/login}" th:method="post"></form>`  |



【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。