1.7 基于XML配置方式使用Spring MVC

这篇具有很好参考价值的文章主要介绍了1.7 基于XML配置方式使用Spring MVC。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

一、基于XML配置与注解的方式使用Spring MVC

1、创建Maven项目

Maven项目 - SpringMvcDemo01
1.7 基于XML配置方式使用Spring MVC

单击【Finish】按钮
1.7 基于XML配置方式使用Spring MVC

2、添加相关依赖

在pom.xml文件里添加支持Spring MVC的相关依赖
1.7 基于XML配置方式使用Spring MVC

<?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>net.hf.spring</groupId>
    <artifactId>SpringMvcDemo01</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <!-- spring.version -->
        <spring.version>5.3.25</spring.version>
    </properties>

    <dependencies>
        <!--Spring核心-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--Spring Bean实体-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--Spring容器-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--Spring测试-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--Spring Web功能-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--Spring MVC框架-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!--JSP标准标签库-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!--Servlet -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <!--日志框架-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!--单元测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

3、给项目添加Web功能

打开项目结构窗口,在列表里选择【Modules】
1.7 基于XML配置方式使用Spring MVC

单击【+】按钮,添加Web功能
1.7 基于XML配置方式使用Spring MVC

1.7 基于XML配置方式使用Spring MVC

单击【Create Artifact】按钮,将名称改为“SpringMvcDemo01”

1.7 基于XML配置方式使用Spring MVC

单击【OK】按钮,可以看到项目多了一个web目录

1.7 基于XML配置方式使用Spring MVC

4、创建三个页面

在WEB-INF里创建views子目录(存放JSP页面)
1.7 基于XML配置方式使用Spring MVC

(1)创建登录页面

在views目录里创建登录页面 - login.jsp
1.7 基于XML配置方式使用Spring MVC

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2023/3/14
  Time: 9:08
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>用户登录</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" >
  <script src="js/check.js"></script>
</head>
<body>
<h3 style="text-align: center">用户登录</h3>
<form id="frmLogin" action="login" method="post">
  <table class="tb" border="1" cellpadding="10" style="margin: 0px auto">
    <tr>
      <td align="center">账号</td>
      <td><input id="username" type="text" name="username"/></td>
    </tr>
    <tr>
      <td align="center">密码</td>
      <td><input id="password" type="password" name="password"/></td>
    </tr>
    <tr align="center">
      <td colspan="2">
        <input type="submit" value="登录" onclick="return checkLoginForm()"/>
        <input type="reset" value="重置"/>
      </td>
    </tr>
  </table>
</form>
</body>
</html>

(2)创建登录成功页面

在views目录里创建登录成功页面 - success.jsp
1.7 基于XML配置方式使用Spring MVC

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2023/3/14
  Time: 9:09
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
    <head>
        <title>登录成功</title>
    </head>
    <body>
        <h1>${username},登录成功!</h1>
    </body>
</html>


(3)创建登录失败页面

在views目录里创建登录失败页面 - failure.jsp
1.7 基于XML配置方式使用Spring MVC

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2023/3/14
  Time: 9:11
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
    <head>
        <title>登录失败</title>
    </head>
    <body>
        <h1>${username},登录失败!</h1>
    </body>
</html>


5、创建登录控制器

创建net.hf.spring.controller包,然后在包里创建LoginController类
1.7 基于XML配置方式使用Spring MVC

package net.hf.spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

/**
 * 功能:登录控制器
 * 作者:hf
 * 日期:2023年03月08日
 */
@Controller // 交给Spring容器来管理
public class LoginController {
    @PostMapping("/login")  // 可用@RequestMapping("/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        HttpSession session) {
        // 将登录表单提交的用户名写入会话
        session.setAttribute("username", username);
        // 判断用户是否登录成功
        if (username.equals("hf") && password.equals("123456")) {
            // 返回逻辑视图名success,表明跳转到登录成功页面
            return "success";
        } 
        
        // 返回逻辑视图名failure,表明跳转到登录失败页面
        return "failure"; 
    }
}

6、创建Spring配置文件

在resources里创建mvc子目录,然后在子目录里创建spring-config.xml
1.7 基于XML配置方式使用Spring MVC

