web前端form表单的action路径url问题

问题:对于一个简单的form表单,url究竟应该如何填写?

1、url的各部分组成

对于地址:http://192.168.1.1:8080/hello/index.html
其中:分解为三部分

  • 服务器地址: http://192.168.1.1:8080
  • WEB应用上下文: /hello
  • 网页或请求: /index.html

2、form表单中的action

  • HTML协议中要求,form的action属性,以“/”开头是绝对路径,不以“/”开头的是相对路径

  • 绝对路径是相对于服务器地址而言的。所以记住,很多时候一个斜杠就代表已经写了 http://192.168.1.1:8080这么多东西

  • 相对路径是相对于当前网页或请求而言的。

  • 根目录代表的是从最底层目录访问到当前目录,即绝对路径;

  • "./" 代表当前目录,"../"代表上级目录,"/"代表Web应用的根目录

  • 无“/”,代表是相对于web应用根目录,即http://localhost:8080/tomcat配置的虚拟目录/

  • 有“/”,代表是相对于web站点根目录,即http://localhost:8080/

3、具体写法:

例如:
Web Application的context是hello
http://localhost:8080/hello/index.html是欢迎页。

现在我的一个Controller的映射为@RequestMapping(“/fileUp”)。
  如果页面的form中的action=“/fileUp”,转向的URL为http://localhost:8080/fileUp,是无效的。
  以下是有效的写法,会转向“http://localhost:8080/hello/fileUp”:

action=“/hello/fileUp”
action=“./fileUp”
action=“fileUp” 无“/” 直接跳转到对于的资源名,这个也常见

4、RequestMapper(“/fileUp”) 这里的 / 可加可不加,但都是从上下文开始,而不是从服务器地址开始

web容器启动的时候,(org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping)会扫描Controller注解找到所有的Handler(这里把处理器就称为Handler,等会儿好理解)类,拿到所有的Handler类之后,会遍历这些Handler类,并且遍历这个Handler类中所有带RequestMapping的方法,同时把类和方法的路径拼起来(框架叫做combine,联结在一起,注意:Handler类可以不要RequestMapping),在这个过程中,会判断路径的最前面是否有斜线(/),如果没有,会拼一个斜线(/)

5、例子

重点理解下面的语句(针对action):

  • 无“/”,代表是相对于web应用根目录,即http://localhost:8080/tomcat配置的虚拟目录/
  • 有“/”,代表是相对于web站点根目录,即http://localhost:8080/

前端:

<form action="student/zhangsan/20" method="post">
        <input type="submit" value="注册学生">
</form>

后端:

 /**
     * 创建资源 Post请求方式
     * http://localhost:8080/myboot/student/zhangsan/20
     */
    @PostMapping("/student/{name}/{age}")
    public String createStudent(@PathVariable("name") String name,
                                @PathVariable("age") Integer age){
    
    
        return "创建资源 student: name="+name+"#age="+age;
    }

猜你喜欢

转载自blog.csdn.net/YiGeiGiaoGiao/article/details/128750622