How include an external JS file in a JSP page
我一直在Google上进行搜索,但找不到任何有用的...我的JS文件与WEB-INF处于同一级别。任何帮助将不胜感激...
下面是我用来在JSP中包含JS文件的代码:-
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.18.0/jquery.validate.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/formValidation.js"></script>
下面的代码在web.xml中:-
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</context-param>
下面的代码在dispatcher-servlet.xml文件中:-
<context:component-scan base-package="com.programcreek.helloworld.controller" />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
答案 0 :(得分:1)
您可能想添加ResourceHandler
来解决js/css
目录之类的静态资源
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/js/**")
.addResourceLocations("/js/")
.setCachePeriod(3600)
.resourceChain(true)
.addResolver(new PathResourceResolver());
}
此方法适用于Java配置类extends WebMvcConfigurerAdapter
xml
版本应如下所示
<mvc:resources mapping="/js/**" location="/js/"/>
这将使用以下.js
文件中的类似内容来解析/webapp/js/
目录下的任何.jsp
文件
<script src="js/custom.js"></script>
答案 1 :(得分:0)
要获取帮助,您可以查看此github链接,单击here 希望对您有帮助 这是项目结构