The SSM framework implements Ajax to send requests and process return data in JSON format

1. Package and related library configuration

To implement JSON, related packages must be introduced. For the download address, please refer to this blog:
https://blog.csdn.net/salonzhou/article/details/36682981
In addition, jQuery should also be introduced in JSP or HTML pages

2. Spring basic configuration (only necessary beans are listed)

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">   
    <property name="messageConverters">  
        <list>  
            <ref bean="mappingJacksonHttpMessageConverter" />  
        </list>  
    </property>  
</bean>   

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" />  

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

<bean id="propertyConfigurer" 
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:*.properties</value>
        </list>
    </property>
</bean>

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
          <list>
               <ref bean="mappingJacksonHttpMessageConverter" />
          </list>
    </property>
</bean>


<bean id="mappingJacksonHttpMessageConverter" 
    class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">  
    <property name = "supportedMediaTypes">  
        <list>  
            <bean class="org.springframework.http.MediaType">  
                <constructor-arg index="0" value="text"/>  
                <constructor-arg index="1" value="plain"/>  
                <constructor-arg index="2" value="UTF-8"/>  
            </bean>  
            <bean class="org.springframework.http.MediaType">  
                <constructor-arg index="0" value="*"/>  
                <constructor-arg index="1" value="*"/>  
                <constructor-arg index="2" value="UTF-8"/>  
            </bean>  
            <bean class="org.springframework.http.MediaType">  
                <constructor-arg index="0" value="text"/>  
                <constructor-arg index="1" value="*"/>  
                <constructor-arg index="2" value="UTF-8"/>  
            </bean>  
            <bean class="org.springframework.http.MediaType">  
                <constructor-arg index="0" value="application"/>  
                <constructor-arg index="1" value="json"/>  
                <constructor-arg index="2" value="UTF-8"/>  
            </bean>  
        </list>  
    </property>  
</bean>   

3. JSP page

Here is a demonstration: when an ISBN is entered in an input box, when the input box loses focus, the relevant information of the book is immediately queried and displayed on the page without refreshing the entire page

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>添加书籍</title>
</head>
<body>
    <script type="text/javascript">
        var sysMsg = "${sysMsg}";
        if(sysMsg != "") alert(sysMsg);
    </script>

    <table>
        <td>ISBN:</td>
        <td><input type="text" name="isbn" id="bookIsbn"/></td>
    </table>
    <p>书名:<div id="bookMsg"></div></p>
    <p>持有量:<div id="bookHave"></div></p>

    <!--必须要先引入jQuery库-->
    <script type="text/javascript" src="/library/js/jquery-1.4.4.min.js"></script>
    <script>
        $(function(){
            $("#bookIsbn").blur(function(){
                $.ajax({
                    //发送请求URL,可使用相对路径也可使用绝对路径
                    url:"findBook.do",
                    //发送方式为GET,也可为POST,需要与后台对应
                    type:"GET",
                    //设置接收格式为JSON
                    dataType:"json",
                    //编码设置
                    contentType:"application/json;charset=utf-8",
                    //向后台发送的数据
                    data:{
                        isbn:$("#bookIsbn").val(),
                    },
                    //后台返回成功后处理数据,data为后台返回的json格式数据
                    success:function(data){
                        if(data != null){
                            $("#bookName").val(data.name);
                            $("#bookHave").val(data.haveNum);
                        }
                        else{
                            $("#bookName").val("该书籍不存在");
                        }
                    }
                    //查询错误处理
                    error:function(){
                        $("#bookName").val("查询异常");
                    }
                });
            });
        });

    </script>
</body>
</html>

Fourth, the controller part

The controller method that processes JSON needs to be decorated with @ResponseBody annotation, which will automatically return the variables in the book instance in json format
. The parameters in @RequestParam must correspond to the data in $.ajax()

@ResponseBody
@RequestMapping("/findBook.do")
public Book checkBook(@RequestParam("isbn")String isbn)
{
    SqlSession sqlSession = MyBatisUtil.getSqlSessionFactory().openSession();
    Book book = null;
    try
    {
        BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);
        book = bookMapper.selectBookByISBN(isbn);
        log.info("查询书籍成功");
    }
    catch(Exception e)
    {
        log.error("异常:", e);
    }
    finally
    {
        sqlSession.close();
        log.info("SQLsession已关闭");
    }
    return book;
}

Book entity class

package com.library.entity;

public class Book implements java.io.Serializable 
{
    private static final long serialVersionUID = -8784440456544318126L;

    private Integer id;
    private String name;
    private String isbn;
    private Integer haveNum;
    //省略构造器及getter、setter方法
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326114259&siteId=291194637