码迷,mamicode.com
首页 > 编程语言 > 详细

Spring MVC系列:(11)返回JSON

时间:2016-09-20 14:06:18      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:springmvc


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

标签:springmvc

原文地址:http://lsieun.blog.51cto.com/9210464/1854428

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!