整合
struts2想要用velocity模板需要如下幾個包:
velocity-1.7.jar velocity-tools-2.0.jar commons-collections-3.2.jar
然後只需要在web.xml中配置result type=velocity就可以了。
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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>structs2_day01</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>velocity</servlet-name>
<servlet-class>org.apache.velocity.tools.view.VelocityViewServlet</servlet-class>
<!-- 需要在struts.xml中定義兩個常量,來幫助struts尋找到tools.xml和velocity.properties的位置 -->
<init-param>
<param-name>org.apache.velocity.toolbox</param-name>
<param-value>/WEB-INF/tools.xml</param-value>
</init-param>
<init-param>
<param-name>org.apache.velocity.properties</param-name>
<param-value>/WEB-INF/velocity.properties</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>velocity</servlet-name>
<url-pattern>*.vm</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- 需要在struts.xml中定義兩個常量,來幫助struts尋找到tools.xml和velocity.properties的位置 -->
<constant name="struts.velocity.toolboxlocation"
value="WEB-INF/tools.xml" />
<constant name="struts.velocity.configfile"
value="WEB-INF/velocity.properties" />
<!-- 動態方法調用,爲true時,就可以在struts.xml配置“*”的通配符,來調用action裏的方法 -->
<constant name="struts.enable.DynamicMethodInvocation"
value="false" />
<constant name="struts.devMode" value="true" />
<!-- 修改 struts2 默認常量值 -->
<constant name="struts.i18n.encoding" value="UTF-8" />
<package name="default" namespace="/" extends="struts-default">
<default-action-ref name="index" />
<global-results>
<result name="error">/error.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping exception="java.lang.Exception"
result="error" />
</global-exception-mappings>
</package>
<!-- 引入hello.xml文件 -->
<include file="struts-hello.xml" />
<!-- Add packages here -->
</struts>
參考: https://www.cnblogs.com/jameslif/p/3653868.html
入門案例
參考: https://www.cnblogs.com/lexus/archive/2012/02/10/2344748.html
https://www.iteye.com/blog/zyjustin9-2093034