SpringMVC通过实体类返回json格式的字符串,并在前端显示
一.除了搭建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格式的字符串,并在前端显示的更多相关文章
- .net 实体类与json转换(.net自带类库实现)更新
上一篇文章中写到在.net中实体类跟json格式的相互转换,今天在做具体转换时候,发现之前版本的jsonhelp对于日期类型的转换不全面.之前版本的jsonhelp中从实体类转换成json格式时候,将 ...
- [转]SpringMVC使用@ResponseBody时返回json的日期格式、@DatetimeFormat使用注意
一.SpringMVC使用@ResponseBody时返回json的日期格式 前提了解: @ResponseBody 返回json字符串的核心类是org.springframework.http.co ...
- SpringMVC使用@ResponseBody时返回json的日期格式、@DatetimeFormat使用注意
一.SpringMVC使用@ResponseBody时返回json的日期格式 前提了解: @ResponseBody 返回json字符串的核心类是org.springframework.http.co ...
- 3.自定义返回json格式的数据给前台(自定义Controller类中的Json方法)
在mvc的项目中,我们前台做一些操作时,后台要返回一些结果给前台,这个时候我们就需要有一个状态来标识到底是什么类型的错误, 例如: 执行删除的时候,如果操作成功(1行受影响),我们需要返回状态为1并输 ...
- springmvc通过ajax异步请求返回json格式数据
jsp 首先创建index.jsp页面 <script type="text/javascript"> $(function () { $("#usernam ...
- Springboot实体类转JSON报错Could not find acceptable representation & 设置访问项目根路径的默认欢迎页面
=================实体类转JSON报错的解决办法============= 之前在springmvc的时候也报过这个错,原因以及springmvc中解决办法参考:https://www ...
- ajax请求正常,返回json格式,后台没问题,浏览器500
1.使用的是springmvc中的 @ResponseBody 注解 ,后台不报错,.正常走完:以为使用这个注解就可以正常返回json格式的数据:所以一直没有怀疑是注解的问题: 以为是ajax本身 ...
- 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 ...
- 返回json格式 不忽略null字段
返回json格式 不忽略null字段 发布于 353天前 作者 king666 271 次浏览 复制 上一个帖子 下一个帖子 标签: json 如题,一个实体的某个字段如果为null,在 ...
随机推荐
- sping 对 hibernate进行事务管理--Annotation, xml, 大多数使用XML
1. UserServiceTest.java: package com.bjsxt.service; import org.junit.Test; import org.springframewor ...
- SecureCRT 密钥生成 SSH 使用密钥登陆 服务器
1.首先“Tool”-“Create Public Key” 2. 选择RSA 模式 4. 创建短语密码 5. 密钥长度为1024 6. 选择标准的 key , 下面是生成的路径 二 . 配置 SS ...
- 单片机联网,UIP实现tcp/udp协议
UIP是单片机界联网的一个很好地选择,移植这个库有点复杂,首先是第一步,网卡驱动要写好,使用的网卡芯片为ENC28J60,驱动可以再工程包里面找到 //配置网卡硬件,并设置MAC地址 //返回值:0, ...
- iOS开发之监听键盘高度的变化 分类: ios技术 2015-04-21 12:04 233人阅读 评论(0) 收藏
最近做的项目中,有一个类似微博中的评论转发功能,屏幕底端有一个输入框用textView来做,当textView成为第一响应者的时候它的Y值随着键盘高度的改变而改变,保证textView紧贴着键盘,但又 ...
- 【转】 Vim多行缩进及高级命令
学习别人的帖子,把内容变成自己的就是成长,此处MARK下 Vim多行缩进技巧 1.按v进入visual状态,选择多行,用>或<缩进或缩出 2. 通常根据语言特征使用自动缩进排版:在命令状态 ...
- Android 屏幕适配方案(转载)
3.百分比的引入 1.引入 其实我们的解决方案,就是在项目中针对你所需要适配的手机屏幕的分辨率各自简历一个文件夹. 如下图: 然后我们根据一个基准,为基准的意思就是: 比如480*320的分辨率为基准 ...
- address2line 定位 Android c++奔溃位置
Android调用c++出现奔溃,崩溃信息为如下: 10-11 15:15:13.541 D/AudioMTKStreamOut( 139): write(), buffer = 0x42bd9390 ...
- MySQL性能分析及explain的使用说明
1.使用explain语句去查看分析结果 如explain select * from test1 where id=1;会出现:id selecttype table type possible_k ...
- asp.net 二级域名session共享
1.自定义类 namespace SessionShare{ public class CrossDomainCookie : IHttpModule { private string m_RootD ...
- [题解]bzoj 1861 Book 书架 - Splay
1861: [Zjoi2006]Book 书架 Time Limit: 4 Sec Memory Limit: 64 MBSubmit: 1396 Solved: 803[Submit][Stat ...