响应——返回类型、转发和重定向、过滤静态资源、响应json
返回值类型
返回值为String
通过视图解析器,会以返回的String作为页面名称进行页面跳转(注意是跳转不是转发)。
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/testString")
public String testString(Model model){
System.out.println("testString方法执行了...");
//模拟从数据库中查询出user对象
User user = new User();
user.setUsername("啊哈哈");
user.setAge(20);
user.setPassword("123");
//将对象加入request域中
model.addAttribute("user",user);
return "success";
}
}
可在跳转的jsp页面取出request域中的值(由于前后端分离,估计以后是用不到了)
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>执行成功</h3>
${user.username}
${user.password}
${user.age}
</body>
</html>
返回值为void
默认情况会返回到与请求路径相同的jsp,该例子为:user/testVoid.jsp
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/testVoid")
public void testVoid(){
System.out.println("testVoid方法执行了...");
}
}
若不想进行默认情况跳转
转发:
/**
* 请求转一次请求,不用request.getContextPath()
* 转发需要,因为为一次新的请求
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
@RequestMapping("/testVoid")
public void testVoid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("testVoid方法执行了...");
//编写请求转发的程序
request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);
return; //防止后方代码执行
}
重定向:重定向无法访问WEB-INF中的资源,只有转发可以
@RequestMapping("/testVoid")
public void testVoid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("testVoid方法执行了...");
//编写请求转发的程序
//request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);
response.sendRedirect(request.getContextPath()+"/index.jsp");
}
直接响应数据写入新页面:会转发到一个空白的新页面,在页面上接受数据
@RequestMapping("/testVoid")
public void testVoid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("testVoid方法执行了...");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
response.getWriter().println("你好");
}
返回值是ModelAndView类型
ModelAndView是Spring提供的一个对象,可以用来调整具体的jsp视图
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
ModelAndView mv = new ModelAndView();
System.out.println("testModelAndView执行了...");
//模拟从数据库查询对象
User user = new User();
user.setUsername("芜湖");
user.setPassword("123");
user.setAge(18);
//把user对象存入到mv对象中,也会把user对象存入到request
mv.addObject("user",user);
//视图解析器会跳转到指定目录
mv.setViewName("success");
return mv;
}
转发和重定向
使用关键字(foward/redirect)就无法使用视图解析器,故需要写出对应路径
foward转发关键字
转发到指定路径
@RequestMapping("/testForwardOrRedirect")
public String testForwardOrRedirect(){
System.out.println("testForwardOrRedirect执行了...");
//请求的转发
return "forward:/WEB-INF/pages/success.jsp";
}
redirect重定向关键字
使用该关键字不用加项目路径,因为框架已经为你封装好了。
@RequestMapping("/testForwardOrRedirect")
public String testForwardOrRedirect(){
System.out.println("testForwardOrRedirect执行了...");
//请求的转发
/*return "forward:/WEB-INF/pages/success.jsp";*/
//重定向
return "redirect:/index.jsp";
}
响应json数据
过滤静态资料
web.xml中配置的DispatcherServlet会拦截任意路径的资源,故我们引入的js、css、jpg等资源都会被拦截,需要我们这此类资源进行设置,过滤拦截
js文件夹放在webapp下,css与images等同理
<?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.czy"></context:component-scan>
<!--视图解析器对象-->
<bean id="internalResourceViewResolver" 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="/js/" mapping="/js/**"></mvc:resources>
<!--开启SpringMVC框架注解的支持-->
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
响应json数据——ResponseBody注解(需导入jackson依赖)
SpringMVC已经封装好了返回json的注解。
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.10</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.10</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.10</version>
</dependency>
<script>
$(function () {
$("#btn").click(function () {
/*alert("hello btn");*/
//发送ajax请求
$.post("user/testAjax",{username:"hehe",password:"123",age:20},function (date) {
alert(date.username + " " + date.password + " " + date.age)
},"json")
})
})
</script>
@RequestMapping("/testAjax")
public @ResponseBody User testAjax(@RequestBody String body) throws IOException {
System.out.println("testAjax执行了...");
System.out.println(body);
//模拟数据库查询数据
User user = new User();
user.setPassword("123");
user.setUsername("哈哈");
user.setAge(22);
//通过responseBody将json数据传回
return user;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!