springmvc ajax請求以及json

菜雞03號發表於2016-08-26

     

1.使用json格式資料進行前臺與後臺間資料傳遞

需要匯入的包:jackson-core-asl-1.9.13.jar     jackson-mapper-asl-1.9.13.jar

需要配置:

在jsp中加:
 <%
 String path = request.getContextPath();
 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 %>
 <!-- base需要放到head中 --> 
 <base href=" <%=basePath%>"> 
在web.xml配置中:
 <servlet-mapping>
 <servlet-name>名字</servlet-name>
 <!-- 這裡可以用 / 但不能用 /* ,攔截了所有請求會導致靜態資源無法訪問,所以要在spring3-servlet.xml中配置mvc:resources -->
 <url-pattern>/</url-pattern>
 </servlet-mapping>


在MVC.XML中配置:

<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
       <property name="supportedMediaTypes">
           <list>
               <value>application/json;charset=UTF-8</value>
           </list>
       </property>     
       <property name="objectMapper">
           <bean class="org.codehaus.jackson.map.ObjectMapper">
               <property name="dateFormat">
                   <bean class="java.text.SimpleDateFormat">
                       <constructor-arg index="0" type="java.lang.String" value="yyyy-MM-dd HH:mm:ss"/>
                   </bean>
               </property>
           </bean>
       </property>
     </bean>
     <bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter"/>
     <bean id="requestMappingHandlerAdapter" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
       <property name="messageConverters">
           <list>
               <ref bean="mappingJacksonHttpMessageConverter"/>
               <ref bean="stringHttpMessageConverter"/>
           </list>
       </property>
     </bean>


相關文章