代码目录结构
User类:
package com.Keafmd.domain; import java.io.Serializable; /** * Keafmd * * @ClassName: User * @Description: * @author: 牛哄哄的柯南 * @date: 2021-01-30 9:59 */ public class User implements Serializable { private String username; private String password; private Integer age; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User{" + "username='" + username + '\'' + ", password='" + password + '\'' + ", age=" + age + '}'; } }
pom.xml:
<?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.keafmd</groupId> <artifactId>springmvc_day02_01_response</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>springmvc_day02_01_response Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <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> <!-- 版本锁定 --> <spring.version>5.2.6.RELEASE</spring.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.11.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.11.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.11.2</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> </dependencies> <build> <finalName>springmvc_day02_01_response</finalName> <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --> <plugins> <plugin> <artifactId>maven-clean-plugin</artifactId> <version>3.1.0</version> </plugin> <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --> <plugin> <artifactId>maven-resources-plugin</artifactId> <version>3.0.2</version> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.0</version> </plugin> <plugin> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.1</version> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> </plugin> <plugin> <artifactId>maven-install-plugin</artifactId> <version>2.5.2</version> </plugin> <plugin> <artifactId>maven-deploy-plugin</artifactId> <version>2.8.2</version> </plugin> </plugins> </pluginManagement> </build> </project>
springmvc.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 开启注解扫描,配置spring创建容器时要扫描的包 --> <context:component-scan base-package="com.Keafmd"></context:component-scan> <!-- 配置视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"></property> <property name="suffix" value=".jsp"></property> </bean> <!--告诉前端控制器,哪些静态资源,不拦截--> <mvc:resources location="/css/" mapping="/css/**" /> <mvc:resources location="/images/" mapping="/images/**" /> <mvc:resources location="/js/" mapping="/js/**" /> <!-- 开启SpringMVC框架注解支持,注解配置spring开启注解mvc的支持 --> <mvc:annotation-driven/> </beans>
success.jsp:
<%-- Created by IntelliJ IDEA. User: Keafmd Date: 2021/1/30 Time: 9:40 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>Title</title> </head> <body> <h1>执行成功</h1> ${user.toString()} </body> </html>
返回值分类
字符串
UserController类:
package com.Keafmd.controller; import com.Keafmd.domain.User; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.jws.soap.SOAPBinding; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Keafmd * * @ClassName: UserController * @Description: * @author: 牛哄哄的柯南 * @date: 2021-01-30 9:52 */ @Controller @RequestMapping("/user") public class UserController { /** * 返回字符串 * @param model * @return */ @RequestMapping("/testString") public String testString(Model model){ String clazz = Thread.currentThread().getStackTrace()[1].getClassName(); String method = Thread.currentThread().getStackTrace()[1].getMethodName(); System.out.println("执行了:"+clazz+" - "+method); //模拟从数据库中查询User对象 User user = new User(); user.setUsername("Keafmd"); user.setPassword("123456"); user.setAge(21); //model对象 model.addAttribute("user",user); return "success"; } }
response.jsp:
<%-- Created by IntelliJ IDEA. User: Keafmd Date: 2021/1/30 Time: 9:40 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <a href="user/testString">testString</a><br/> </body> </html>
运行效果:
执行了:com.Keafmd.controller.UserController - testString
void
1.如果控制器的方法返回值编写成void,执行程序报404的异常,默认查找JSP页面没有找到,文.件[/WEB-INF/pages/user/testVoid.jsp] 未找到。
2.可以使用请求转发或者重定向跳转到指定的页面。
UserController类:
/** * 返回void * 请求转发是一次请求,不用编写项目的名称 * @param */ @RequestMapping("/testVoid") public void testVoid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String clazz = Thread.currentThread().getStackTrace()[1].getClassName(); String method = Thread.currentThread().getStackTrace()[1].getMethodName(); System.out.println("执行了:"+clazz+" - "+method); //文.件[/WEB-INF/pages/user/testVoid.jsp] 未找到 //编写请求转发程序 //手动转发不会使用视图解析器,需要自己写路径 //request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response); //如果这后面有代码,还是会继续执行的,不想执行加上return //编写重定向程序 //response.sendRedirect(request.getContextPath()+"/index.jsp"); //设置中文乱码 response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); //直接进行响应 response.getWriter().println("hello牛哄哄的柯南"); return; }
response.jsp:
<a href="user/testVoid">testVoid</a><br/>
运行效果:
执行了:com.Keafmd.controller.UserController - testVoid
ModelAndView
ModelAndView对象是Spring提供的一个对象,可以用来调整具体的JSP视图。
UserController类:
/** * 返回 ModelAndView * 返回String底层调用的就是ModelAndView * @return */ @RequestMapping("/testModelAndView") public ModelAndView testModelAndView(){ String clazz = Thread.currentThread().getStackTrace()[1].getClassName(); String method = Thread.currentThread().getStackTrace()[1].getMethodName(); System.out.println("执行了:"+clazz+" - "+method); //创建ModelAndView对象 ModelAndView mv = new ModelAndView(); //模拟从数据库中查询User对象 User user = new User(); user.setUsername("小兰"); user.setPassword("123456"); user.setAge(21); //把User对象存到mv对象中,也会把user对象存入request对象 mv.addObject("user",user); //跳转到哪个页面 mv.setViewName("success"); return mv; }
response.jsp:
<a href="user/testModelAndView">testModelAndView</a><br/>
运行效果:
执行了:com.Keafmd.controller.UserController - testModelAndView
转发和重定向
UserController类:
/** * 使用关键字进行转发或重定向 * @return */ @RequestMapping("/testForwardOrRedirect") public String testForwardOrRedirect(){ String clazz = Thread.currentThread().getStackTrace()[1].getClassName(); String method = Thread.currentThread().getStackTrace()[1].getMethodName(); System.out.println("执行了:"+clazz+" - "+method); //请求的转发 //return "forward:/WEB-INF/pages/success.jsp"; //重定向 return "redirect:/index.jsp"; }
response.jsp:
<a href="user/testForwardOrRedirect">testForwardOrRedirect</a><br/>
运行效果:
执行了:com.Keafmd.controller.UserController - testForwardOrRedirect
ResponseBody响应json数据
json字符串和JavaBean对象互相转换的过程中,需要使用jackson的jar包:
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.11.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.11.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.11.2</version> </dependency>
response.jsp:
<%-- Created by IntelliJ IDEA. User: Keafmd Date: 2021/1/30 Time: 9:40 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script src="js/jquery.min.js" type="text/javascript"></script> <script> //页面加载,绑定页面单击事件 $(function (){ $('#btn').click(function (){ //alert("hello btn") $.ajax({ //编写json格式。设置属性和值 url:"user/testAjax", contentType:"application/json;charset=UTF-8", data:'{"username":"Keafmd","password":"666","age":"21"}', dataType:"json", type:"post", success:function (data){ //data指的是服务器端响应的数据,进行解析 alert(data); alert(data.username); alert(data.password); alert(data.age); } }); }); }); </script> </head> <body> <button id="btn">发送ajax的请求</button> </body> </html>
UserController类:
package com.Keafmd.controller; import com.Keafmd.domain.User; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.jws.soap.SOAPBinding; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Keafmd * * @ClassName: UserController * @Description: * @author: 牛哄哄的柯南 * @date: 2021-01-30 9:52 */ @Controller @RequestMapping("/user") public class UserController { /** * 模拟异步请求响应 */ @RequestMapping("/testAjax") public @ResponseBody User testAjax(@RequestBody User user){ String clazz = Thread.currentThread().getStackTrace()[1].getClassName(); String method = Thread.currentThread().getStackTrace()[1].getMethodName(); System.out.println("执行了:"+clazz+" - "+method); //客户端发送ajax请求,传的是json字符串,后端把json字符串封装到user对象中 System.out.println(user); //做相应,模拟查询数据库 user.setUsername("小兰"); user.setPassword("123"); return user; } }
运行效果:
执行了:com.Keafmd.controller.UserController - testAjax User{username='Keafmd', password='666', age=21}
以上就是SpringMVC中响应数据和结果视图的全部内容。