<?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 
       https://www.springframework.org/schema/context/spring-context.xsd">

    <!--组件扫描-->
    <context:component-scan base-package="net.hf.spring" />

</beans>

7、创建Spring MVC配置文件

在resources/mvc目录里创建spring-mvc-config.xml
1.7 基于XML配置方式使用Spring MVC

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

    <!--采用注解驱动-->
    <mvc:annotation-driven/>

    <!--扫描控制器-->
    <context:component-scan base-package="net.hf.spring.controller"/>

    <!--定义内部资源视图解析器:负责解析控制器里从逻辑视图到物理页面的映射-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/views/"/> <!--路径-->
        <property name="suffix" value=".jsp"/> <!--扩展名-->
    </bean>
</beans>

8、修改Web部署描述文件

一个Web项目启动时最先要读取web.xml文件
在web/WEB-INF目录里打开web.xml文件
1.7 基于XML配置方式使用Spring MVC

<?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">
    <!--设置启动首页-->
    <welcome-file-list>
        <welcome-file>/WEB-INF/views/login.jsp</welcome-file>
    </welcome-file-list>

    <!--Spring容器加载监听器,让Spring随着Web项目启动而初始化-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!--指定Spring配置文件位置-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:mvc/spring-config.xml</param-value>
    </context-param>

    <!--注册Spring前端控制器,加载Spring MVC配置文件-->
    <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:mvc/spring-mvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup> <!--数字越小,启动级别越高-->
    </servlet>

    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>  <!--/”表明拦截一切请求-->
    </servlet-mapping>

    <!--设置字符编码过滤器-->
    <filter>
        <filter-name>Character Encoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>Character Encoding</filter-name>
        <url-pattern>/*</url-pattern> <!--/*表明过滤一切请求-->
    </filter-mapping>
</web-app>

对应关系图
1.7 基于XML配置方式使用Spring MVC

9、配置Tomcat服务器

单击工具栏上的【Curren File】

1.7 基于XML配置方式使用Spring MVC

弹出【Run/Debug Configurations】窗口
1.7 基于XML配置方式使用Spring MVC

添加本地的Tomcat服务器
1.7 基于XML配置方式使用Spring MVC

对服务器进行设置(配置应用服务器,部署Web项目)
1.7 基于XML配置方式使用Spring MVC

1.7 基于XML配置方式使用Spring MVC

注意项目的URL
1.7 基于XML配置方式使用Spring MVC

单击【OK】按钮
1.7 基于XML配置方式使用Spring MVC

10、添加项目对Tomcat的依赖

打开【Project Structure】窗口,选择Modules对应的Dependencies,单击【+】按钮
1.7 基于XML配置方式使用Spring MVC

添加应用服务器库 - Tomcat 8.5.86
1.7 基于XML配置方式使用Spring MVC

单击【Add Selected】按钮
1.7 基于XML配置方式使用Spring MVC

单击【OK】按钮

11、启动Tomcat服务器

单击工具栏上绿色的运行按钮
启动失败,输出目录没有项目运行所需的jar包
1.7 基于XML配置方式使用Spring MVC

配置Artifacts,添加项目正常运行所需的jar包
1.7 基于XML配置方式使用Spring MVC

单击【Put into /WEB-INF/lib】菜单项
1.7 基于XML配置方式使用Spring MVC
单击【OK】按钮
启动服务器,查看结果

1.7 基于XML配置方式使用Spring MVC

12、测试登录功能

登录成功
1.7 基于XML配置方式使用Spring MVC
登录失败

1.7 基于XML配置方式使用Spring MVC

二、实战练习

任务1、设置项目首页 - index.jsp

页面显示内容 - Welcome to Spring MVC World!与系统当前日期时间

1、修改web.xml文件

注释掉“设置启动首页”元素(删除也可以)
1.7 基于XML配置方式使用Spring MVC

2、创建首页文件

在views目录里创建首页文件 - index.jsp
1.7 基于XML配置方式使用Spring MVC

<%@ page import="java.util.Date" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>首页</title>
    </head>
    <body>
        <h1>Welcome to Spring MVC World~</h1>
        <h3><%= new Date() %></h3> <!--JSP表达式元素-->
    </body>
</html>

此时,启动服务器,查看效果
1.7 基于XML配置方式使用Spring MVC

3、修改登录控制器

在登录控制器里LoginController里添加一个方法能够跳转到首页
1.7 基于XML配置方式使用Spring MVC

4、启动服务器,查看效果

访问http://localhost:8080/SpringMvcDemo01/
1.7 基于XML配置方式使用Spring MVC

任务2、首页添加登录链接,单击跳转到登录页面

1、修改首页文件

添加一个超链接,跳转到登录页面
1.7 基于XML配置方式使用Spring MVC

启动服务器
1.7 基于XML配置方式使用Spring MVC

单击【跳转到登录页面】超链接
1.7 基于XML配置方式使用Spring MVC
修改超链接元素
1.7 基于XML配置方式使用Spring MVC

2、修改登录控制器

在LoginController里添加一个跳转到登录页面的方法toLogin()
1.7 基于XML配置方式使用Spring MVC

3、启动服务器,查看效果

显示首页
1.7 基于XML配置方式使用Spring MVC

单击【跳转到登录页面】超链接
1.7 基于XML配置方式使用Spring MVC

任务3、利用Spring MVC配置文件实现快捷页面跳转

1、修改Spring MVC配置文件

定义两个视图控制器来负责页面跳转

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

    <!--采用注解驱动-->
    <mvc:annotation-driven/>

    <!--扫描控制器-->
    <context:component-scan base-package="net.hf.spring.controller"/>

    <!--定义内部资源视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--定义视图控制器-->
    <mvc:view-controller path="/" view-name="index"/>
    <mvc:view-controller path="/toLogin" view-name="login"/>
</beans>

2、修改登录控制器

删除或者注释两个负责页面跳转的方法:index()、toLogin()
1.7 基于XML配置方式使用Spring MVC

3、启动服务器,查看效果

显示首页(说明Spring MVC配置文件里的第一个视图控制器生效)
1.7 基于XML配置方式使用Spring MVC

单击【跳转到登录页面】超链接,跳转到了登录页面(说明Spring MVC配置文件里的第二个视图控制器也生效了)
1.7 基于XML配置方式使用Spring MVC

任务4、添加静态资源,让Spring MVC正确处理

1、添加一张图片

在WEB-INF里创建images目录,将图片gingko.jpg拷贝进来
1.7 基于XML配置方式使用Spring MVC

2、修改首页文件

增加显示图片的元素
1.7 基于XML配置方式使用Spring MVC

3、启动服务器,查看效果

首页无法正常显示图片,也就是说明应用无法访问静态的图片资源
1.7 基于XML配置方式使用Spring MVC

4、修改Spring MVC配置文件

单独处理静态资源
1.7 基于XML配置方式使用Spring MVC

5、修改首页文件

图片源采用虚拟路径,由配置文件负责映射到真实路径
1.7 基于XML配置方式使用Spring MVC

6、重启服务器,查看效果

1.7 基于XML配置方式使用Spring MVC

课堂练习
(1)添加CSS样式表

在WEB-INF里创建css目录,在里面创建样式文件index.css,负责首页的样式(元素全部居中,设置页面背景颜色,去掉超链接的下划线……)
1.7 基于XML配置方式使用Spring MVC

1.7 基于XML配置方式使用Spring MVC

1.7 基于XML配置方式使用Spring MVC

1.7 基于XML配置方式使用Spring MVC

(2)添加JavaScript脚本

在WEB-INF里创建js目录,在里面创建脚本文件check.js,负责登录页面的非空校验(先进行用户名非空校验,后进行密码非空校验)
1.7 基于XML配置方式使用Spring MVC

1.7 基于XML配置方式使用Spring MVC

1.7 基于XML配置方式使用Spring MVC

1.7 基于XML配置方式使用Spring MVC

1.7 基于XML配置方式使用Spring MVC

任务5、请求服务器端返回的简单字符串

1、创建获取字符串控制器

获取字符串控制器 - GetStringController
1.7 基于XML配置方式使用Spring MVC

package net.hf.spring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 功能:获取字符串控制器
 * 作者:hf
 * 日期:2023年03月21日
 */
