栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

RestFul风格

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

RestFul风格

RestFul的优势:简洁,高效,安全 还能实现url的复用

restful风格的注解

变量上的注解:@PathVariable

方法上的注解

@PostMapping("/h1/{a}/{b}") <==========> @RequestMapping(path = "/h1/{a}/{b}",method = RequestMethod.POST)
@GetMapping()
@PutMapping()
@DeleteMapping()
@PatchMapping()

首先要知道最初的传递参数的方式?a=1&b=2 ,这样的传参,暴露了我们的参数是不安全的,而restful风格的传参是/1/2,只是传递了值。

再写一遍web.xml文件和springmvc-servlet.xml文件,其实在我们的开发中这两个配置文件基本上是不需要在做改变的

web.xml文件



    
    
    
        springmvc
        org.springframework.web.servlet.DispatcherServlet

        
        
            contextConfigLocation
            classpath:springmvc-servlet.xml
        

        
        1
    
    
    
        springmvc
        /
    

springmvc-servlet.xml文件




    
    
    
    
    
    

    
    
        
        
        
        
    

hello.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title


${result}


RestfulController.java

package com.zkw.restful;

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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/restful")
public class RestfulController {

    @RequestMapping(path = "/h1/{a}/{b}",method = RequestMethod.POST)
    public String Restful(@PathVariable int a, @PathVariable String b, Model model){
        model.addAttribute("result","结果为"+(a+b));
        return "hello";
    }

   @GetMapping("/h1/{a}/{b}")
    public String Restful(@PathVariable int a, @PathVariable int b, Model model){
        model.addAttribute("result","结果为"+(a+b));
        return "hello";
    }

    //原始的风格
    @RequestMapping("/h2")
    public String Restful(String a, int b, Model model){
        model.addAttribute("result","结果为"+(a+b));
        return "hello";
    }

}

解释一下,在类上边的@RequestMapping("/restful")与这个类下边方法上的所有@RequestMapping("/h2")和 @GetMapping("/h1/{a}/{b}")是父子关系,相当于你要想访问这各类里边的方法,首先要先访问这个类。

原始风格的结果为

先说一下,它默认的提交方式是get,当我使用restful风格访问的时候,它走得是 @GetMapping("/h1/{a}/{b}")这个

最后再说一下url的复用,当我在另一个页面上使用post提交表单的时候它请求的方法是第一个

首先写一个测试页面test.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title


结果为

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/362503.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号