springmvc中ajax处理

1.使用HttpServletResponse处理--不需要配置解析器

@Controller
public class AjaxController {
    @RequestMapping("/ajax")
    public void ajax(String name,HttpServletResponse resp) throws IOException{ 
        if("123".equals(name)){
            resp.getWriter().println("true");
        }else{
            resp.getWriter().println("false");
        }
    }
}

 

2.springmvc处理json数据

a)导入jar

jackson-annotations-2.8.5.jar

jackson-core-2.8.5.jar

jackson-databind-2.8.5.jar

b)  配置json转换器

 

<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.MappingJackson2HttpMessageConverter"></bean>
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="stringConverter" />
                <ref bean="jsonConverter" />
            </list>
        </property>
    </bean>

 

c)Controller代码

 

public class JsonController {
    @RequestMapping("/json")
    @ResponseBody
    public List<User> json(){
        List<User> list = new ArrayList<User>();
        list.add(new User(1,"lisan","male"));
        list.add(new User(2,"lisan1","male"));
        list.add(new User(3,"lisan2","male"));
        return list;
    }
}

 

d)jsp代码

 

<%@ 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>
<script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
    $(function(){
        $("#btn").click(function(){
            $.post("json.do",function(data){
                var html = "";
                for(var i=0;i<data.length;i++){
                    html+="<tr><td>"+data[i].id+"</td><td>"+data[i].name+"</td><td>"+data[i].sex+"</td></tr>";
                }
                $("#content").html(html);    
            });
        });
    });
</script>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<input id="btn" value="get data" type="button"/>
<table width="50%" align="center">
    <tr>
        <td>id</td>
        <td>name</td>
        <td>sex</td>
    </tr>
    <tbody id="content">
    
    </tbody>
    
</table>
</body>
</html>

 

 

 

 

 

 

posted @ 2017-01-28 19:36  Realvie  阅读(623)  评论(0编辑  收藏  举报