@Controller
public class GetStringController {
    @GetMapping("/getString")
    @ResponseBody // 响应正文注解,表明返回普通字符串而不是返回逻辑视图名
    public String getString() {
        return "Spring MVC真好玩~";
    }
}

2、启动服务器,查看效果

访问http://localhost:8080/SpringMvcDemo01/getString
1.7 基于XML配置方式使用Spring MVC

3、修改获取字符串控制器

设置返回字符串采用的编码
1.7 基于XML配置方式使用Spring MVC

4、重启服务器,查看效果

访问http://localhost:8080/SpringMvcDemo01/getString
1.7 基于XML配置方式使用Spring MVC

思考题:能否让返回字符串有点样式?
设置返回普通文本,返回字符串不认网页标签
1.7 基于XML配置方式使用Spring MVC

设置返回网页文本,返回字符串才认网页标签
1.7 基于XML配置方式使用Spring MVC

任务6、请求服务器端返回的JSON数据

1、创建用户实体类

创建net.hf.spring.bean包,然后在包里创建User类
1.7 基于XML配置方式使用Spring MVC

用户实体类对应用户表
1.7 基于XML配置方式使用Spring MVC

package net.hf.spring.bean;

import java.util.Date;

/**
 * 功能:用户实体类
 * 作者:hf
 * 日期:2023年03月21日
 */
