Springmvc中ajax與jason應用

Springmvc中ajax與jason應用

相關依賴包

json數據轉換的jar包javascript

jackson-annotations-2.5.4
jackson-core-2.5.4
jackson-databind-2.5.4html

spring以及spring的依賴包java

bean context aop context core web webmvc expressionjquery

未涉及json的ajax請求

簡單的表單驗證git

Controller層java代碼

@Controller
public class AjaxCtrl {
    @RequestMapping("/toAjax.do")
    public String toAjax() {
        return "ajax";
    }
    @RequestMapping("/ajax.do")
    @ResponseBody
    public void ajaxJson(@RequestParam("name")String name,HttpServletResponse resp) throws IOException {
        PrintWriter out = resp.getWriter();
        if(name.equals("hm"))
            out.print("該用戶已註冊");
        else
            out.print("該用戶可以使用");
    }

注意點:github

  • 在手動調用getWriter()方法時不能夠再添加返回值,不然tomcat會報錯(getWriter()方法已存在)。由於在返回值處容器會自動調用getWriter()方法來輸出內容,而檢測到前面getWriter()已經被調用過,產生衝突。
  • 解決:1. 像上面的代碼不給出返回值;2. resp.reset(); resp.setContentType("text/html; charset=utf-8"); out.flush; out.close();
  • @ResponseBody會將返回的數據自動轉換爲json格式的數據web

    相關jsp代碼:ajax.jsp

<script src="${pageContext.request.contextPath }/js/jquery-2.1.0.min.js" type="text/javascript"></script>
</head>
<body>
    姓名:<input type="text" id="field" name="name" /><span id="txt"></span>
    <script type="text/javascript">
        $("#field").blur(function(){
            $.post("ajax.do",{'name':$('#field').val()},function(result){
                $("#txt").html(result);
            });
        });
    </script>
</body>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">
    <display-name>springmvc_ajax</display-name>
    <filter>
        <filter-name>characterencoding</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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterencoding</filter-name>
        <url-pattern>*.do</url-pattern>
    </filter-mapping>
    <servlet>
        <servlet-name>ajax</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>ajax</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>

涉及json格式數據的ajax請求

Controller層java代碼

@RequestMapping("/toAjaxJson.do")
    public String toAjaxJson() {
        return "ajaxJson";
    }
    @RequestMapping("/ajaxJson.do")
    @ResponseBody
    public List<User> ajaxJson() {
        List<User> list = new ArrayList<User>();
        list.add(new User(1, "xb", "123"));
        list.add(new User(2, "xc", "234"));
        list.add(new User(3, "xd", "345"));
        list.add(new User(4, "xa", "456"));
        return list;
    }

相關jsp代碼:ajaxJson.jsp

<input type="button" id="btn" value="獲取json數據">
    <table  width="80%" align="center">
        <tr>
            <th>編號</th>
            <th>姓名</th>
            <th>密碼</th>
        </tr>
        <tbody id="content"></tbody>
    </table>
    <script type="text/javascript">
    $(function(){
        $("#btn").click(function(){
            $.get("ajaxJson.do",function(list){
                var field = "";
                for (var i = 0; i < list.length; i++) {
                    field +="<tr><td>"+list[i].id+"</td>"+"<td>"+list[i].name+"</td>"+"<td>"+list[i].passwd+"</td></tr>";
                }
                $("#content").html(field);
            });
        });
    });
    </script>

springmvc的核心配置文件:mvc.xml

<?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/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
    <!-- 開啓mvc的註解 -->
    <mvc:annotation-driven />
    <!-- 掃描包 -->
    <context:component-scan base-package="com.zrm.controller"></context:component-scan>
    <!-- 配置視圖解析器 -->
    <bean id="InternalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <bean id="stringConverter" class="org.springframework.http.converter. StringHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/plain;charset=UTF-8</value>
            </list>
        </property>
    </bean>
    <bean id="jsonConverter" class="org.springframework.http.converter.json. "></bean>
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="stringConverter"/>
                <ref bean="jsonConverter"/>
            </list>
        </property>
    </bean> 
</beans>

相關類的介紹

StringHttpMessageConverter

官方文檔:
An HttpMessageConverter implementation that can read and write Strings from the HTTP request and response. By default, this converter supports all text media types (text/*), and writes with a Content-Type of text/plain.ajax

譯文:
一種HttpMessageConverter能夠從HTTP請求和響應中讀取和寫入字符串的實現。默認狀況下,此轉換器支持全部文字媒體類型(text/*),並用Content-Type中的text/plain類型。spring

MappingJackson2HttpMessageConverter

官方文檔:
An HttpMessageConverter implementation that can read and write JSON using Jackson’s ObjectMapper. JSON mapping can be customized as needed through the use of Jackson’s provided annotations. When further control is needed, a custom ObjectMapper can be injected through the ObjectMapper property for cases where custom JSON serializers/deserializers need to be provided for specific types. By default this converter supports ( application/json).express

譯文:
一個HttpMessageConverter能夠使用Jackson庫提供的ObjectMapper類來讀取和寫入json格式的數據。能夠根據須要經過使用Jackson庫提供的註解來自定義XML映射。當須要進一步控制時,XmlMapper 能夠經過ObjectMapper屬性注入自定義,以用於須要爲特定類型提供自定義XML序列化器/反序列化器的狀況。默認狀況下,此轉換器支持(application/xml)。

ObjectMapper是Jackson庫的主要類,他提供的一些功能用於將Java對象轉換爲符合jason結構的字符串。

AnnotationMethodHandlerAdapter

注入了AnnotationMethodHandlerAdapter做用是對有RequestMapping註解的控制器進行HTTP路徑、HTTP方法和請求參數解析.

項目結構

ajaxJson

項目源碼已上傳至 github ajaxJson

相關文章
相關標籤/搜索