SpringMVC从Controller中获取json数据

简介: 版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010741376/article/details/44680151 web.
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010741376/article/details/44680151

web.xml配置文件:

       

<?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>hello</servlet-name>
	        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	          <init-param>
	           <param-name>contextConfigLocation</param-name>
	           <param-value>/WEB-INF/hello-servlet.xml</param-value>
	      </init-param>
	        <!-- 设置启动优先级 -->
	        <load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
	        <servlet-name>hello</servlet-name>
	        <url-pattern>*.do</url-pattern>
	</servlet-mapping>
	<!-- filter用来设置编码 -->
	<filter>
	       <filter-name>CharacterFilter</filter-name>
	       <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
	        <init-param>
	             <param-name>encoding</param-name>
	             <param-value>utf-8</param-value>
	        </init-param>
	       
	</filter>
	<filter-mapping>
	        <filter-name>CharacterFilter</filter-name>
	        <url-pattern>/</url-pattern>
	</filter-mapping>
	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

springMVC配置文件:

 

<?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:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc 
    http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.1.xsd">
    
    <context:component-scan base-package="com.spring.json.controller"></context:component-scan>
     
     <!-- 开启注解模式 -->
     <mvc:annotation-driven></mvc:annotation-driven>
     
     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
             <property name="prefix" value="/WEB-INF/pages/"></property>
             <property name="suffix" value=".jsp"></property>
     </bean>
    
    
    
    </beans>

实体类User:

 

package com.spring.json.entity;

public class User {
      private String userName;
      private String password;
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}

}
Controller控制器:

方式一:

  

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.spring.json.entity.User;


@Controller
public class UserController {
    
	@RequestMapping(value="/user.do")
	public String toUser(){
		System.out.println("ok");
		return "userList";
	}
	
	//方式一
	@RequestMapping(value="/getUserList.do")
	public String getUserList(HttpServletResponse response){
		  response.setCharacterEncoding("utf-8");
		  response.setContentType("application/json");
		 List<User> userList=getUsers();
		 Gson gson = new Gson(); 
		String json=gson.toJson(userList);
		 System.out.println("json------"+json);
		 PrintWriter out=null;
		  try {
			out=response.getWriter();
			out.write(json);
			out.flush();
		} catch (Exception e) {
			
			e.printStackTrace();
		}finally{
			if(out!=null){
				out.close();
			}
		}
		  return "userList";
	}
	
	
	private List<User> getUsers(){
		List<User> users=new ArrayList<User>();
		User u1=new User();
		u1.setUserName("张三");
		u1.setPassword("123456");
		
		
		User u2=new User();
		u2.setUserName("李四");
		u2.setPassword("ls123");
		
		User u3=new User();
		u3.setUserName("王五");
		u3.setPassword("ww888");
		users.add(u1);
		users.add(u2);
		users.add(u3);
		
		return users;
		
	}
}

方式二:需要加入jackson-all-1.6.4.jar

  

package com.spring.json.controller;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.spring.json.entity.User;


@Controller
public class UserController {
    
	@RequestMapping(value="/user.do")
	public String toUser(){
		System.out.println("ok");
		return "userList";
	}
	
	//方式二
	
	/**
	 * @responsebody表示该方法的返回结果直接写入HTTP response body中
               一般在异步获取数据时使用,在使用@RequestMapping后,返回值通常解析为跳转路径,   
			加上@responsebody后返回结果不会被解析为跳转路径,而是直接写入HTTP response body中。
			比如异步获取json数据,加上@responsebody后,会直接返回json数据
	 */
	@RequestMapping("/getUserList.do")
	@ResponseBody
	public Map<String, Object> getUserList(){
		Map<String, Object> result=new HashMap<String, Object>();
	    List<User> userlist=getUsers();
		result.put("users",userlist);
		return result;
	}
	
	private List<User> getUsers(){
		List<User> users=new ArrayList<User>();
		User u1=new User();
		u1.setUserName("张三");
		u1.setPassword("123456");
		
		
		User u2=new User();
		u2.setUserName("李四");
		u2.setPassword("ls123");
		
		User u3=new User();
		u3.setUserName("王五");
		u3.setPassword("ww888");
		users.add(u1);
		users.add(u2);
		users.add(u3);
		
		return users;
		
	}
}

jsp页面(方式一):

<%@ 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>
    <base href="<%=basePath%>">
    
    <title>My JSP 'welcome.jsp' starting page</title>
     <script type="text/javascript" src="js/jquery-1.7.2.js"></script>
      <script type="text/javascript">
          $(function(){
               $("#btn").click(function(){
		                 
		          $.ajax({
		              type:'post',
		              url:'${pageContext.request.contextPath}/getUserList.do',
		              success:function(data){
		                  //返回json数据
		                  alert("data:"+data);
		                  $.each(data,function(i,user){
		                      $("#result").append(user.userName+"----"+user.password+"<br>");
		                  })
		                  
		              },
		              error:function(e){
		              alert("error:"+e);
		              }
		          
		
		          }); 
               
               
               
               });
         
          });
         
      
         
      
      </script>
  </head>
   
  <body>
       <input type="button" id="btn" value="获取用户信息"/><br/>
      用户信息:<br/>
      <div id="result"></div>
  </body>
