一.除了搭建springmvc框架需要的jar包外,还需要这两个jar包

jackson-core-asl-1.9.2.jar和jackson-mapper-asl-1.9.2.jar

二.web,.xml配置

classpath:spring-servlet.xml指定springmvc配置文件的位置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <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.xml配置文件的位置和名称,默认为WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,如spring-servlet.xml
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value> 默认
</init-param>
-->
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping> </web-app>

三.spring-servlet.xml配置

通过此配置,将实体类自动返回为json格式的数据

<?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:p="http://www.springframework.org/schema/p"
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-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<!-- 启用spring mvc 注解 -->
<context:annotation-config /> <!-- 设置使用注解的类所在的jar包 -->
<context:component-scan base-package="me.mvc,me.base"></context:component-scan> <!-- 完成请求和注解POJO的映射 -->
<!-- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> --> <!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/jsp/" p:suffix=".jsp" />
   <!-- 通过实体类返回json格式数据的关键配置 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <!--返回字符串格式json--> <value>application/json;charset=UTF-8</value> </list> </property> </bean> </list> </property> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="102400000"></property> </bean> </beans>

四,后台java代码

package me.mvc;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import me.mvc.service.testmvcDao;
import net.sf.json.JSONArray; import org.apache.struts2.ServletActionContext;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView; @Controller
@RequestMapping("/mvc/*")
public class testmvc { @RequestMapping(method=RequestMethod.GET,value="/hello22index.do")//第一步访问hello2页面
public String index2() { return "hello2";
}
@ResponseBody
@RequestMapping(method=RequestMethod.POST,value="/hello22.do")//第二步前台发送ajax请求调用此方法并返回json数据
public User index2post(String testname1 ,HttpServletResponse response) throws IOException { System.out.println("*************:"+testname1); User u=new User();
u.setUsername("name");
u.setUserpassword("pass");
return u;
} }

五.前端页面

该方法sendajax()将向后台发送请求,调用index2post()方法,返回json数据格式

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script type="text/javascript" src="../../js/jquery-1.12.0.js"></script>
<base href="<%=basePath%>"> <title>My JSP 'hello2.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page"> <script type="text/javascript" src="<%=path%>/js/jquery-1.12.0.js"></script></head> <body> <input type="text" name="testname" id="testname1"> <input type="button" value="ajax提交" onclick="sendajax()"> </form>
</body>
<script type="text/javascript">
function sendajax()
{
var testname1=$("#testname1").val();
alert(testname1);
$.ajax({
type: "post",
url: "<%=path%>/mvc/hello22.do",
data: {testname1:testname1},
dataType: "json",
success: function (data) {
alert(data.username); },
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("系统繁忙,请稍后重试!");
}
});
}
</script>
</html>

  

