初学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";
    }
}
相关推荐
会编程的吕洞宾1 小时前
Spring AI 2.0 工具调用实战:让 AI 自动调用你的 Java 方法
java·人工智能·经验分享·后端·spring
技术小代1 小时前
弹窗里的 RegionName 为什么不生效?把区域作用域和模块化一次讲明白|MVVM框架-Prism-3
后端
斯维赤1 小时前
SELECT * 为什么是覆盖索引的天敌?
java·后端·mysql
程序员cxuan2 小时前
上海团队开源了首个国产记忆模型,554B!这也太狠了
人工智能·后端·程序员
天天鸭3 小时前
前端转全栈,要学会后端看项目的思维
前端·后端·ai编程
BingoGo3 小时前
为什么 PHP 应该只保留 ZTS 构建模式
后端·php
孟陬3 小时前
Foobar 技术周刊 #161:AI 录屏员工屏幕训练 SOP,被当做「动物园的猴子」是否触犯隐私?
前端·后端·程序员
SimonKing3 小时前
又一款数据库同步神器,2.3K Star的dbswitch
java·后端·程序员
Rain的Java大神之路4 小时前
前端转 Java 全栈:用 AI 两天交付一个能跑的 Demo,踩坑全记录
java·前端·后端
mldong5 小时前
换审批人不用写代码:jeeflow工作流引擎内置 9 种找人规则
后端·架构