初学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";
    }
}
相关推荐
子兮曰3 天前
jev-ultrafast 深度解析:7 秒订机票的浏览器 Agent 是如何炼成的
前端·后端·agent
子兮曰3 天前
Jev 爆发一周:7 秒 Agent 背后的 System One 生态与三场争议
前端·后端·ai编程
爱勇宝3 天前
ZCode 开源 24 小时:一份没有历史的账本,回答不了"有没有偷代码"
前端·后端·chatglm (智谱)
胡写代码3 天前
别再前后端各写一套表单校验了
java·后端
大勇前进3 天前
原生 PHP 还是 Laravel?小项目到底要不要上框架
后端
yuzhi_liu3 天前
我用 LangGraph4j 实现 Multi-Agent Supervisor
后端
alsmile3 天前
Node-RED 之外,国产规则引擎的新方案:基于标准语法,Go 先行实现
后端·开源·go
大白803 天前
PHP 内存溢出排查思路:看懂报错日志,精准定位问题
后端
二月龙3 天前
PHP 接口返回统一响应封装,让前后端对接更省心
后端
盖伦发发3 天前
软件工程SOLID 五大设计原则
后端·软件工程