SpringMVC学习笔记(十二)

1、SpringMVC实现json交互

需要注意的是json需要哪些jar包、如何配置json转换器以及注解@RequestBod和@ResponseBody的含义。

2、简单实例

(1)项目结构



(2)Item.java

package cn.hwd.springmvc.bean;

public class Item {

	private int id;
	private String name;
	private double price;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public Item() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Item(int id, String name, double price) {
		super();
		this.id = id;
		this.name = name;
		this.price = price;
	}
	@Override
	public String toString() {
		return "Item [id=" + id + ", name=" + name + ", price=" + price + "]";
	}
}

(3)JsonController.java

package cn.hwd.springmvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hwd.springmvc.bean.Item;

@Controller
@RequestMapping("/json")
public class JsonController {
	
	@RequestMapping("/index.action")  
    public String index() throws Exception {
        return "index";  
    }
	
	/**
	 * @RequestBod:表示将json串转换成item对象
	 * @ResponseBody:表示将item对象转换成json串
	 * @param item
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/requestJson.action")  
    public @ResponseBody Item requestJson(@RequestBody Item item) throws Exception {
        return item;  
    }
	
	@RequestMapping("/responseJson.action")  
    public @ResponseBody Item responseJson(Item item) throws Exception {
        return item;  
    }
	
}

(4)spring-servlet.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.3.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
    
    <context:component-scan base-package="cn.hwd.springmvc.controller" />
    
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/page/" />
		<property name="suffix" value=".jsp" />
	</bean>
	
	<!-- 配置json转换器 -->
	<mvc:annotation-driven />
	
</beans>

(5)pom.xml

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>cn.hwd</groupId>
  <artifactId>SpringMVC38</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringMVC38 Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <build>
    <finalName>SpringMVC38</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.0</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
  <dependencies>
  	<dependency>
  		<groupId>javax.servlet</groupId>
  		<artifactId>servlet-api</artifactId>
  		<version>2.5</version>
  	</dependency>
  	<dependency>
	  <groupId>org.springframework</groupId>
	  <artifactId>spring-webmvc</artifactId>
	  <version>4.0.2.RELEASE</version>
	</dependency>
	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>jstl</artifactId>
		<version>1.2</version>
	</dependency>
	<dependency>
		<groupId>taglibs</groupId>
		<artifactId>standard</artifactId>
		<version>1.1.2</version>
	</dependency>
	<!-- json jar包 -->
	<dependency>
	    <groupId>org.codehaus.jackson</groupId>
	    <artifactId>jackson-core-asl</artifactId>
	    <version>1.9.11</version>
	</dependency>
	<dependency>
	    <groupId>org.codehaus.jackson</groupId>
	    <artifactId>jackson-mapper-asl</artifactId>
	    <version>1.9.11</version>
	</dependency>
	<!-- jsp -->
	<dependency>
	    <groupId>javax.servlet</groupId>
	    <artifactId>jsp-api</artifactId>
	    <version>2.0</version>
	    <scope>provided</scope>
	</dependency>
  </dependencies>
</project>

(6)index.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-3.2.1.js"></script> 
<script type="text/javascript">
	//请求json响应json
	function requestJson(){
		$.ajax({
			type: 'post',
			url: '${pageContext.request.contextPath }/json/requestJson.action',
			contentType: 'application/json;charset=utf-8',
			data: '{"id":1,"name":"华为手机","price":1999.9}',
			success: function(data){
				alert("id=" + data.id + "\nname=" + data.name + "\nprice=" + data.price);
			}
		});
	}
	//请求key/value响应json
	function responseJson(){
		$.ajax({
			type: 'post',
			url: '${pageContext.request.contextPath }/json/responseJson.action',
			data: 'id=2&name=魅族&price=1499.9',
			success: function(data){
				alert("id=" + data.id + "\nname=" + data.name + "\nprice=" + data.price);
			}
		});
	}
</script>
</head>
<body>
	<input type="button" value="请求json响应json" οnclick="requestJson()" />
	<input type="button" value="请求key/value响应json" οnclick="responseJson()" />
</body>
</html>

(7)web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Archetype Created Web Application</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-servlet.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>*.action</url-pattern>
  </servlet-mapping>
</web-app>

(8)运行结果


分别点击“请求json响应json"按钮和"请求key/value响应json"按钮,输出结果如下图所示。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值