SpringMVC从Controller中获取json数据

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>

):

  项目截图:

 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值