SpringMVC通过实体类返回json格式的字符串,并在前端显示的更多相关文章

  1. .net 实体类与json转换(.net自带类库实现)更新

    上一篇文章中写到在.net中实体类跟json格式的相互转换,今天在做具体转换时候,发现之前版本的jsonhelp对于日期类型的转换不全面.之前版本的jsonhelp中从实体类转换成json格式时候,将 ...

  2. [转]SpringMVC使用@ResponseBody时返回json的日期格式、@DatetimeFormat使用注意

    一.SpringMVC使用@ResponseBody时返回json的日期格式 前提了解: @ResponseBody 返回json字符串的核心类是org.springframework.http.co ...

  3. SpringMVC使用@ResponseBody时返回json的日期格式、@DatetimeFormat使用注意

    一.SpringMVC使用@ResponseBody时返回json的日期格式 前提了解: @ResponseBody 返回json字符串的核心类是org.springframework.http.co ...

  4. 3.自定义返回json格式的数据给前台(自定义Controller类中的Json方法)

    在mvc的项目中,我们前台做一些操作时,后台要返回一些结果给前台,这个时候我们就需要有一个状态来标识到底是什么类型的错误, 例如: 执行删除的时候,如果操作成功(1行受影响),我们需要返回状态为1并输 ...

  5. springmvc通过ajax异步请求返回json格式数据

    jsp 首先创建index.jsp页面 <script type="text/javascript"> $(function () { $("#usernam ...

  6. Springboot实体类转JSON报错Could not find acceptable representation & 设置访问项目根路径的默认欢迎页面

    =================实体类转JSON报错的解决办法============= 之前在springmvc的时候也报过这个错,原因以及springmvc中解决办法参考:https://www ...

  7. ajax请求正常,返回json格式,后台没问题,浏览器500

    1.使用的是springmvc中的 @ResponseBody 注解   ,后台不报错,.正常走完:以为使用这个注解就可以正常返回json格式的数据:所以一直没有怀疑是注解的问题: 以为是ajax本身 ...

  8. ASP.NET实现二维码 ASP.Net上传文件 SQL基础语法 C# 动态创建数据库三(MySQL) Net Core 实现谷歌翻译ApI 免费版 C#发布和调试WebService ajax调用WebService实现数据库操作 C# 实体类转json数据过滤掉字段为null的字段

    ASP.NET实现二维码 using System;using System.Collections.Generic;using System.Drawing;using System.Linq;us ...

  9. 返回json格式 不忽略null字段

    返回json格式 不忽略null字段  发布于 353天前  作者 king666  271 次浏览  复制  上一个帖子  下一个帖子  标签: json 如题,一个实体的某个字段如果为null,在 ...

随机推荐

  1. Javascript Jquery 中的数组定义与操作_子木玲_新浪博客

    body{ font-family: "Microsoft YaHei UI","Microsoft YaHei",SimSun,"Segoe UI& ...

  2. JSON串行化

    大多数情况下,我们不会再Javascript中直接创建JSON字符串.而是,创建一些Javascript对象,这些对象和服务器上的.net对象对应.因此,可以在服务器上创建.net实体类,然后串行化成 ...

  3. IO之同步、异步、阻塞、非阻塞 (2)

    [原创链接: http://www.smithfox.com/?e=191, 转载请保留此声明, 谢谢! ] I/O Model 是一个很大的话题, 也是一个实践性很强的事情, 网上有各种说法和资料, ...

  4. javascript基础教程学习总结(1)

    摘自javascript基础教程 开始: 1.将脚本放在哪里: 1.1 放在html和<html>之间 范例: <!DOCTYPE html PUBLIC "-//W3C/ ...

  5. javascript-函数及兼容

    1.事件绑定,删除,传播,默认方式,获取类型的兼容 var eventList = { //添加事件兼容 addEvent:function (event,type,backevent) { if ( ...

  6. MAC中使用Vim和GCC编译C程序

    1.打开终端 2.输入以下命令进入vim编辑器: vim a.c 3.进入编辑器后按i进入insert模式,然后键入以下代码: #include<stdio.h> int main(){ ...

  7. IOS开发-UI学习-UIPageControl(页码控制器)的使用

    UIPageControl即页码控制器,是在翻动图片阅览时下面显示的几个小点,属性设置如下: UIPageControl *pagecontrol = [[UIPageControl alloc]in ...

  8. web 前端routine

    HTML:check CSS : check Javascript: struggling 框架:—— SQL:—— http://www.cnblogs.com/kzang/tag/SQL/ web ...

  9. Java XML解析器

    使用Apache Xerces解析XML文档 一.技术概述 在用Java解析XML时候,一般都使用现成XML解析器来完成,自己编码解析是一件很棘手的问题,对程序员要求很高,一般也没有专业厂商或者开源组 ...

  10. lower_bound和upper_bound算法实现

    lower_bound算法要求在已经按照非递减顺序排序的数组中找到第一个大于等于给定值key的那个数,其基本实现原理是二分查找,如下所示: int lower_bound(vector<int& ...