spring中使用json问题

1)添加包:

json解析用到的包:核心包json-lib-2.2.3-jdk15,核心包用到的包ezmorph-1.0.6

spring中的视图解析:json-lib-ext-spring-1.0.2,这是官方提供的,也可以自己写个。

2)问题:即使使用了spring字符过滤器,在Controller里设置字符类型,仍然呈现乱码

3)猜测原因:HttpServletResponse被多次包装过程中可能发生字符转换导致。

4)解决:在最后的端点设置编码。

 

5)经验:在始点和终点设置编码,不理会中间过程怎么处理。同理当我们遇到多样化的字符串处理时,把变花样放在终点。

 

6)代码:

a.配置:

 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

 <bean name="/jsonView.htm" class="org.sea.content.web.view.JsonView"/>
    <bean id="manageProject" class="org.sea.content.web.view.manageProject">
        <property name="sessionForm">
            <value>true</value>
        </property>
        <property name="commandClass">
            <value>org.sea.content.model.Project</value>
        </property>
        <property name="formView">
            <value>manageProject</value>
        </property>
        <property name="successView" value="jsonView"/>
    </bean>

 

b.manageProject.java

public class manageProject extends SimpleFormController {
      protected final Log logger = LogFactory.getLog(getClass());

    protected ModelAndView onSubmit(Object command) throws Exception {
        Project model =(Project)command;
        model.setProjectTime(String.valueOf(System.currentTimeMillis()));
        logger.debug("-------------------------->model"+model.getProjectName());
         JSONObject object=   JSONObject.fromObject(model);
      
         logger.debug("-------------------------->model"+object.toString());
        return new ModelAndView(getSuccessView(), "model", object.toString());
    }
}

 

c.jsonView.jsp 所有的有关json的返回都是用这个jsp.

<%response.setHeader("Charset","UTF-8");

PrintWriter pw=   response.getWriter();
    pw.write((String)request.getAttribute("model"));
%>

 

d.org.sea.content.web.view.JsonView拷贝自json官方的:

 

package org.sea.content.web.view;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 2009-3-30
 * Time: 21:39:23
 * To change this template use File | Settings | File Templates.
 */
import java.util.Map;

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

import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;
import net.sf.json.filters.OrPropertyFilter;

import org.springframework.web.servlet.view.AbstractView;

/**
 * A View that renders its model as a JSON object.
 *
 * @author Andres Almiray <aalmiray@users.sourceforge.net>
 */
public class JsonView extends AbstractView {
   /** Default content type. Overridable as bean property. */
   private static final String DEFAULT_JSON_CONTENT_TYPE = "application/json";
   private boolean forceTopLevelArray = false;
   private boolean skipBindingResult = true;
   /** Json confiiguration */
   private JsonConfig jsonConfig = new JsonConfig();

   public JsonView() {
      super();
      setContentType( DEFAULT_JSON_CONTENT_TYPE );
   }

   public JsonConfig getJsonConfig(){
      return jsonConfig;
   }

   public boolean isForceTopLevelArray() {
      return forceTopLevelArray;
   }

   /**
    * Returns whether the JSONSerializer will ignore or not its internal property
    * exclusions.
    */
   public boolean isIgnoreDefaultExcludes() {
      return jsonConfig.isIgnoreDefaultExcludes();
   }

   /**
    * Returns whether the JSONSerializer will skip or not any BindingResult related keys on the model.<p>
    * Models in Spring >= 2.5 will cause an exception as they contain a BindingResult that cycles back.
    */
   public boolean isSkipBindingResult() {
      return skipBindingResult;
   }

   /**
    * Sets the group of properties to be excluded.
    */
   public void setExcludedProperties( String[] excludedProperties ) {
      jsonConfig.setExcludes( excludedProperties );
   }

   public void setForceTopLevelArray( boolean forceTopLevelArray ) {
      this.forceTopLevelArray = forceTopLevelArray;
   }

   /**
    * Sets whether the JSONSerializer will ignore or not its internal property
    * exclusions.
    */
   public void setIgnoreDefaultExcludes( boolean ignoreDefaultExcludes ) {
      jsonConfig.setIgnoreDefaultExcludes( ignoreDefaultExcludes );
   }

   public void setJsonConfig( JsonConfig jsonConfig ) {
     this.jsonConfig = jsonConfig != null ? jsonConfig : new JsonConfig();
     if( skipBindingResult ){
        PropertyFilter jsonPropertyFilter = this.jsonConfig.getJsonPropertyFilter();
        if( jsonPropertyFilter == null ) {
           this.jsonConfig.setJsonPropertyFilter( new BindingResultPropertyFilter() );
        }else{
           this.jsonConfig.setJsonPropertyFilter( new OrPropertyFilter(new BindingResultPropertyFilter(), jsonPropertyFilter) );
        }
     }
   }

   /**
    * Sets whether the JSONSerializer will skip or not any BindingResult related keys on the model.<p>
    * Models in Spring >= 2.5 will cause an exception as they contain a BindingResult that cycles back.
    */
   public void setSkipBindingResult( boolean skipBindingResult ) {
      this.skipBindingResult = skipBindingResult;
   }

   /**
    * Creates a JSON [JSONObject,JSONArray,JSONNUll] from the model values.
    */
   protected JSON createJSON( Map model, HttpServletRequest request, HttpServletResponse response ) {
      return defaultCreateJSON( model );
   }

   /**
    * Creates a JSON [JSONObject,JSONArray,JSONNUll] from the model values.
    */
   protected final JSON defaultCreateJSON( Map model ) {
      if( skipBindingResult && jsonConfig.getJsonPropertyFilter() == null ){
         this.jsonConfig.setJsonPropertyFilter( new BindingResultPropertyFilter() );
      }
      return JSONSerializer.toJSON( model, jsonConfig );
   }

   /**
    * Returns the group of properties to be excluded.
    */
   protected String[] getExcludedProperties() {
      return jsonConfig.getExcludes();
   }

   protected void renderMergedOutputModel( Map model, HttpServletRequest request,
         HttpServletResponse response ) throws Exception {
      response.setContentType( getContentType() );
      writeJSON( model, request, response );
   }

   protected void writeJSON( Map model, HttpServletRequest request,
         HttpServletResponse response ) throws Exception {
      JSON json = createJSON( model, request, response );
      if( forceTopLevelArray ){
         json = new JSONArray().element(json);
      }
      json.write( response.getWriter() );
   }

   private static class BindingResultPropertyFilter implements PropertyFilter {
      public boolean apply( Object source, String name, Object value ) {
         return name.startsWith("org.springframework.validation.BindingResult.");
      }
   }
}
 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值