Spring MVC使用JSON的过程与步骤


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

目录

 JSON数据交互

 RESTful支持


 JSON数据交互

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

 2.在WEB-INF目录下创建web.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"
		 id="WebApp_ID" version="4.0">
	<display-name>chapter13</display-name>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	<!-- 配置前端控制器 -->
	<servlet>
		<!-- 配置前端过滤器 -->
		<servlet-name>springmvc</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>
		<!-- 表示容器在启动时立即加载Servlet -->
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

3.src目录下创建Spring MVC的核心配置文件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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
	<!--指定需要扫描的包 -->
	<context:component-scan base-package="com.ssm.controller" />
	<!-- 配置注解驱动 -->
	<mvc:annotation-driven />
	<!-- 配置静态资源的访问映射,此配置中的文件,将不被前端控制器拦截 -->
	<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
	<!-- 定义视图解析器 -->
	<bean id="viewResoler"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 设置前缀 -->
		<property name="prefix" value="/" />
		<!-- 设置后缀 -->
		<property name="suffix" value=".jsp" />
	</bean>
</beans>

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

package com.ssm.po;
public class Customer {
	private Integer id;
	private String loginname;
	private String nickname;
	private String password;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getLoginname() {
		return loginname;
	}
	public void setLoginname(String loginname) {
		this.loginname = loginname;
	}
	public String getNickname() {
		return nickname;
	}
	public void setNickname(String nickname) {
		this.nickname = nickname;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String toString() {
		return "Customer [id=" + id + ", loginname=" + loginname + ", nickname=" + nickname + ", password=" + password
				+ "]";
	}
}

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

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<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.5.0.min.js">
	</script>
	<script type="text/javascript">
	function testJson(){
		//获取输入的客户信息
		var loginname=$("#loginname").val();
		var password=$("#password").val();
		$.ajax({
			url:"${pageContext.request.contextPath }/testJson",
			type:"post",
			//data表示发送的数据
			data:JSON.stringify({loginname:loginname,password:password}),
			// 定义发送请求的数据格式为JSON字符串
			contentType:"application/json;charset=UTF-8",
			//定义回调响应的数据格式为JSON字符串,该属性可以省略
			dataType:"json",
			//成功响应的结果
			success:function(data){
				if(data!=null){
					alert("您输入的登录名为:"+data.loginname+",密码为:"+data.password);
				}
			}
  		});
	}
	</script>
	</head>
	<body>
		<form>
		登录名:<input type="text" name="loginname" id="loginname" /> <br />
		密&nbsp;&nbsp;&nbsp;&nbsp;码:<input type="password" name="password" id="password" /> <br />
		<input type="button" value="测试JSON交互" onclick="testJson()" />	
		</form>
	</body>
</html>

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

jquery-3.5.0.min.js

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

package com.ssm.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ssm.po.Customer;
@Controller
public class CustomerController {
	@RequestMapping("/testJson")
	@ResponseBody
	public Customer testJson(@RequestBody Customer customer){
		System.out.println(customer);
		return customer;
	}

}

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

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

 7.运行json.jsp

 RESTful支持

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

	@RequestMapping(value="/customer/{id}",method=RequestMethod.GET)
	@ResponseBody
	public Customer selectCustomer(@PathVariable("id") Integer id){

		System.out.println(id);
		Customer customer=new Customer();

		if(id==1){
			customer.setLoginname("zyy");
		}
		return customer;
	}

 @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方式通过输入的客户编号来查询客户信息

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>RESTful测试</title>
	<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-3.5.0.min.js">
	</script>
	<script type="text/javascript">
	function search(){
		//获取输入的查询编号
		var id=$("#number").val();
		$.ajax({
			url:"${pageContext.request.contextPath }/customer/"+id,
			type:"GET",
			//定义回调响应的数据格式为JSON字符串,该属性可以省略
			dataType:"json",
			//成功响应的结果
			success:function(data){
				if(data.loginname!=null){
					alert("您查询的客户登录名为:"+data.loginname);
				}else{
					alert("没有找到id为:"+id+"的客户!");
				}
			}
  		});
	}
	</script>
	</head>
	<body>
		<form>
		客户编号:<input type="text" name="number" id="number" /> <br />
		<input type="button" value="查询" onclick="search()" />	
		</form>
	</body>
</html>

4.运行restful.jsp

 源码:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无忧#

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值