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>
时间: 2024-08-01 03:44:21

Spring MVC系列:(11)返回JSON的相关文章

Spring MVC使用@ResponseBody返回JSON数据406问题解决方案

其实前面一篇关于zTree返回JSON数据的文章已经有一种解决方案了,但是当我今天在新公司搭建新环境的时候,发现决然又不行了,所以我觉得那应该不是最优的解决方案. 说起来,我以前接触到的一个项目,根本没有配置spring的文件,就直接用@ResponseBody可以返回JSON数据,不知道其中的秘诀在什么地方,搞不懂了. 今天主要提供另一个解决@ResponseBody返回JSON数据,页面抛出406错误的解决方案. 第一步,引入包: <dependency> <groupId>c

Spring MVC灵活控制返回json的值(自定义过滤字段)

在使用spring MVC开发过程中,为了提高项目执行效率,所以在一些外键字段的实体中会注解"@ManyToOne(fetch = FetchType.LAZY)"以实现延迟加载的效果. 但是,在使用ajax请求数据,当需要返回的序列化数据中包含延迟加载的属性时,会出现错误,延迟加载的属性无法进行序列化.在这个时候,我们需要暂时取消延迟加载,以取到所有需要的数据. 可是,这样又会造成一堆垃圾数据的产生.序列化.传递至前台. 所以需要在控制层进行数据过滤,只序列化需要的数据. 具体过滤方

【转】解决spring mvc 中ajax返回json乱码问题

转载自:http://my.oschina.net/u/140421/blog/176625 转载自:http://my.oschina.net/candon/blog/149073?fromerr=I9VBOy62 第一个转载: 在使用spring-mvc的mvc的时候既享受它带来的便捷,又头痛它的一些问题,比如经典的中文乱码问题.现在是用json作为客户端和服务端 的数据交换格式貌似很流行,但是在springmvc中有时候会因为我们的各种疏忽从而造成页面ajax请求到的相应数据,如果带有中文

spring mvc 4.1 返回json报406错误的解决办法

浏览器访问,报 The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers. 解决办法,检查springmvc的配置文件中有无 <mvc:annotation-driven />

spring -mvc 将对象封装json返回时删除掉对象中的属性注解方式

spring -mvc 将对象封装json返回时删除掉对象中的属性注解方式 在类名,接口头上注解使用在 @JsonIgnoreProperties(value={"comid"}) //希望动态过滤掉的属性 例 @JsonIgnoreProperties(value={"comid"}) public interface 接口名称{ } @JsonIgnoreProperties(value={"comid"}) public class 类名{

判断JSON是否为空 (用spring mvc @ResponseBody 自动返回的json串 )

判断JSON是否为空 (用spring mvc @ResponseBody 自动返回的json串 ) 知识分类:EXTJS  spring mvc json 记录时间: 20150708 简单描述:用json.length 属性长度来判断是否为空,在此过程中spring mvc 自动返回的json串是 字符串的类型,所以用.length的方式返回的则是字符串的长度(一般空的JSON 在此处返回的长度应为3),并不是数组的长度,在EXTJS中用Ext.decode(json); 则可以将字符串js

Spring基础系列11 -- 自动创建Proxy

Spring基础系列11 -- 自动创建Proxy 转载:http://www.cnblogs.com/leiOOlei/p/3557964.html 在<Spring3系列9- Spring AOP——Advice>和<Spring3系列10- Spring AOP——Pointcut,Advisor拦截指定方法>中的例子中,在配置文件中,你必须手动为每一个需要AOP的bean创建Proxy bean(ProxyFactoryBean). 这不是一个好的体验,例如,你想让DAO层

MVC web api 返回JSON的几种方式,JSON时间去T的几种方式。

MVC web api 返回JSON的几种方式 1.在WebApiConfig的Register中加入以下代码 1 config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); 2.在WebApiConfig的Register中加入以下代码 1 config.Formatters.Remove(config.Formatters.XmlFormatter);

spring mvc @RequestBody接受post json对象

jq ajax通过post json对象 遇到的HTTP 415/400问题错误解决方案:http://www.linuxidc.com/Linux/2014-04/99928.htm 客户端: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</ti

使用Spring MVC 的 @RequestBody 映射json请求参数时报异常问题

使用Spring MVC 的 @RequestBody 映射json请求参数时报"The request sent by the client was syntactically incorrect."异常解决方案 最近工作中开发RESTful接口需要处理客户端上传的json,图方便想起Spring的Controller中有@RequestBody可以优雅地完成json报文与Java类的映射,但是使用时碰到了 "The request sent by the client w