public class User {
    private int id;
    private String username;
    private String password;
    private String telephone;
    private Date registerTime;
    private int popedom;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getTelephone() {
        return telephone;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    public Date getRegisterTime() {
        return registerTime;
    }

    public void setRegisterTime(Date registerTime) {
        this.registerTime = registerTime;
    }

    public int getPopedom() {
        return popedom;
    }

    public void setPopedom(int popedom) {
        this.popedom = popedom;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", telephone='" + telephone + '\'' +
                ", registerTime=" + registerTime +
                ", popedom=" + popedom +
                '}';
    }
}

2、创建获取JSON控制器

获取JSON控制器 - GetJsonController
1.7 基于XML配置方式使用Spring MVC

package net.hf.spring.controller;

import net.hf.spring.bean.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 功能:获取JSON控制器
 * 作者:hf
 * 日期:2023年03月21日
 */
@RestController // @RestController是@Controller和@ResponseBody的结合
public class GetJsonController {
    @GetMapping(value = "/getJson", produces = "application/json; charset=utf-8")
    public User getJson() {
        // 创建用户对象
        User user = new User();
        // 设置用户对象属性
        user.setId(1);
        user.setUsername("萌萌哒");
        user.setPassword("123456");
        user.setTelephone("13890903456");
        user.setRegisterTime(new Date());
        user.setPopedom(1);
        // 返回用户对象(按照请求映射注解的参数设置转换成JSON)
        return user;
    }