</html>

jsp页面(方式二
<%@ 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>
    <base href="<%=basePath%>">
    
    <title>My JSP 'welcome.jsp' starting page</title>
     <script type="text/javascript" src="js/jquery-1.7.2.js"></script>
      <script type="text/javascript">
          $(function(){
               $("#btn").click(function(){
		                 
		          $.ajax({
		              type:'post',
		              url:'${pageContext.request.contextPath}/getUserList.do',
		              success:function(data){
		                  //返回json数据
		                  alert("data:"+data);
		                  $.each(data.users,function(i,user){
		                      $("#result").append(user.userName+"----"+user.password+"<br>");
		                  })
		                  
		              },
		              error:function(e){
		              alert("error:"+e);
		              }
		          
		
		          }); 
               
               
               
               });
         
          });
         
      
         
      
      </script>
  </head>
   
  <body>
       <input type="button" id="btn" value="获取用户信息"/><br/>
      用户信息:<br/>
      <div id="result"></div>
  </body>
</html>

):

  项目截图:

 


相关文章
|
6天前
|
JSON 缓存 自然语言处理
多语言实时数据微店商品详情API:技术实现与JSON数据解析指南
通过以上技术实现与解析指南,开发者可高效构建支持多语言的实时商品详情系统,满足全球化电商场景需求。
|
5天前
|
JSON API 数据安全/隐私保护
Python采集淘宝评论API接口及JSON数据返回全流程指南
Python采集淘宝评论API接口及JSON数据返回全流程指南
|
7天前
|
JSON 自然语言处理 API
多语言实时数据淘宝商品评论API:技术实现与JSON数据解析指南
淘宝商品评论多语言实时采集需结合官方API与后处理技术实现。建议优先通过地域站点适配获取本地化评论,辅以机器翻译完成多语言转换。在合规前提下,企业可构建多语言评论数据库,支撑全球化市场分析与产品优化。
|
13天前
|
机器学习/深度学习 JSON API
干货,淘宝拍立淘按图搜索,淘宝API(json数据返回)
淘宝拍立淘按图搜索API接口基于深度学习与计算机视觉技术,通过解析用户上传的商品图片,在淘宝商品库中实现毫秒级相似商品匹配,并以JSON格式返回商品标题、图片链接、价格、销量、相似度评分等详细信息。
|
14天前
|
JSON 算法 API
干货!电商API接口(淘宝商品评论)json数据返回
要获取淘宝商品评论的JSON数据,需通过淘宝开放平台的商品评论API接口实现。以下是详细步骤及代码示例
|
1月前
|
JSON API 数据格式
淘宝/天猫图片搜索API接口,json返回数据。
淘宝/天猫平台虽未开放直接的图片搜索API,但可通过阿里妈妈淘宝联盟或天猫开放平台接口实现类似功能。本文提供基于淘宝联盟的图片关联商品搜索Curl示例及JSON响应说明,适用于已获权限的开发者。如需更高精度搜索,可选用阿里云视觉智能API。
|
1月前
|
JSON API 数据安全/隐私保护
深度分析淘宝卖家订单详情API接口,用json返回数据
淘宝卖家订单详情API(taobao.trade.fullinfo.get)是淘宝开放平台提供的重要接口,用于获取单个订单的完整信息,包括订单状态、买家信息、商品明细、支付与物流信息等,支撑订单管理、ERP对接及售后处理。需通过appkey、appsecret和session认证,并遵守调用频率与数据权限限制。本文详解其使用方法并附Python调用示例。
|
18天前
|
机器学习/深度学习 JSON 监控
淘宝拍立淘按图搜索与商品详情API的JSON数据返回详解
通过调用taobao.item.get接口,获取商品标题、价格、销量、SKU、图片、属性、促销信息等全量数据。
|
19天前
|
JSON API 数据格式
干货满满!淘宝商品详情数据,淘宝API(json数据返回)
淘宝商品详情 API 接口(如 taobao.item.get)的 JSON 数据返回示例如下
|
28天前
|
JSON 算法 安全
淘宝商品详情API接口系列,json数据返回
淘宝开放平台提供了多种API接口用于获取商品详情信息,主要通过 淘宝开放平台(Taobao Open Platform, TOP) 的 taobao.tbk.item.info.get(淘宝客商品详情)或 taobao.item.get(标准商品API)等接口实现。以下是关键信息及JSON返回示例: