Java、Spring和Javascript的集成
本文讲解内容为如何基于Spring MVC来实现Java与Javascript集成。项目主要利用Spring来组织本次项目的Java生态,并使用Javascript脚本语言对宿主语言Java进行功能扩展。涉及到的知识点有以下几点:
Maven构建环境搭建
Java的ScriptEngine
Spring应用关联文
准备工作
为了简化配置,这里使用maven来实现项目构建。由于我使用的是STS(Spring Tool Suite),maven插件以及相关的实现已经内置在IDE中,所以不需要额外进行环境配置,对于没有准备好构建的环境的童鞋还请自己动手。
在配置maven的时候,由于GFW(Great Firewall of China,简写为Great Firewall)的存在,有时会导致一些存放在国外服务器上的maven repository无法访问,所以我们需要手动添加国内镜像仓储,具体详情请参考文档:http://maven.oschina.net/help.html
。按照文档中的说明配置完成之后,请右键点击项目图标,依次选择Maven、Update Projects…,然后静静等待5至10分钟(这时主要是下载构建时依赖的jar包,最终速度取决于网络情况),直至项目编译完成。
PS:如果项目总是无法编译且红叉不断的话,我们可以尝试删除未完成的依赖更新文件
*.jar.lastUpdated
,删除临时文件的目的是为了让maven重新下载依赖包。下面就是其中一种例子:
./repository/org/springframework/spring-test/3.2.3.RELEASE/spring-test-3.2.3.RELEASE.jar.lastUpdated
添加并配置Controller
配置Spring MVC
maven环境搭建完成之后我们就可以正式进入开发了。第一个要添加的就是Controller类(Spring MVC),为我们的项目提供一个入口文件。
配置好web.xml并在mvc-config.xml中配置Controller服务,示例代码如下:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>JavaSpringJavascriptIntegrationWorld</display-name>
<!--
- Location of the XML file that defines the root application context.
- Applied by ContextLoaderListener.
-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/application-config.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--
- Servlet that dispatches request to registered handlers (Controller implementations).
-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
web.xml里定义了两个配置文件,一个是供Spring MVC使用的mvc-config.xml,另一个是非Web关联文下的application-config.xml,至于这两者之间到底有什么区别,我们可以从后面的运行时信息里找到答案。出了两个关联文配置文件外,剩余的则是Spring MVC定义时所需的必要配置内容,这里不做多解释。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring