SpringMVC 通过Controller返回到jsp页面后,页面能显示,但js,css图片等加载不出来

spring的controller做的跳转页面,后台控制前台跳转页面,发现跳转后的页面,静态资源css,js以及图片等在jsp里面引用的配置,都没有加载出来。

我用的bootstrap写的前台,经过检查DispatcherServlet,mvc:resources,配置没有出错后,发现自己的jsp页面是先开始写的html页面,直接修改的jsp文件,马上检查文件哪里没有写,果然忘了加上下面这个代码

<%  
String path = request.getContextPath();  
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
%>  
  
<base href="<%=basePath%>">

这段代码是为了保证,静态资源的配置可以写相对路径,不用写绝对路径

 

request.getSchema()可以返回当前页面使用的协议,http 或是 https;

request.getServerName()可以返回当前页面所在的服务器的名字;

request.getServerPort()可以返回当前页面所在的服务器使用的端口,就是80;

request.getContextPath()可以返回当前页面所在的应用的名字;

 

这个是修改了跳转后访问页面的路径的代码,

就是这个base href,官方解释这个标签的意思:href 属性规定页面中所有相对链接的基准 URL。

扫描二维码关注公众号,回复: 2152275 查看本文章

 

我的文件是在ssm1/web-inf/static/css/bootstrap.min.css下面

我配置了静态资源配置

<mvc:resources location="static/css/" mapping="/css/**" cache-period="31556926"/>

所以资源的引用绝对路径变成了ssm1/web-inf/css/bootstrap.min.css

 

jsp中是这样写的css引用

<link href="css/bootstrap.min.css" rel="stylesheet">

没有加上上面那行代码,我直接从controller跳转,这是跳转后的路径

http://127.0.0.1:8080/ssm1/user/login

查看源代码

image

css引用代码是这样的路径http://127.0.0.1:8080/ssm1/user/css/bootstrap.min.css

点击是找不到文件的

 

加上那段代码   跳转后的 路径一样

http://127.0.0.1:8080/ssm1/user/login

查看源代码

image

看看多了什么

css引用的代码是这样的路径http://127.0.0.1:8080/ssm1/css/bootstrap.min.css

点击路径直接打开了bootstrap.min.css文件








1.controller代码
@ Controller
@RequestMapping ( "/account" )
public  class  AccountController {
         @RequestMapping (value= "userLogin" ,method=RequestMethod. POST )
        public  String userLogin(){
              return "user_login";
          }
}

2.在jsp中的js引用
< script  src = "js/jquery-3.1.1.js" ></ script >

3.页面能显示出来,但js与图片都没有加载出来
通过谷歌浏览器开发者工具发现js路径上多了个 account
http://localhost:8080/PicShare/ account /js/ jquery-3.1.1.js

正确的路径是
http://localhost:8080/PicShare/js / jquery-3.1.1.js

很明显,那两个地址明显不匹配,jsp界面是由html修改过来的
它缺少了basePath 路径,所以那些写好的路劲都加在了account的后面

4修改办法
1.在jsp中添加以下代码
<%@  page  language = "java"  import = "java.util.*"  pageEncoding = "UTF-8" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+ "://" +request.getServerName()+ ":" +request.getServerPort()+path+ "/" ;
%>

2.在图片,js,css..引用中修改为以下格式
< script  src = " <%= path  %>/ js/jquery-3.1.1.js" ></ script >

猜你喜欢

转载自blog.csdn.net/wsh596823919/article/details/80997493