初学SpringMVC之 RestFul 风格、重定向和转发

RestFul 风格改变 URL 形式

比如之前是:http://localhost:8080/add?a=1\&b=2

现在是:http://localhost:8080/add/a/b(全是斜杠)

java 复制代码
package com.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class RestFul {
    //@RequestMapping(value = "/add/{a}/{b}",method = RequestMethod.GET)
    @GetMapping("/add/{a}/{b}")
    public String test(@PathVariable String a,@PathVariable String b, Model model){
        String res = a + b;
        model.addAttribute("msg",res);
        return "test"; //test.jsp
    }
}

通过 @PathVariable 映射到 URL 上

所有的地址栏请求默认都是 HTTP GET 类型

同理,组合注解有:

@GetMapping() 、@PostMapping()

@PutMapping() 、@DeleteMapping() 、@PatchMapping()

ServletAPI:通过 HttpServletRequest 进行输出、实现重定向、实现转发

java 复制代码
package com.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class Model {
    @RequestMapping("/model")
    public String test(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        System.out.println(session.getId());
        return "test";
    }
}

response.senRedirect("/xx.jsp") 重定向

request.getRequestDispatcher("/WEB-INF/jsp/xx.jsp").forward(request,response) 转发

通过 Spring MVC 来实现转发和重定向,无需视图解析器

forward 转发(不改变 URL)、redirect 重定向(改变 URL)

java 复制代码
package com.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ModelTest {
    @RequestMapping("/model")
    public String test(Model model){
        model.addAttribute("msg","Model");

        //转发:不改变url
        //return "/WEB-INF/jsp/test.jsp";
        //return "forward:/WEB-INF/jsp/test.jsp";

        //重定向:改变url
        return "redirect:/index.jsp";
    }
}
相关推荐
想用offer打牌4 小时前
RocketMQ如何防止消息丢失?
java·后端·架构·开源·rocketmq
源码获取_wx:Fegn08955 小时前
基于springboot + vue健身房管理系统
java·开发语言·前端·vue.js·spring boot·后端·spring
Mr1ght5 小时前
为什么 InheritableThreadLocal 在 Spring 线程池中“偶尔”能传递变量?——一次线程池上下文传播的误解
java·spring
摇滚侠5 小时前
面试实战 问题三十三 Spring 事务常用注解
数据库·spring·面试
码事漫谈6 小时前
Vibe Coding时代:人人都是开发者
后端
2501_916766546 小时前
【Spring框架】SpringJDBC
java·后端·spring
谷哥的小弟6 小时前
Spring Framework源码解析——ApplicationContextInitializer
java·spring·源码
+VX:Fegn08956 小时前
计算机毕业设计|基于springboot + vue图书管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
AntBlack6 小时前
忍不住推荐 : AI 时代 ,桌面端真的可以考虑一下Go+Wails 的组合
后端·go·ai编程
码事漫谈6 小时前
C++20协程如何撕开异步编程的牢笼
后端