问题:对于一个简单的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; }
以上内容转自:https://blog.csdn.net/YiGeiGiaoGiao/article/details/128750622
现在描述下我的问题:
1.直接访问没问题:截图如下
访问地址:http://localhost:8080/spring_mvc/index.jsp

2.跳转就访问不到
访问地址:http://localhost:8080/spring_mvc/charpter07/logion
@Controller @RequestMapping("/charpter07") public class Charpter07Controler { @GetMapping("/logion") public String logion(){ System.out.println("跳转到logion.jsp"); return "forward:/index.jsp"; } }



也就是说我们配置
href="layui/css/layui.css"
src="layui/layui.js"
是相对路径。直接访问没问题,但是如果一旦经过了跳转,静态资源的访问路径就变成了
http://localhost:8080/spring_mvc/charpter07/layui/css/layui.css
http://localhost:8080/spring_mvc/charpter07/layui/layui.js
因此就会出现找不到的问题:
最终解决办法:通过添加绝对路径访问(如下图),这样,不管是直接访问,还是转发到此页面,访问路径就都是
http://localhost:8080/spring_mvc/layui/css/layui.css
http://localhost:8080/spring_mvc/layui/layui.js

此处给一个有意义的参考:https://www.cnblogs.com/jimisun/p/9418247.html