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>

):

  项目截图:

 


相关文章
|
1月前
|
存储 JSON Apache
揭秘 Variant 数据类型:灵活应对半结构化数据,JSON查询提速超 8 倍,存储空间节省 65%
在最新发布的阿里云数据库 SelectDB 的内核 Apache Doris 2.1 新版本中,我们引入了全新的数据类型 Variant,对半结构化数据分析能力进行了全面增强。无需提前在表结构中定义具体的列,彻底改变了 Doris 过去基于 String、JSONB 等行存类型的存储和查询方式。
揭秘 Variant 数据类型:灵活应对半结构化数据,JSON查询提速超 8 倍,存储空间节省 65%
|
2月前
|
XML 机器学习/深度学习 JSON
在火狐浏览器调ajax获取json数据时,控制台提示“XML 解析错误:格式不佳”。
在火狐浏览器调ajax获取json数据时,控制台提示“XML 解析错误:格式不佳”。
29 0
在火狐浏览器调ajax获取json数据时,控制台提示“XML 解析错误:格式不佳”。
|
11天前
|
存储 JSON JavaScript
「Python系列」Python JSON数据解析
在Python中解析JSON数据通常使用`json`模块。`json`模块提供了将JSON格式的数据转换为Python对象(如列表、字典等)以及将Python对象转换为JSON格式的数据的方法。
28 0
|
15天前
|
存储 JSON 数据挖掘
python逐行读取txt文本中的json数据,并进行处理
Python代码示例演示了如何读取txt文件中的JSON数据并处理。首先,逐行打开文件,然后使用`json.loads()`解析每一行。接着,处理JSON数据,如打印特定字段`name`。异常处理包括捕获`JSONDecodeError`和`KeyError`,确保数据有效性和字段完整性。将`data.txt`替换为实际文件路径运行示例。
12 2
|
1月前
|
JSON 数据格式
糊涂工具类(hutool)post请求设置body参数为json数据
糊涂工具类(hutool)post请求设置body参数为json数据
34 1
|
1月前
|
JSON 前端开发 数据格式
Ajax传递json数据
Ajax传递json数据
11 0
|
1月前
|
JSON 并行计算 API
使用CJSON/Nlohmann:快速简便地在C/C++中处理JSON数据
使用CJSON/Nlohmann:快速简便地在C/C++中处理JSON数据
116 0
|
1月前
|
JSON 数据格式 Python
Python生成JSON数据
Python生成JSON数据
23 0
|
1月前
|
JSON 数据可视化 Linux
数据可视化工具JSON Crack结合内网穿透实现公网访问
数据可视化工具JSON Crack结合内网穿透实现公网访问
数据可视化工具JSON Crack结合内网穿透实现公网访问
|
2月前
|
JSON fastjson Java
FastJSON操作各种格式的JSON数据
FastJSON处理各种格式的JSON数据