1. 程式人生 > >spring註解@ResponseBody處理ajax請求,json資料型別

spring註解@ResponseBody處理ajax請求,json資料型別

           最近做了一個spring+ajax 二級級聯選單,總是報各種錯誤,最後經過分析總結終於解決此問題,現在把問題展示給大家,以供分享。如有問題可以評論,肯定支援。

json需要引用的JSON包有:jackson-core-asl-1.9.13.jar,jackson-mapper-asl-1.9.13.jar,版本並不是固定的,只是這兩個的版本一樣就行了

         controller層:

@RequestMapping(value = "branchMap")
 @ResponseBody
 public List<Temp> getBranchMap(HttpServletRequest request) {
  String tmp = request.getParameter("organizid");
  Long id = Long.parseLong(tmp);
  return serviceManager.getBranchMap(id);
 }

         service層:

public List<Temp> getBranchMap(Long id) {
  return institutionsDao.getBranchMap(id);
 }

         dao層:(其中Temp是臨時類,就是institutions類想要的欄位組成的類)

 public List<Temp> getBranchMap(Long id) {
  List<Temp> lt = new ArrayList<Temp>();
  String sql = "select s.id,s.name from institutions s where s.parent=?";
  Session session = this.getSession();
  SQLQuery sqlQuery = session.createSQLQuery(sql);
  sqlQuery.setLong(0, id);
  sqlQuery.addScalar("id", Hibernate.LONG);
  sqlQuery.addScalar("name", Hibernate.STRING);
  sqlQuery.setResultTransformer(Transformers
    .aliasToBean(Institutions.class));
  List<Institutions> list = sqlQuery.list();
  if (list.size() <= 0) {
   Temp t = new Temp();
   t.setId(0L);
   if (id == -1) {
    t.setName("請先選擇機構");
   } else {
    t.setName("該機構沒有分支");
   }
   lt.add(t);
   return lt;
  }
  for (int i = 0; i < list.size(); i++) {
   Institutions ins = list.get(i);
   Temp t = new Temp();
   t.setId(ins.getId());
   t.setName(ins.getName());
   lt.add(t);
  }
  return lt;
 }

       jsp層:

       var val=$("#organization option:selected").val();
       $.ajax({
           type:"post",
           url:"${ctx}/account/user/branchMap",
           dataType:"json",
           async:false,
           data:{organizid:val},
           success:function(data){
            $("#branch").html("");
               $.each(data,function(i,item){
                   $("#branch").append("<option value="+item.id+">"+item.name+"</option>");
               });
           }
       });

然後在對應的spring-mvc.servlet.xml中新增配置

<!--
  @ResponseBody之後返回字串中中文可能會出現亂碼 因為sping
  mvc預設是text/plain;charset=ISO-8859-1,要支援中需做如下配置指定編碼格式
 -->

 <bean
  class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
  <property name="messageConverters">
   <list>
    <bean
     class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
     <property name="supportedMediaTypes">
      <list>
       <!--返回字串格式json-->
       <value>application/json;charset=UTF-8</value>
      </list>
     </property>
    </bean>
   </list>
  </property>
 </bean>

只要後臺查詢查詢的結果集是list<XXX>泛型的list集合然後把controller層標註上 @ResponseBody,前臺呼叫此方法,並在$.ajax中標示為dataType:"json",  async:false,即可。