`

四. Spring MVC 3 支持json及 常见错误解决

 
阅读更多

spring3 已经集成了jackson,本身支持页面的ajax获取数据。在版本中我们无需任何配置,只需下载jackson-all的包,放置在lib目录中,在controller中采用@ResponseBody 标记,就可以直接把Map,list 及各种对象直接转换为json对象的形式展现在前端。

1、spring3支持的各种类型转换为json对象的实例如下

在controller层中我们设置如下4种类型,分别是异常信息(结合上篇文章),Map,List及object对象,controller层代码如下:

package com.jason.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jason.domain.User;
import com.jason.exception.BusinessException;
import com.jason.service.UserService;
import com.jason.util.Constants;
import com.jason.web.dto.LoginCommand;

@Controller
public class LoginController {

	@Autowired
	private UserService userService;

	/**
	 * jump into the login page
	 * 
	 * @return
	 * @throws BusinessException
	 * @throws
	 * @throws BusinessException
	 */
	@RequestMapping(value = "/index.html")
	public String loginPage() throws BusinessException {
		return Constants.LOGIN_PAGE;
	}

	/**
	 * get the json object
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/josonException.html")
	public @ResponseBody
	Map<String, Object> getjson() throws BusinessException {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			map.put("content", "123");
			map.put("result", true);
			map.put("account", 1);
			throw new Exception();
		} catch (Exception e) {
			throw new BusinessException("detail of ajax exception information");
		}
	}

	/**
	 * get the json object
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/josonMap.html")
	public @ResponseBody Map<String, Object> getjsonMap() throws BusinessException {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("content", "123");
		map.put("result", true);
		map.put("account", 1);
		return map;
	}
	
	/**
	 * get the json object
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/josonList.html")
	public @ResponseBody List getjsonList() throws BusinessException {
		LoginCommand loginCommand = new LoginCommand();
		loginCommand.setUserName("admin");
		loginCommand.setPassword("123456");
		loginCommand.setKaptchaCode("9943");
		List list = new ArrayList();
		list.add(0,loginCommand);
		list.add(1,loginCommand);
		list.add(2,loginCommand);
		list.add(3,loginCommand);
		list.add(4,loginCommand);
		list.add(5,loginCommand);
		return list;
	}
	
	/**
	 * get the json object
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/josonObject.html")
	public @ResponseBody LoginCommand getjsonObject() throws BusinessException {
		LoginCommand loginCommand = new LoginCommand();
		loginCommand.setUserName("admin");
		loginCommand.setPassword("123456");
		loginCommand.setKaptchaCode("9943");
		return loginCommand;
	}
	/**
	 * login in operation
	 * 
	 * @param request
	 * @param loginCommand
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/login.html")
	public ModelAndView loginIn(HttpServletRequest request,
			HttpServletResponse respone, LoginCommand loginCommand)
			throws IOException {

		boolean isValidUser = userService.hasMatchUser(
				loginCommand.getUserName(), loginCommand.getPassword());
		boolean isValidateCaptcha = validateCaptcha(request, loginCommand);

		ModelAndView modeview = new ModelAndView(Constants.LOGIN_PAGE);

		if (!isValidUser) {
			// if have more information,you can put a map to modelView,this use
			// internalization
			modeview.addObject("loginError", "login.user.error");
			return modeview;
		} else if (!isValidateCaptcha) {
			// if have more information,you can put a map to modelView,this use
			// internalization
			modeview.addObject("loginError", "login.user.kaptchaError");
			return modeview;
		} else {
			User user = userService.findUserByUserName(loginCommand
					.getUserName());
			user.setLastIp(request.getLocalAddr());
			user.setLastVisit(new Date());

			userService.loginSuccess(user);

			// we can also use
			request.getSession().setAttribute(Constants.LOGINED, user);
			String uri = (String) request.getSession().getAttribute(
					Constants.CURRENTPAGE);
			if (uri != null
					&& !StringUtils.equalsIgnoreCase(uri,
							Constants.CAPTCHA_IMAGE)) {
				respone.sendRedirect(request.getContextPath() + uri);
			}
			return new ModelAndView(Constants.FRONT_MAIN_PAGE);
		}
	}

	/**
	 * logout operation
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/logout.html")
	public ModelAndView logout(HttpServletRequest request,
			HttpServletResponse response) {

		/*
		 * HttpServletRequest.getSession(ture) equals to
		 * HttpServletRequest.getSession() means a new session created if no
		 * session exists request.getSession(false) means if session exists get
		 * the session,or value null
		 */
		HttpSession session = request.getSession(false);

		if (session != null) {
			session.invalidate();
		}

		return new ModelAndView("redirect:/index.jsp");
	}

	/**
	 * check the Captcha code
	 * 
	 * @param request
	 * @param command
	 * @return
	 */
	protected Boolean validateCaptcha(HttpServletRequest request, Object command) {
		String captchaId = (String) request.getSession().getAttribute(
				com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		String response = ((LoginCommand) command).getKaptchaCode();
		if (!StringUtils.equalsIgnoreCase(captchaId, response)) {
			return false;
		}
		return true;
	}
}

   页面配置如下:分别测试异常,map,list及对象

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ include file="/common/taglibs.jsp"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>spring login information</title>
  <script type="text/javascript">
  	function ajaxTestException()
  	{
  		$.ajax( {
			type : 'GET',
			//contentType : 'application/json',   
			url : '${basePath}/josonException.html',   
			async: false,//禁止ajax的异步操作,使之顺序执行。
			dataType : 'json',
			success : function(data,textStatus){
				alert(JSON.stringify(data));
			},
			error : function(data,textstatus){
				alert(data.responseText);
			}
		});
  	}
  	function ajaxTestMap()
  	{
  		$.ajax( {
			type : 'GET',
			//contentType : 'application/json',   
			url : '${basePath}/josonMap.html',   
			async: false,//禁止ajax的异步操作,使之顺序执行。
			dataType : 'json',
			success : function(data,textStatus){
				alert(JSON.stringify(data));
			},
			error : function(data,textstatus){
				alert(data.responseText);
			}
		});
  	}
  	function ajaxTestList()
  	{
  		$.ajax( {
			type : 'GET',
			//contentType : 'application/json',   
			url : '${basePath}/josonList.html',   
			async: false,//禁止ajax的异步操作,使之顺序执行。
			dataType : 'json',
			success : function(data,textStatus){
				alert(JSON.stringify(data));
			},
			error : function(data,textstatus){
				alert(data.responseText);
			}
		});
  	}
  	
  	function ajaxTestObject()
  	{
  		$.ajax( {
			type : 'GET',
			//contentType : 'application/json',   
			url : '${basePath}/josonObject.html',   
			async: false,//禁止ajax的异步操作,使之顺序执行。
			dataType : 'json',
			success : function(data,textStatus){
				alert(JSON.stringify(data));
			},
			error : function(data,textstatus){
				alert(data.responseText);
			}
		});
  	}
  </script>
 </head>
 <body>
	<table cellpadding="0" cellspacing="0" style="width:100%;">
	  <tr>
	      <td rowspan="2" style="width:30px;">
	      </td>
	      <td style="height:72px;">
	          <div>
	              spring login front information
	          </div>
	          <div>
	               ${loginedUser.userName},欢迎您进入Spring login information,您当前积分为${loginedUser.credits};
	          </div>
	          <div>
            	<a href="${basePath}/backendmain.html">后台管理</a>
           	 </div>
	      </td>
	      <td>
    	  	<div>
            <a href="${basePath}/logout.html">退出</a>
           </div>
	     </td>
	  </tr>
	  <tr>
	  	 <td style="height:72px;">
	          <div>
            	<input type=button value="Ajax Exception Test" onclick="ajaxTestException();"></input>
           	 </div>
	      </td>
	      	 <td style="height:72px;">
	          <div>
            	<input type=button value="Ajax Map Test" onclick="ajaxTestMap();"></input>
           	 </div>
	      </td>
	      	 <td style="height:72px;">
	          <div>
            	<input type=button value="Ajax List Test" onclick="ajaxTestList();"></input>
           	 </div>
	      </td>
	      	 <td style="height:72px;">
	          <div>
            	<input type=button value="Ajax Object Test" onclick="ajaxTestObject();"></input>
           	 </div>
	      </td>
	  </tr>
	</table>
 </body>
</html>

 运行代码,到达登录成功界面及获取的结果如下:



 

 

 

 

2、集成Json对象时,常常会抛如下的406错误:The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ()。

      针对这个问题,网络上有好多的答案,五花八门,其实这个本身是spring的bug导致,在spring的rc版本中都会出现这个问题,而不能支持ajax方式,而不是jackson.jar的问题。目前,解决这个问题的spring版本是3.1.1 release版本。而目前最新的spring rc版本仍然存在这个问题。

 

至此,spring3支持json方式介绍到这里。

 

 

 

  • 大小: 32.5 KB
  • 大小: 40.8 KB
  • 大小: 45.1 KB
  • 大小: 58.8 KB
  • 大小: 46.6 KB
分享到:
评论

相关推荐

    SpringMVCDemo:Spring MVC 框架知识案例

    3.Spring MVC 请求参数的获取案例 4.Spring MVC 域对象共享数据案例 5.Spring MVC @ModelAttribute 注解案例 6.Spring MVC 国际化案例 7.Spring MVC 请求转发与请求重定向案例 8.Spring MVC 下载 Excel 文档的需求...

    org.spring-framework-3.0.4. 所有jar

    org.springframework.aop-3.0.4.RELEASE.jar org.springframework.asm-3.0.4.RELEASE.jar org.springframework.aspects-3.0.4.RELEASE.jar org.springframework.beans-3.0.4.RELEASE.jar org.springframework....

    Java面试题50.Spring MVC的执行流程.mp4

    Java面试题50.Spring MVC的执行流程.mp4

    Spring.MVC-A.Tutorial-Spring.MVC学习指南 高清可复制版PDF

    Spring.MVC-A.Tutorial-Spring.MVC学习指南 高清可复制版PDF

    jdk7-Spring MVC核心包集合.rar

    3.spring-beans-3.2.0.RELEASE.jar 4.spring-context-3.2.0.RELEASE.jar 5.spring-context-support-3.2.0.RELEASE.jar 6.spring-core-3.2.0.RELEASE.jar 7.spring-expression-3.2.0.RELEASE.jar 8.spring-jdbc-3.2.0...

    精通Spring MVC 4

    本书共计10章,分别介绍了快速搭建Spring Web应用、精通MVC结构、URL映射、文件上传与错误处理、创建Restful应用、保护应用、单元测试与验收测试、优化请求、将Web应用部署到云等内容,循序渐进地讲解了Spring MVC4...

    Spring3 MVC Ajax with JSON

    Ajax With Spring 3. Eclipse 工程,包含Web所需要的 所有jar包。 1&gt; ajax 请求。 2&gt; spring 3注解使用 3&gt; mvc:annotation

    spring mvc 3.0.5工程所需包整合

    spring mvc 3.0.5工程所需包,现整理后提供给朋友们下载,免得一个一个的下载。org.springframework.aop-3.0.5.RELEASE.jar,org.springframework.asm-3.0.5.RELEASE.jar,org.springframework.aspects-3.0.5....

    spring MVC配置详解

    spring MVC配置详解

    spring3-miniweb.rar_spring json_spring3_spring3 mvc

    spring MVC 传json的简单实现 很入门 也很实用

    Spring.MVC.A.Tutorial.2nd.Edition.1771970316

    Table of Contents Introduction Chapter 1: The Spring Framework Chapter 2: Model 2 and the MVC Pattern Chapter 3: Introduction to Spring MVC Chapter 4: Annotation-Based Controllers Chapter 5: Data ...

    spring-mock.jar

    Classes contained in spring-mock.jar: org.springframework.mock.jndi.ExpectedLookupTemplate.class org.springframework.mock.jndi.SimpleNamingContext.class org.springframework.mock.jndi....

    spring mvc json&&jackson jquery js

    spring mvc 常用开发框架 jar包 提高开发效率 降低开发难度

    Pro.Spring.MVC.With.Web.Flow.英文版+源码

    Pro.Spring.MVC.With.Web.Flow.英文版+源码

    springmvc01.zip_DEMO_JSON校验_spring mvc

    这个是入门spring mvc的Demo,是我学习spring mvc时写的,实现了spring mvc的输入校验,上传文件,和返回json数据时的配置,感觉对于初学者很有帮助

    Spring+Spring mvc+Hibernate+Bootstrap、企业级员工信息管理系统

    01. 采用后台及前台的 Spring + Spring mvc + Hibernate + Bootstrap 02. 后台全注解式的开发(除了必要的spring和hibernate的xml配置以外) 03. 后台通过自定义注解结合一个访问拦截器实现整个系统的权限控制 04...

    Spring MVC 入门实例

    首先, 我需要在你心里建立起 Spring MVC 的基本概念. 基于 Spring 的 Web 应用程序接收到 http://localhost:8080/hello.do(事实上请求路径是 /hello.do) 的请求后, Spring 将这个请求交给一个名为 helloController ...

    spring MVC 配置文档

    DispatcherServlet 是Spring MVC 的入口 所有进入Spring Web 的 Request 都经过 DispatcherServlet 需要在 web.xml 中注册 DispatcherServlet &lt;servlet&gt; &lt;servlet-name&gt;dispatherContext&lt;/servlet-name&gt; ...

Global site tag (gtag.js) - Google Analytics