Spring MVC系列:(11)返回JSON

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring MVC系列:(11)返回JSON相关的知识,希望对你有一定的参考价值。


1、引入jar包

jackson-core-asl-1.9.11.jar

jackson-mapper-asl-1.9.11.jar


2、配置springmvc.xml

    <!-- 基于注解的适配器 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
            </list>
        </property>
    </bean>


3、Action代码

    @RequestMapping(value="/test")
    public @ResponseBody User test() throws Exception{
        User user = new User();
        user.setId(99);
        user.setName("小明");
        user.setSal(8888.88);
        user.setHiredate(new Date());
        return user;
    }


4、JSP页面

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta name="content-type" content="text/html; charset=UTF-8">
        <title>Index Page</title>
        <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.12.3.js"></script>
        <script type="text/javascript">
            $(function(){
            	$(‘#btn‘).click(function(){
            		$.ajax({
            			"url":"${pageContext.request.contextPath}/user/test.action",
            			success:function(result){
            				var str = "";
            				str += result.id + "\n";
            				str += result.name + "\n";
            				str += result.sal + "\n";
            				str += result.hiredate + "\n";
            				var millisec = result.hiredate;
            				var date = new Date();
            				date.setTime(millisec);
            				str += date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();
            				alert(str);
            			}
            		});
            	});
            });
        </script>
    </head>
  
    <body>
       <input id="btn" type="button" value="GetJson"/>
    </body>
</html>


技术分享



完整的UserAction.java

package com.rk.action;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.rk.entity.User;

@Controller
@RequestMapping(value="/user")
public class UserAction {

    @InitBinder
    private void initBinder(ServletRequestDataBinder binder){
        binder.registerCustomEditor(
                Date.class, 
                new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    }
    
    @RequestMapping(value="/delete")
    public String delete(int id) throws Exception{
        System.out.println("删除用户->" + id);
        //转发到find(int)
        //return "forward:/user/find.action";
        //重定向到find(int)
        return "redirect:/user/find.action?id=4";
    }
    
    @RequestMapping(value="/test")
    public @ResponseBody User test() throws Exception{
        User user = new User();
        user.setId(99);
        user.setName("小明");
        user.setSal(8888.88);
        user.setHiredate(new Date());
        return user;
    }
 
}

完整的springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    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/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">

    <!-- <import resource="com/rk/config/spring-test.xml"/>     -->

    <!-- Action控制器 -->
    <context:component-scan base-package="com.rk.action"></context:component-scan>
    
    <!-- 基于注解的映射器(可选) -->
    <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/>
      
    <!-- 基于注解的适配器 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
            </list>
        </property>
    </bean>
      
    <!-- 视图解析器(可选) -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"/>

</beans>





以上是关于Spring MVC系列:(11)返回JSON的主要内容,如果未能解决你的问题,请参考以下文章

spring mvc 不返回 json 内容 - 错误 406

spring mvc返回json字符串的方式

Spring MVC 中 AJAX请求并返回JSON

spring mvc怎么返回json

json格式的spring mvc输出

Spring MVC返回对象JSON