    @GetMapping(value = "/getJsonArray", produces = "application/json; charset=utf-8")
    public List<User> getJsonArray() {
        // 创建用户列表
        List<User> users = new ArrayList<>();

        // 创建第1个用户
        User user = new User();
        user.setId(1);
        user.setUsername("萌萌哒");
        user.setPassword("123456");
        user.setTelephone("13890903456");
        user.setRegisterTime(new Date());
        user.setPopedom(1);
        // 将用户添加到用户列表
        users.add(user);

        // 创建第2个用户
        user = new User();
        user.setId(2);
        user.setUsername("康科德");
        user.setPassword("222222");
        user.setTelephone("13856567890");
        user.setRegisterTime(new Date());
        user.setPopedom(1);
        // 将用户添加到用户列表
        users.add(user);

        // 创建第3个用户
        user = new User();
        user.setId(3);
        user.setUsername("娃哈哈");
        user.setPassword("333333");
        user.setTelephone("15890905678");
        user.setRegisterTime(new Date());
        user.setPopedom(1);
        // 将用户添加到用户列表
        users.add(user);

        // 返回用户列表
        return users;
    }
}

3、给项目添加JSON依赖

在pom.xml文件里添加对json的支持
1.7 基于XML配置方式使用Spring MVC

<!--对json的支持-->                                        
<dependency>                                               
    <groupId>com.fasterxml.jackson.core</groupId>          
    <artifactId>jackson-core</artifactId>                  
    <version>2.9.7</version>                               
</dependency>                                              
<dependency>                                               
    <groupId>com.fasterxml.jackson.core</groupId>          
    <artifactId>jackson-databind</artifactId>              
    <version>2.9.7</version>                               
</dependency>                                              
<dependency>                                               
    <groupId>com.fasterxml.jackson.core</groupId>          
    <artifactId>jackson-annotations</artifactId>           
    <version>2.9.7</version>                               
</dependency>                                              

4、启动服务器,查看结果

访问http://localhost:8080/SpringMvcDemo01/getJson
1.7 基于XML配置方式使用Spring MVC

需要将刚才新添加的依赖要放到输出目录
1.7 基于XML配置方式使用Spring MVC

添加之后,lib里就有了对json支持的依赖包
1.7 基于XML配置方式使用Spring MVC

重启服务器,再次访问,查看效果
1.7 基于XML配置方式使用Spring MVC

访问http://localhost:8080/SpringMVCDemo01/getJsonArray
1.7 基于XML配置方式使用Spring MVC

任务7、请求服务器端返回的XML数据

1、创建获取XML控制器

获取XML控制器 - GetXmlController

1.7 基于XML配置方式使用Spring MVC

package net.hf.spring.controller;

import net.hf.spring.bean.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 功能:获取XML控制器
 * 作者:hf
 * 日期:2023年03月21日
 */
@RestController
public class GetXmlController {
    @GetMapping(value = "/getXml", produces = "application/xml; charset=utf-8")
    public List<User> getXml() {
        // 创建用户列表
        List<User> users = new ArrayList<>();

        // 创建第1个用户
        User user = new User();
        user.setId(1);
        user.setUsername("萌萌哒");
        user.setPassword("123456");
        user.setTelephone("13890903456");
        user.setRegisterTime(new Date());
        user.setPopedom(1);
        // 将用户添加到用户列表
        users.add(user);

        // 创建第2个用户
        user = new User();
        user.setId(2);
        user.setUsername("康科德");
        user.setPassword("222222");
        user.setTelephone("13856567890");
        user.setRegisterTime(new Date());
        user.setPopedom(1);
        // 将用户添加到用户列表
        users.add(user);

        // 创建第3个用户
        user = new User();
        user.setId(3);
        user.setUsername("娃哈哈");
        user.setPassword("333333");
        user.setTelephone("15890905678");
        user.setRegisterTime(new Date());
        user.setPopedom(1);
        // 将用户添加到用户列表
        users.add(user);

        // 返回用户列表
        return users;
    }
}

2、项目添加XML的依赖

在pom.xml文件里添加对xml的支持
1.7 基于XML配置方式使用Spring MVC

<!--对xml的支持-->
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.5.3</version>
</dependency>

3、将依赖添加到输出目录

在项目结构窗口里将依赖添加到输出目录
1.7 基于XML配置方式使用Spring MVC

添加之后的情况
1.7 基于XML配置方式使用Spring MVC

4、启动服务器,查看效果

访问http://localhost:8080/SpringMvcDemo01/getXml文章来源地址https://www.toymoban.com/news/detail-476801.html

到了这里,关于1.7 基于XML配置方式使用Spring MVC的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Java配置方式使用Spring MVC

    上一节,我们学习了如何基于XML配置与注解的方式使用Spring MVC,涉及到三个XML配置文件:Spring配置文件(spring-config.xml)、Spring MVC配置文件(spring-mvc-config.xml)、Web部署描述文件(web.xml),这一节,我们通过案例学习如何基于Java配置类与注解的方式使用Spring MVC,只有Java配

    2024年02月05日
    浏览(34)
  • Java配置方式使用Spring MVC:实战练习

    承接上文《Java配置方式使用Spring MVC》 登录页面 - login.jsp 注:这个页面没有JSP代码,其实可以做成静态页面 - login.html 登录成功页面 - success.jsp(必须是动态页面,因为要获取会话对象中的数据) 如果不用JSP的标签库,要获取会话中的数据,要复杂一点 登录失败页面 - failu

