在SpringMVC中进行JSON简单的数据交互

工具
1.java环境
2.相应的jar包

导入响应的jar包
在这里插入图片描述
这几个包主要用于JSON数据转换
在这里插入图片描述
在web.xml中对SpringMVC 的前端控制器信息进行配置

<?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">
    <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>
    <display-name>jsonTest</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

在src目录下,创建SpringMVC的核心配置文件springmvc-config.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">


    <context:component-scan base-package="com.itheima.controller"/>
    <mvc:annotation-driven/>
    <mvc:resources mapping="/js/**" location="/js/"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

创建响应包用于存放User类型的请求参数和控制器类
在这里插入图片描述
User.java

package com.itheima.po;

public class User {
    private String username;
    private String password;

    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 toString(){
        return "User[username=" + username + ", password=" + password + "]";
    }

}

创建页面文件index.jsp文件来测试JSON数据交互

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    <title>测试json交互</title>
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.3.1.min.js">
    </script>
    <script type="text/javascript">
      function testJson() {
        var username = $("#username").val();
        var password = $("#password").val();
        $.ajax({
          url : "${pageContext.request.contextPath}/testJson",
          type : "post",
          data : JSON.stringify({username:username,password:password}),
          contentType : "application/json;charset=UTF-8",
          dataType : "json",
          success : function (data) {
            if (data != null) {
              alert("您输入的用户名为:"+data.username+
              "密码为:"+data.password)
            }
          }
        });
      }
    </script>
  </head>
  <body>
    <form>
      用户名:<input type="text" name="username" id="username"><br>
      密&nbsp;&nbsp;&nbsp;码:<input type="password" name="password" id="password"><br>
      <input type="button" value="测试json交互" "testJson()"/>
    </form>
  </body>
</html>

编写控制器类UserController.java

package com.itheima.controller;

import com.itheima.po.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@Controller
public class UserController {
    @RequestMapping("/testJson")
    @ResponseBody
    public User testJson(@RequestBody User user){
        System.out.println(user);
        return user;
    }

    @RequestMapping(value="/user/{id}",method=RequestMethod.GET)
    @ResponseBody
    public User selectUser(@PathVariable("id") String id){
        System.out.println("id=" + id);
        User user = new User();
        if (id.equals("1234")){
            user.setUsername("tom");
        }
        return user;
    }

}

将项目发布到tomcat启动便可进行测试了

猜你喜欢

转载自blog.csdn.net/weixin_43951020/article/details/89081210
今日推荐