首页 > 代码库 > Spring MVC系列:(11)返回JSON

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="http://www.mamicode.com/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="http://www.mamicode.com/${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="http://www.mamicode.com/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="http://www.mamicode.com/user")
public class UserAction {

    @InitBinder
    private void initBinder(ServletRequestDataBinder binder){
        binder.registerCustomEditor(
                Date.class, 
                new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    }
    
    @RequestMapping(value="http://www.mamicode.com/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="http://www.mamicode.com/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