ModelAanView:即传递数据,又跳转页面
返回String,只进行页面的跳转工作
void:不能表示数据,也不能表示视图,在处理ajax的时候可以使用void返回值
web.xml:
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
- version="4.0">
-
- <!-- 声明,注册springmvc的核心对象DispatcherServlet-->
- <servlet>
- <servlet-name>myweb</servlet-name>
- <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
-
- <!-- 自定义springmvc读取的配置文件的位置-->
- <init-param>
- <!--springmvc的配置文件属性-->
- <param-name>contextConfigLocation</param-name>
- <!-- 指定自定义文件的位置-->
- <param-value>classpath:springmvc.xml</param-value>
- </init-param>
-
- <!-- 在tomcat启动后,创建Servlet对象
- load-on-startup:表示tomcat启动后创建对象的顺序,它的值是正数,数值越小 tomacat创建对象越早
- -->
- <load-on-startup>1</load-on-startup>
-
- </servlet>
-
- <!-- 所有的*..do请求交给myweb中央处理器处理-->
- <servlet-mapping>
- <servlet-name>myweb</servlet-name>
- <url-pattern>*.do</url-pattern>
- </servlet-mapping>
-
- <!--注册声明过滤器,解决post请求乱码问题-->
- <filter>
- <filter-name>characterEncodingFilter</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>
- <!--强制请求对象(HttpServletRequest)使用encoding编码的值-->
- <init-param>
- <param-name>forceRequestEncoding</param-name>
- <param-value>true</param-value>
- </init-param>
- <!--强制应答对象(HttpServletResponse)使用encoding编码的值-->
- <init-param>
- <param-name>forceReponsetEncoding</param-name>
- <param-value>true</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>characterEncodingFilter</filter-name>
- <!--
- /*:表示强制所有的请求先通过过滤器处理
- -->
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- </web-app>
springmvc.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"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
-
- <!-- 用了注解需要注解扫描器:声明组件扫描器:包扫描-->
- <context:component-scan base-package="com.bjpowernode.controller"/>
-
- <!-- 声明springmvc框架中的视图解析器,帮助开发人员设置视图文件的路径-->
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <!-- 前缀:视图文件的路径-->
- <property name="prefix" value="/WEB-INF/view/"/>
- <!-- 后缀:视图文件的扩展名-->
- <property name="suffix" value=".jsp"/>
- </bean>
-
- </beans>
返回类型为String:
MyController:
- package com.bjpowernode.controller;
-
- import com.bjpowernode.vo.Student;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.servlet.ModelAndView;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpSession;
-
- @Controller
- public class MyController {
-
- //处理器方法返回String
- @RequestMapping(value ="/returnString-view.do") //value里面可以写多个名字进行访问
- public String doReturnView(HttpServletRequest request,String name,Integer age){ //doSome相当于doGet()---调用Service请求处理
- System.out.println("doReturnView,name="+name+" age="+age);//这里先不调用,简化处理
-
- //如果还想存储数据,可以手工去做,我们可以使用request作用域手工添加到request作用域
- request.setAttribute("myname",name);
- request.setAttribute("myage",age);
-
- //show:逻辑视图名称,项目中配置了视图解析器
- //框架对视图执行forword转发操作
- return "show";
- //还可以返回完整路径,不用视图解析器,在配置文件中把视图解析器注释
- //return "/WEB-INF/view/show.jsp";
-
- }
- }
index.xml:
- <%--
- Created by IntelliJ IDEA.
- User: DELL
- Date: 2022/6/7
- Time: 17:37
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
- %>
- <html>
- <head>
- <title>Title</title>
- <base href="<%=basePath%>">
- </head>
- <body>
- <h1>处理器方法返回String表示视图名称</h1>
-
- <form action="returnString-view.do" method="post">
- 姓名:<input type="text" name="name"><br>
- 年龄:<input type="text" name="age"><br>
- <input type="submit" value="提交参数">
- </form>
- </body>
- </html>
show.jsp:
- <%--
- Created by IntelliJ IDEA.
- User: DELL
- Date: 2022/6/7
- Time: 19:01
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
- %>
- <html>
- <head>
- <title>Title</title>
- <base href="<%=basePath%>">
- </head>
- <body>
- <h3>/WEB-INF/view/show.jsp,从request作用域中获取数据</h3>
- <h3>myname数据:${myname}</h3>
- <h3>myage数据:${myage}</h3>
- </body>
- </html>
返回值void:
pom.xml:引入json依赖:
- <?xml version="1.0" encoding="UTF-8"?>
-
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <groupId>com.beijingnode</groupId>
- <artifactId>ch04-return</artifactId>
- <version>1.0-SNAPSHOT</version>
- <packaging>war</packaging>
-
-
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <maven.compiler.source>1.8</maven.compiler.source>
- <maven.compiler.target>1.8</maven.compiler.target>
- </properties>
-
- <dependencies>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.11</version>
- <scope>test</scope>
- </dependency>
- <!-- servlet依赖-->
- <dependency>
- <groupId>javax.servlet</groupId>
- <artifactId>javax.servlet-api</artifactId>
- <version>3.1.0</version>
- <scope>provided</scope>
- </dependency>
-
- <!-- springmvc依赖-->
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>5.2.5.RELEASE</version>
- </dependency>
-
- <!-- Jackson依赖-->
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-core</artifactId>
- <version>2.9.0</version>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- <version>2.9.0</version>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <!-- 编码和编译和JDK版本-->
- <plugin>
- <artifactId>maven-compiler-plugin</artifactId>
- <version>3.1</version>
- <configuration>
- <source>1.8</source>
- <target>1.8</target>
- </configuration>
- </plugin>
- </plugins>
- </build>
- </project>
Student:
- package com.bjpowernode.vo;
- //保存请求参数的一个普通类
- public class Student {
- //属性名和请求中的参数名一样
- private String name;
- private Integer age;
-
- public Student() {
- System.out.println("===Student===的无参构造方法");
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- System.out.println("SetName="+name);
- this.name = name;
- }
-
- public Integer getAge() {
- return age;
- }
-
- public void setAge(Integer age) {
- System.out.println("SetAge="+age);
- this.age = age;
- }
-
- @Override
- public String toString() {
- return "Stuydent{" +
- "name='" + name + '\'' +
- ", age=" + age +
- '}';
- }
- }
MyController:
- package com.bjpowernode.controller;
-
- import com.bjpowernode.vo.Student;
- import com.fasterxml.jackson.core.JsonProcessingException;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.servlet.ModelAndView;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpSession;
- import java.io.IOException;
- import java.io.PrintWriter;
-
- @Controller
- public class MyController {
-
-
- //处理器方法返回String
- @RequestMapping(value ="/returnString-view.do") //value里面可以写多个名字进行访问
- public String doReturnView(HttpServletRequest request,String name,Integer age){ //doSome相当于doGet()---调用Service请求处理
- System.out.println("doReturnView,name="+name+" age="+age);//这里先不调用,简化处理
-
- //如果还想存储数据,可以手工去做,我们可以使用request作用域手工添加到request作用域
- request.setAttribute("myname",name);
- request.setAttribute("myage",age);
-
- //show:逻辑视图名称,项目中配置了视图解析器
- //框架对视图执行forword转发操作
- return "show";
- //还可以返回完整路径,不用视图解析器,在配置文件中把视图解析器注释
- //return "/WEB-INF/view/show.jsp";
-
- }
-
- //处理器方法返回void ,响应ajax请求
- @RequestMapping(value ="/returnVoid-ajax.do") //value里面可以写多个名字进行访问
- public void doReturnVoidAjax(HttpServletResponse response,String name,Integer age) throws IOException { //doSome相当于doGet()---调用Service请求处理
- System.out.println("doReturnVoidAjax,name="+name+" age="+age);//这里先不调用,简化处理
-
- //处理ajax,使用json做数据的格式
- //Service调用完了,使用Student表示处理结果
- Student student=new Student();
- student.setName(name);
- student.setAge(age);
-
- String json="";
- //把结果的对象转为json格式的数据
- if(student!=null){
- ObjectMapper om=new ObjectMapper();
- json= om.writeValueAsString(student);
- System.out.println("Student转换为json=="+json);
- }
-
- //输出数据,响应ajax的请求
- response.setContentType("application/json;charset=utf-8");
- PrintWriter pw=response.getWriter();
- pw.println(json);
- pw.flush();
- pw.close();
-
-
-
- }
- }
index.jsp:
- <%--
- Created by IntelliJ IDEA.
- User: DELL
- Date: 2022/6/7
- Time: 17:37
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
- %>
- <html>
- <head>
- <title>Title</title>
- <base href="<%=basePath%>">
- <script type="text/javascript" src="js/jquery-3.3.1.js"></script>
- <script type="text/javascript">
- $(function(){
- $("button").click(function(){
- //alert("button click");
- $.ajax({
- url:"returnVoid-ajax.do",
- data:{
- name:"zhangsan",
- age:20
- },
- type:"post",
- dataType:"json",
- success:function(resp){
- //resp从服务器返回的是json格式的字符串{"name":"zhangsan","age":20}
- //jquery会把字符串转换为json对象,赋值给resp形参
- alert(resp.name+" "+resp.age);
- }
- })
-
- })
- })
- </script>
- </head>
- <body>
- <h1>处理器方法返回String表示视图名称</h1>
-
- <form action="returnString-view.do" method="post">
- 姓名:<input type="text" name="name"><br>
- 年龄:<input type="text" name="age"><br>
- <input type="submit" value="提交参数">
- </form>
- <br>
- <br>
- <button id="btn">发起ajax请求</button>
- </body>
- </html>
点击发起ajax请求:
Response Header:响应头:
Content-Type:application/json;charset=utf-8 , 值得是我们的Controller向浏览器返回的数据说明,对应:
//输出数据,响应ajax的请求 response.setContentType("application/json;charset=utf-8");
Request Header:请求头:发请求给Controller,附带的一些参数,Controller需要用的话可以取出来的
Accep:application/json,text/javascripot, */*;q=0.01 来自,jquery中:
dataType:"json",//表示希望得到的数据时json格式
在点击发送请求时把json转换为Accep的东西,把它Controller
Response:响应 响应的是一个json
服务器端输出的结果:
PrintWriter pw=response.getWriter(); pw.println(json);
Preview:参数:对应:
data:{ name:"zhangsan", age:20 },
返回对象:
返回对象可以用来响应ajax请求的
不用在做将结果对象转换为json和输出数据,响应ajax,交给框架来处理
springmvc.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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
-
- <!-- 用了注解需要注解扫描器:声明组件扫描器:包扫描-->
- <context:component-scan base-package="com.bjpowernode.controller"/>
-
- <!-- 声明springmvc框架中的视图解析器,帮助开发人员设置视图文件的路径-->
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <!-- 前缀:视图文件的路径-->
- <property name="prefix" value="/WEB-INF/view/"/>
- <!-- 后缀:视图文件的扩展名-->
- <property name="suffix" value=".jsp"/>
- </bean>
-
- <!-- 加上注解驱动-->
- <mvc:annotation-driven/>
- </beans>
MyController:
- package com.bjpowernode.controller;
-
- import com.bjpowernode.vo.Student;
- import com.fasterxml.jackson.core.JsonProcessingException;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.bind.annotation.ResponseBody;
- import org.springframework.web.servlet.ModelAndView;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpSession;
- import java.io.IOException;
- import java.io.PrintWriter;
-
- @Controller
- public class MyController {
-
-
- //处理器方法返回String
- @RequestMapping(value ="/returnString-view.do") //value里面可以写多个名字进行访问
- public String doReturnView(HttpServletRequest request,String name,Integer age){ //doSome相当于doGet()---调用Service请求处理
- System.out.println("doReturnView,name="+name+" age="+age);//这里先不调用,简化处理
-
- //如果还想存储数据,可以手工去做,我们可以使用request作用域手工添加到request作用域
- request.setAttribute("myname",name);
- request.setAttribute("myage",age);
-
- //show:逻辑视图名称,项目中配置了视图解析器
- //框架对视图执行forword转发操作
- return "show";
- //还可以返回完整路径,不用视图解析器,在配置文件中把视图解析器注释
- //return "/WEB-INF/view/show.jsp";
-
- }
-
- //处理器方法返回void ,响应ajax请求
- //手工实现ajax,json数据:代码存在重复:java对象转换为json;通过HttpServletResponse输出json数据
- @RequestMapping(value ="/returnVoid-ajax.do") //value里面可以写多个名字进行访问
- public void doReturnVoidAjax(HttpServletResponse response,String name,Integer age) throws IOException { //doSome相当于doGet()---调用Service请求处理
- System.out.println("doReturnVoidAjax,name="+name+" age="+age);//这里先不调用,简化处理
-
- //处理ajax,使用json做数据的格式
- //Service调用完了,使用Student表示处理结果
- Student student=new Student();
- student.setName(name);
- student.setAge(age);
-
- String json="";
- //把结果的对象转为json格式的数据
- if(student!=null){
- ObjectMapper om=new ObjectMapper();
- json= om.writeValueAsString(student);
- System.out.println("Student转换为json=="+json);
- }
-
- //输出数据,响应ajax的请求
- response.setContentType("application/json;charset=utf-8");
- PrintWriter pw=response.getWriter();
- pw.println(json);
- pw.flush();
- pw.close();
- }
-
-
- //处理器方法返回一个Student,通过框架转为json,响应ajax请求
- //@ResponseBody注解作用:把处理器方法返回的对象转为json后,通过HttpServletResponse输出给浏览器。
- @RequestMapping(value ="/returnStudentJson.do")
- @ResponseBody
- public Student doStudentJsonObject(String name,Integer age){
- //调用Service,获取请求结果数据,Student对象表示结果数据
- Student student=new Student();
- student.setName("李四");
- student.setAge(20);
- return student;//会被框架转换为json
- }
- }
index.jsp:更换访问的url:
- <%--
- Created by IntelliJ IDEA.
- User: DELL
- Date: 2022/6/7
- Time: 17:37
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
- %>
- <html>
- <head>
- <title>Title</title>
- <base href="<%=basePath%>">
- <script type="text/javascript" src="js/jquery-3.3.1.js"></script>
- <script type="text/javascript">
- $(function(){
- $("button").click(function(){
- //alert("button click");
- $.ajax({
- //url:"returnVoid-ajax.do",
- url:"returnStudentJson.do",
- data:{
- name:"zhangsan",
- age:20
- },
- type:"post",
- dataType:"json",
- success:function(resp){
- //resp从服务器返回的是json格式的字符串{"name":"zhangsan","age":20}
- //jquery会把字符串转换为json对象,赋值给resp形参
- alert(resp.name+" "+resp.age);
- }
- })
-
- })
- })
- </script>
- </head>
- <body>
- <h1>处理器方法返回String表示视图名称</h1>
-
- <form action="returnString-view.do" method="post">
- 姓名:<input type="text" name="name"><br>
- 年龄:<input type="text" name="age"><br>
- <input type="submit" value="提交参数">
- </form>
- <br>
- <br>
- <button id="btn">发起ajax请求</button>
- </body>
- </html>
返回json对象数组:返回List集合
MyController:
- package com.bjpowernode.controller;
-
- import com.bjpowernode.vo.Student;
- import com.fasterxml.jackson.core.JsonProcessingException;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.bind.annotation.ResponseBody;
- import org.springframework.web.servlet.ModelAndView;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpSession;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.util.ArrayList;
- import java.util.List;
-
- @Controller
- public class MyController {
-
-
- //处理器方法返回String
- @RequestMapping(value ="/returnString-view.do") //value里面可以写多个名字进行访问
- public String doReturnView(HttpServletRequest request,String name,Integer age){ //doSome相当于doGet()---调用Service请求处理
- System.out.println("doReturnView,name="+name+" age="+age);//这里先不调用,简化处理
-
- //如果还想存储数据,可以手工去做,我们可以使用request作用域手工添加到request作用域
- request.setAttribute("myname",name);
- request.setAttribute("myage",age);
-
- //show:逻辑视图名称,项目中配置了视图解析器
- //框架对视图执行forword转发操作
- return "show";
- //还可以返回完整路径,不用视图解析器,在配置文件中把视图解析器注释
- //return "/WEB-INF/view/show.jsp";
-
- }
-
- //处理器方法返回void ,响应ajax请求
- //手工实现ajax,json数据:代码存在重复:java对象转换为json;通过HttpServletResponse输出json数据
- @RequestMapping(value ="/returnVoid-ajax.do") //value里面可以写多个名字进行访问
- public void doReturnVoidAjax(HttpServletResponse response,String name,Integer age) throws IOException { //doSome相当于doGet()---调用Service请求处理
- System.out.println("doReturnVoidAjax,name="+name+" age="+age);//这里先不调用,简化处理
-
- //处理ajax,使用json做数据的格式
- //Service调用完了,使用Student表示处理结果
- Student student=new Student();
- student.setName(name);
- student.setAge(age);
-
- String json="";
- //把结果的对象转为json格式的数据
- if(student!=null){
- ObjectMapper om=new ObjectMapper();
- json= om.writeValueAsString(student);
- System.out.println("Student转换为json=="+json);
- }
-
- //输出数据,响应ajax的请求
- response.setContentType("application/json;charset=utf-8");
- PrintWriter pw=response.getWriter();
- pw.println(json);
- pw.flush();
- pw.close();
- }
-
-
- //处理器方法返回一个Student,通过框架转为json,响应ajax请求
- //@ResponseBody注解作用:把处理器方法返回的对象转为json后,通过HttpServletResponse输出给浏览器。
- /*
- 返回对象框架的处理流程:
- 1.框架会把返回Student类型,调用框架中的ArrayList<HttpMeaasgeConverter>中的每个类的canwrite()方法
- 检查哪个HttpMessageConverter接口的实现类能处理Student类型的数据-->MappingJackson2HttpMessageConverter
- 2.框架会调用实现类的write()方法,把李四的Student对象转为json,调用Jackon的ObjectMapper实现转换json
- 3.框架会电泳@ResponseBody把2的结果输出到浏览器,ajax请求处理完成
- */
- @RequestMapping(value ="/returnStudentJson.do")
- @ResponseBody
- public Student doStudentJsonObject(String name,Integer age){
- //调用Service,获取请求结果数据,Student对象表示结果数据
- Student student=new Student();
- student.setName("李四");
- student.setAge(20);
- return student;//会被框架转换为json
- }
-
-
- /*处理器方法返回一个List集合,通过框架转为json,响应ajax请求
- @ResponseBody注解作用:把处理器方法返回的对象转为json后,通过HttpServletResponse输出给浏览器。
- */
- /*
- 返回对象框架的处理流程:
- 1.框架会把返回List<Student>类型,调用框架中的ArrayList<HttpMeaasgeConverter>中的每个类的canwrite()方法
- 检查哪个HttpMessageConverter接口的实现类能处理Student类型的数据-->MappingJackson2HttpMessageConverter
- 2.框架会调用实现类的write()方法,把李四的Student对象转为json,调用Jackon的ObjectMapper实现转换json array
- 3.框架会电泳@ResponseBody把2的结果输出到浏览器,ajax请求处理完成
- */
- @RequestMapping(value ="/returnStudentJsonArray.do")
- @ResponseBody
- public List<Student> doStudentJsonObjectArray(String name, Integer age){
-
- List<Student> list=new ArrayList<>();
- //调用Service,获取请求结果数据,Student对象表示结果数据
- Student student=new Student();
- student.setName("李四");
- student.setAge(20);
-
- list.add(student);
-
- student=new Student();
- student.setName("张三");
- student.setAge(28);
- list.add(student);
-
- return list;//会被框架转换为json数组
- }
- }
index.jsp:更换url
- <%--
- Created by IntelliJ IDEA.
- User: DELL
- Date: 2022/6/7
- Time: 17:37
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
- %>
- <html>
- <head>
- <title>Title</title>
- <base href="<%=basePath%>">
- <script type="text/javascript" src="js/jquery-3.3.1.js"></script>
- <script type="text/javascript">
- $(function(){
- $("button").click(function(){
- //alert("button click");
- $.ajax({
- //url:"returnVoid-ajax.do",
- //url:"returnStudentJson.do",
- url:"returnStudentJsonArray.do",
- data:{
- name:"zhangsan",
- age:20
- },
- type:"post",
- dataType:"json",
- success:function(resp){
- //resp从服务器返回的是json格式的字符串{"name":"zhangsan","age":20}
- //jquery会把字符串转换为json对象,赋值给resp形参
- //alert(resp.name+" "+resp.age);
-
- //返回的是json数组
- $.each(resp,function (i,n) {
- alert(n.name+" "+n.age);
- })
- }
- })
-
- })
- })
- </script>
- </head>
- <body>
- <h1>处理器方法返回String表示视图名称</h1>
-
- <form action="returnString-view.do" method="post">
- 姓名:<input type="text" name="name"><br>
- 年龄:<input type="text" name="age"><br>
- <input type="submit" value="提交参数">
- </form>
- <br>
- <br>
- <button id="btn">发起ajax请求</button>
- </body>
- </html>
响应ajax,处理器返回的是String
My Controller:
- package com.bjpowernode.controller;
-
- import com.bjpowernode.vo.Student;
- import com.fasterxml.jackson.core.JsonProcessingException;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.bind.annotation.ResponseBody;
- import org.springframework.web.servlet.ModelAndView;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpSession;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.util.ArrayList;
- import java.util.List;
-
- @Controller
- public class MyController {
-
-
- //处理器方法返回String
- @RequestMapping(value ="/returnString-view.do") //value里面可以写多个名字进行访问
- public String doReturnView(HttpServletRequest request,String name,Integer age){ //doSome相当于doGet()---调用Service请求处理
- System.out.println("doReturnView,name="+name+" age="+age);//这里先不调用,简化处理
-
- //如果还想存储数据,可以手工去做,我们可以使用request作用域手工添加到request作用域
- request.setAttribute("myname",name);
- request.setAttribute("myage",age);
-
- //show:逻辑视图名称,项目中配置了视图解析器
- //框架对视图执行forword转发操作
- return "show";
- //还可以返回完整路径,不用视图解析器,在配置文件中把视图解析器注释
- //return "/WEB-INF/view/show.jsp";
-
- }
-
- //处理器方法返回void ,响应ajax请求
- //手工实现ajax,json数据:代码存在重复:java对象转换为json;通过HttpServletResponse输出json数据
- @RequestMapping(value ="/returnVoid-ajax.do") //value里面可以写多个名字进行访问
- public void doReturnVoidAjax(HttpServletResponse response,String name,Integer age) throws IOException { //doSome相当于doGet()---调用Service请求处理
- System.out.println("doReturnVoidAjax,name="+name+" age="+age);//这里先不调用,简化处理
-
- //处理ajax,使用json做数据的格式
- //Service调用完了,使用Student表示处理结果
- Student student=new Student();
- student.setName(name);
- student.setAge(age);
-
- String json="";
-
- //把结果的对象转为json格式的数据
- if(student!=null){
- ObjectMapper om=new ObjectMapper();
- json= om.writeValueAsString(student);
- System.out.println("Student转换为json=="+json);
- }
-
- //输出数据,响应ajax的请求
- response.setContentType("application/json;charset=utf-8");
- PrintWriter pw=response.getWriter();
- pw.println(json);
- pw.flush();
- pw.close();
- }
-
-
- //处理器方法返回一个Student,通过框架转为json,响应ajax请求
- //@ResponseBody注解作用:把处理器方法返回的对象转为json后,通过HttpServletResponse输出给浏览器。
- /*
- 返回对象框架的处理流程:
- 1.框架会把返回Student类型,调用框架中的ArrayList<HttpMeaasgeConverter>中的每个类的canwrite()方法
- 检查哪个HttpMessageConverter接口的实现类能处理Student类型的数据-->MappingJackson2HttpMessageConverter
- 2.框架会调用实现类的write()方法,把李四的Student对象转为json,调用Jackon的ObjectMapper实现转换json
- contentType:application/json;charset=utf-8
- 3.框架会电泳@ResponseBody把2的结果输出到浏览器,ajax请求处理完成
- */
- @RequestMapping(value ="/returnStudentJson.do")
- @ResponseBody
- public Student doStudentJsonObject(String name,Integer age){
- //调用Service,获取请求结果数据,Student对象表示结果数据
- Student student=new Student();
- student.setName("李四");
- student.setAge(20);
- return student;//会被框架转换为json
- }
-
-
- /*处理器方法返回一个List集合,通过框架转为json,响应ajax请求
- @ResponseBody注解作用:把处理器方法返回的对象转为json后,通过HttpServletResponse输出给浏览器。
- */
- /*
- 返回对象框架的处理流程:
- 1.框架会把返回List<Student>类型,调用框架中的ArrayList<HttpMeaasgeConverter>中的每个类的canwrite()方法
- 检查哪个HttpMessageConverter接口的实现类能处理Student类型的数据-->MappingJackson2HttpMessageConverter
- 2.框架会调用实现类的write()方法,把李四的Student对象转为json,调用Jackon的ObjectMapper实现转换json array
- contentType:application/json;charset=utf-8
- 3.框架会电泳@ResponseBody把2的结果输出到浏览器,ajax请求处理完成
- */
- @RequestMapping(value ="/returnStudentJsonArray.do")
- @ResponseBody
- public List<Student> doStudentJsonObjectArray(String name, Integer age){
-
- List<Student> list=new ArrayList<>();
- //调用Service,获取请求结果数据,Student对象表示结果数据
- Student student=new Student();
- student.setName("李四");
- student.setAge(20);
-
- list.add(student);
-
- student=new Student();
- student.setName("张三");
- student.setAge(28);
- list.add(student);
-
- return list;//会被框架转换为json数组
- }
-
- /*
- * 处理器方法返回的是String,String表示数据,不是视图
- * 区分返回值是String 是数据,还是视图,看有没有@ResponseBody注解
- * 如果有@ResponseBody注解,返回String就是数据,反之就是视图
- * 默认使用“text/plain;charset=IOS-8859-1”作为contentType,导致中文乱码
- * 解决:
- * 给@ResponseMapping增加一个属性produces,使用这个属性指定的新的contentType
- * */
- /*
- 返回对象框架的处理流程:
- 1.框架会把返回String类型,调用框架中的ArrayList<HttpMeaasgeConverter>中的每个类的canwrite()方法
- 检查哪个HttpMessageConverter接口的实现类能处理String类型的数据-->StringHttpMessageConverter
- 2.框架会调用实现类StringHttpMessageConverter的write()方法
- 把字符串按照指定的编码处理,text/plain;charset=IOS-8859-1
- 3.框架会电泳@ResponseBody把2的结果输出到浏览器,ajax请求处理完成
- */
- @RequestMapping(value = "/returnStringData.do",produces = "text/plain;charset=utf-8")
- @ResponseBody
- public String doStringData(String name,Integer age){
- return "Hellow SpringMVC 返回对象,表示数据";
- }
-
- }
index.jsp:更换url和dataType
- <%--
- Created by IntelliJ IDEA.
- User: DELL
- Date: 2022/6/7
- Time: 17:37
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
- %>
- <html>
- <head>
- <title>Title</title>
- <base href="<%=basePath%>">
- <script type="text/javascript" src="js/jquery-3.3.1.js"></script>
- <script type="text/javascript">
- $(function(){
- $("button").click(function(){
- //alert("button click");
- $.ajax({
- //url:"returnVoid-ajax.do",
- //url:"returnStudentJson.do",
- //url:"returnStudentJsonArray.do",
- url:"returnStringData.do",
- data:{
- name:"zhangsan",
- age:20
- },
- type:"post",
- //dataType:"json",
- dataType:"text",
- success:function(resp){
- //resp从服务器返回的是json格式的字符串{"name":"zhangsan","age":20}
- //jquery会把字符串转换为json对象,赋值给resp形参
- //alert(resp.name+" "+resp.age);
-
- //返回的是json数组
- /*$.each(resp,function (i,n) {
- alert(n.name+" "+n.age);
- })*/
-
- //返回的数据,字符串
- alert("返回文本数据:"+resp);
- }
- })
-
- })
- })
- </script>
- </head>
- <body>
- <h1>处理器方法返回String表示视图名称</h1>
-
- <form action="returnString-view.do" method="post">
- 姓名:<input type="text" name="name"><br>
- 年龄:<input type="text" name="age"><br>
- <input type="submit" value="提交参数">
- </form>
- <br>
- <br>
- <button id="btn">发起ajax请求</button>
- </body>
- </html>