• Spring MVC使用JSON的过程与步骤



    活动地址:CSDN21天学习挑战赛

    目录

     JSON数据交互

     RESTful支持


     JSON数据交互

    1.用eclipse创建一个动态web项目,将项目依赖的jar包放到lib目录下:

     2.在WEB-INF目录下创建web.xml,对Spring MVC的前端控制器等信息进行配置。

    1. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
    4. http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    5. id="WebApp_ID" version="4.0">
    6. <display-name>chapter13display-name>
    7. <welcome-file-list>
    8. <welcome-file>index.jspwelcome-file>
    9. welcome-file-list>
    10. <servlet>
    11. <servlet-name>springmvcservlet-name>
    12. <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    13. <init-param>
    14. <param-name>contextConfigLocationparam-name>
    15. <param-value>classpath:springmvc-config.xmlparam-value>
    16. init-param>
    17. <load-on-startup>1load-on-startup>
    18. servlet>
    19. <servlet-mapping>
    20. <servlet-name>springmvcservlet-name>
    21. <url-pattern>/url-pattern>
    22. servlet-mapping>
    23. web-app>

    3.src目录下创建Spring MVC的核心配置文件springmvc-config.xml

    1. <beans xmlns="http://www.springframework.org/schema/beans"
    2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xmlns:mvc="http://www.springframework.org/schema/mvc"
    4. xmlns:context="http://www.springframework.org/schema/context"
    5. xmlns:tx="http://www.springframework.org/schema/tx"
    6. xsi:schemaLocation="http://www.springframework.org/schema/beans
    7. http://www.springframework.org/schema/beans/spring-beans.xsd
    8. http://www.springframework.org/schema/mvc
    9. http://www.springframework.org/schema/mvc/spring-mvc.xsd
    10. http://www.springframework.org/schema/context
    11. http://www.springframework.org/schema/context/spring-context.xsd">
    12. <context:component-scan base-package="com.ssm.controller" />
    13. <mvc:annotation-driven />
    14. <mvc:resources location="/js/" mapping="/js/**">mvc:resources>
    15. <bean id="viewResoler"
    16. class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    17. <property name="prefix" value="/" />
    18. <property name="suffix" value=".jsp" />
    19. bean>
    20. beans>

    4.在src目录下创建一个com.ssm.po包,在包内创建一个客户Customer类,该类用于封装User类型的请求参数。

    1. package com.ssm.po;
    2. public class Customer {
    3. private Integer id;
    4. private String loginname;
    5. private String nickname;
    6. private String password;
    7. public Integer getId() {
    8. return id;
    9. }
    10. public void setId(Integer id) {
    11. this.id = id;
    12. }
    13. public String getLoginname() {
    14. return loginname;
    15. }
    16. public void setLoginname(String loginname) {
    17. this.loginname = loginname;
    18. }
    19. public String getNickname() {
    20. return nickname;
    21. }
    22. public void setNickname(String nickname) {
    23. this.nickname = nickname;
    24. }
    25. public String getPassword() {
    26. return password;
    27. }
    28. public void setPassword(String password) {
    29. this.password = password;
    30. }
    31. public String toString() {
    32. return "Customer [id=" + id + ", loginname=" + loginname + ", nickname=" + nickname + ", password=" + password
    33. + "]";
    34. }
    35. }

    5.在webapp目录下创建页面文件json.jsp

    1. <%@ page language="java" contentType="text/html; charset=UTF-8"
    2. pageEncoding="UTF-8"%>
    3. html>
    4. <html>
    5. <head>
    6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    7. <title>测试JSON交互title>
    8. <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-3.5.0.min.js">
    9. script>
    10. <script type="text/javascript">
    11. function testJson(){
    12. //获取输入的客户信息
    13. var loginname=$("#loginname").val();
    14. var password=$("#password").val();
    15. $.ajax({
    16. url:"${pageContext.request.contextPath }/testJson",
    17. type:"post",
    18. //data表示发送的数据
    19. data:JSON.stringify({loginname:loginname,password:password}),
    20. // 定义发送请求的数据格式为JSON字符串
    21. contentType:"application/json;charset=UTF-8",
    22. //定义回调响应的数据格式为JSON字符串,该属性可以省略
    23. dataType:"json",
    24. //成功响应的结果
    25. success:function(data){
    26. if(data!=null){
    27. alert("您输入的登录名为:"+data.loginname+",密码为:"+data.password);
    28. }
    29. }
    30. });
    31. }
    32. script>
    33. head>
    34. <body>
    35. <form>
    36. 登录名:<input type="text" name="loginname" id="loginname" /> <br />
    37.     码:<input type="password" name="password" id="password" /> <br />
    38. <input type="button" value="测试JSON交互" onclick="testJson()" />
    39. form>
    40. body>
    41. html>

    当执行页面中的testJson()函数时,函数会使用JQuery的AJAX方式,将JSON格式的登录名和密码传递到"/testJson"结尾的请求中。所以在webapp目录下创建js文件夹用于存放

    jquery-3.5.0.min.js

     6.在src目录下创建com.ssm.controller包,在该包下创建一个用于存放客户操作的控制器类CustomerController

    1. package com.ssm.controller;
    2. import org.springframework.stereotype.Controller;
    3. import org.springframework.web.bind.annotation.PathVariable;
    4. import org.springframework.web.bind.annotation.RequestBody;
    5. import org.springframework.web.bind.annotation.RequestMapping;
    6. import org.springframework.web.bind.annotation.RequestMethod;
    7. import org.springframework.web.bind.annotation.ResponseBody;
    8. import com.ssm.po.Customer;
    9. @Controller
    10. public class CustomerController {
    11. @RequestMapping("/testJson")
    12. @ResponseBody
    13. public Customer testJson(@RequestBody Customer customer){
    14. System.out.println(customer);
    15. return customer;
    16. }
    17. }

    使用注解方式定义一个控制器类,并编写了接受和响应JSON格式数据的testJson()方法,在方法中接受并打印了接收到的JSON格式的用户数据,然后返回了JSON格式的用户对象。

    方法中的@RequestBody注解用于将前端请求体中的JSON格式数据绑定到形参customer上,@ResponseBody注解用于直接返回Customer对象。

     7.运行json.jsp

     RESTful支持

    1.在控制器类CustomerController中编写客户查询方法selectCustomer()

    1. @RequestMapping(value="/customer/{id}",method=RequestMethod.GET)
    2. @ResponseBody
    3. public Customer selectCustomer(@PathVariable("id") Integer id){
    4. System.out.println(id);
    5. Customer customer=new Customer();
    6. if(id==1){
    7. customer.setLoginname("zyy");
    8. }
    9. return customer;
    10. }

     @RequestMapping(value="/customer/{id}",method=RequestMethod.GET);注解用于匹配请求路径和方式。其中value="/customer/{id}"表示可以匹配到以"customer/{id}"结尾的请求,id为请求中的动态参数;method=RequestMethod.GET表示只接受GET方式的请求。方法中@PathVariable("id")注解则用于接受并绑定请求参数,它可以将请求URL中的变量映射到方法的形参上。如果请求路径为"/customer/{id}",即请求参数中的id和方法形参名称id一样,则@PathVariable后面的("id")可以省略。

     2.在webapp创建restful.jsp,在页面中使用AJAX方式通过输入的客户编号来查询客户信息

    1. <%@ page language="java" contentType="text/html; charset=UTF-8"
    2. pageEncoding="UTF-8"%>
    3. html>
    4. <html>
    5. <head>
    6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    7. <title>RESTful测试title>
    8. <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-3.5.0.min.js">
    9. script>
    10. <script type="text/javascript">
    11. function search(){
    12. //获取输入的查询编号
    13. var id=$("#number").val();
    14. $.ajax({
    15. url:"${pageContext.request.contextPath }/customer/"+id,
    16. type:"GET",
    17. //定义回调响应的数据格式为JSON字符串,该属性可以省略
    18. dataType:"json",
    19. //成功响应的结果
    20. success:function(data){
    21. if(data.loginname!=null){
    22. alert("您查询的客户登录名为:"+data.loginname);
    23. }else{
    24. alert("没有找到id为:"+id+"的客户!");
    25. }
    26. }
    27. });
    28. }
    29. script>
    30. head>
    31. <body>
    32. <form>
    33. 客户编号:<input type="text" name="number" id="number" /> <br />
    34. <input type="button" value="查询" onclick="search()" />
    35. form>
    36. body>
    37. html>

    4.运行restful.jsp

     源码:

    链接:https://pan.baidu.com/s/1ge-iF6GoQ-KQiM_T5Ynw9Q?pwd=5bi6
    提取码:5bi6

  • 相关阅读:
    ssm整合增删改查
    Allegro模块镜像详细操作教程
    基于python开发的IP修改工具
    mysql中遇到查询字段的别名与函数冲突问题
    基于Netty实现的简单聊天服务组件
    【react native】模拟mock接口
    【开发教程3】开源蓝牙心率防水运动手环-开发环境搭建
    Nacos配置管理
    Codeforces Round #826 (Div. 3) A-E
    Java二分查找
  • 原文地址:https://blog.csdn.net/weixin_52473454/article/details/126238331