    2024年02月05日
    浏览(47)
  • 【Spring MVC】Spring MVC基于注解的程序开发

    目录 一、什么是Spring MVC  二、Spring MVC项目的创建和使用 1、实现客户端和服务器端之间的连接 1.1、RequsestMapping注解 1.2、@RequestMapper的简单使用  1.3、使用@GetMapping和@POSTMapping注解来实现HTTP连接 三、获取参数 1、实现获取单个参数 2、实现获取对象 3、后端参数重命名(@Requ

    2024年02月13日
    浏览(37)
  • 【Spring MVC】Spring MVC的功能使用和相关注解介绍

    Spring MVC主要有三个功能: 连接 获取参数 输出数据 对于 Spring MVC 来说,掌握了以上 3 个功能就相当于掌握了Spring MVC。 连接的功能:将⽤户(浏览器)和 Java 程序连接起来,也就是访问⼀个地址能够调⽤到我们的Spring 程序。 先创建一个SpringMVC项目,过程和SpringBoot项目创建相

    2024年02月16日
    浏览(31)
  • Spring-mvc的参数传递与常用注解的解答及页面的跳转方式---综合案例

    目录 一.slf4j--日志 二.常用注解        2.1.@RequestMapping       2.2.@RequestParam       2.3.@RequestBody       2.4.@PathVariable 三.参数的传递 3.1 基础类型 3.2 复杂类型 3.3 @RequestParam 3.4  @PathVariable 3.5 @RequestBody 3.6 增删改查  四.返回值            4.1 void 返回值   4.2 String

    2024年02月09日
    浏览(43)
  • Spring注解驱动开发之常用注解案例_告别在XML中配置Bean

    注解驱动开发就是不再使用Spring的bean.xml文件,改为纯使用注解的方式开发 @Configuration 此注解为配置类注解,相当于spring.xml文件,即配置类==配置文件 @Bean 给容器中注册一个Bean;类型为返回值的类型,id默认是用方法名作为id 示例 Person类(后续注解配置类中都会以此类举例),

    2024年01月21日
    浏览(39)
  • SSM项目集成Spring Security 4.X版本(使用spring-security.xml 配置文件方式)

    目录 前言 实战开发: 一、Spring Security整合到SSM项目 1. pom文件引入包 2. web.xml 配置 3. 添加 spring-security.xml 文件 二、Spring Security实战应用 1. 项目结构 2. pom文件引入 3. web.xml 配置 4. Spring 配置 applicationContext.xml 5. spring-security.xml 配置 6. springmvc.xml 配置 7. 创建实体类 8. DAO层实

    2024年01月24日
    浏览(40)
  • Spring IOC基于XML和注解管理Bean(二)

    Spring IOC基于XML和注解管理Bean(一) 2.9、实验八:p命名空间 引入p命名空间 引入p命名空间后,可以通过以下方式为bean的各个属性赋值 2.10、实验九:引入外部属性文件 ①加入依赖 ②创建外部属性文件 [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

    2024年02月09日
    浏览(34)
  • Spring IOC基于XML和注解管理Bean(一)

    Spring IOC基于XML和注解管理Bean(二) IoC 是 Inversion of Control 的简写,译为“ 控制反转 ”,它不是一门技术,而是一种设计思想,是一个重要的面向对象编程法则,能够指导我们如何设计出 松耦合 、更优良的程序。 Spring 通过 IoC 容器来管理所有 Java 对象的实例化和初始化,控

    2024年02月08日
    浏览(64)
  • 【Spring MVC】快速学习使用Spring MVC的注解及三层架构

    💓 博客主页:从零开始的-CodeNinja之路 ⏩ 收录文章:【Spring MVC】快速学习使用Spring MVC的注解及三层架构 🎉欢迎大家点赞👍评论📝收藏⭐文章 SpringWebMVC是基于ServletAPI构建的原始Web框架,从⼀开始就包含在Spring框架中。它的正式名称“SpringWebMVC”来⾃其源模块的名称(Spri

    2024年04月17日
    浏览(32)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包