springmvc--处理器的返回参数

ModelAndView

返回视图和数据模型

字符串

返回内部资源逻辑视图名

    @RequestMapping("/first.do")
    public String dealDo(String name,Integer age)  {
        
        return "show";
    }

void

ajax 请求

需要:1加入包

   2在springmvc配置文件中加入 注解驱动 <mvc:annotation-driven/>

      3 在处理器方法上加 @ResponseBody 

<%@ 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=ISO-8859-1">
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
    $(function(){
        
        $("#button").click(
        function(){
            $.ajax(
            {
                url:"first.do",
                name:"a",
                data:{
                     name:"zhangsan",
                    age:"20"
                },
                type:"post",
                dataType:"json",
                success:function(resp){
                    alert("resp:"+resp.name+"  "+resp.age);
                }
            }        
            )
        }        
        )
    }
    
    )

</script>
<title>Insert title here</title>
</head>
<body>

    index.jsp<br>
    <!-- <a href="hello.do">发起用户请求</a> <br>
    <img alt="图片信息" src="imagew/22.png"> -->
    <!-- <form action="first.do" method="post">
        姓名: <input type="text" name="name"><br>
        年龄: <input type="text" name="age"><br>
         <input type="submit" value="post请求"><br>
    
    </form> -->
    
    <input id="button" type="submit" value="请求">
</body>
</html>

    @RequestMapping("/first.do")
    @ResponseBody
    // 作用把HttpMessageConverter接口转换过的诗句,通过 HttpServletResponse 输出给浏览器
  //MappingJackson2HttpMessageConverter 负责读取和写入json格式的数据。利用Jackson 的 ObjectMapper读写。可读取 application/json的数据,响应类型也为
application/json

public void first(String name, Integer age, HttpServletResponse response) throws JsonGenerationException, JsonMappingException, IOException { Student s = new Student(); s.setName(name); s.setAge(age); // 调用Jackson的 ObjectMapper 处理java对象 ObjectMapper mapper = new ObjectMapper(); // 输出给浏览器 mapper.writeValue(response.getOutputStream(), s); }

 

 

一般是包不兼容。

 降低包的版本。

对象

处理器方法返回对象(Object),表示返回数据。对象的范围比较广泛,integer,String,自定义的对象 都是。

对象有属性,属性值是返回给浏览器的数据。

处理流程:按照数据类型调用HttpMessageConverter的实现类。例如String 的对应实现类:StringHttpMessageConverter

    把返回值转换成需要的数据格式。

    使用@ResponseBody ,把转换后的数据通过HttpServletResponse 的输出,输出到响应体中,即输出给浏览器。

返回字符串

    //produces 指定应答的数据类型和编码格式
    @RequestMapping(value="/first1.do",produces="text/plan;charset=utf-8")
    //返回是String 表示给浏览器提供的数据
    @ResponseBody
    public String dealDo(String name, Integer age) {
        return "hello,北京";
    }
text/html 表示数据类型文本,可能含有html标签
text/plan 表示纯文本。
原文地址:https://www.cnblogs.com/llq1214/p/11636497.html