刚刚查阅官方文档(convention-plugin.html)并学习了Struts2的Convention插件,文章这里只作为一个笔记,建议大家去看官方文档比较清晰和全面。
需要在项目添加这些包
convention先找package,其中如果package包含action这个单词,就会将这个包作为根路径,即namespace="/"
然后找类,如果一个类的类名称是Action结尾,或者继承了ActionSupport类,那么会将该类作为action类,对应的url为
例如:
com.example.actions.MainAction -> /main
com.example.actions.products.Display -> /products/display
com.example.struts.company.details.ShowCompanyDetailsAction -> /company/details/show-company-details
jsp文件要放到/WEB-INF/content/文件夹下
/WEB-INF/content/main.jsp
/WEB-INF/content/display.jsp
/WEB-INF/content/company/details/show-company-details.jsp
下面来一个例子:
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>
<constant name="struts.i18n.encoding" value="UTF-8" />
<!-- 当struts的配置文件修改后,系统是否自动重新加载该文件,默认值为false(生产环境下使用),开发阶段最好打开 -->
<constant name="struts.configuration.xml.reload" value="true" />
<!-- 开发模式下使用,这样可以打印出更详细的错误信息 -->
<constant name="struts.devMode" value="true" />
</struts>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>Struts Blank</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> <welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list> </web-app>
包结构如下:
HelloWorld.java
package com.hyy.action; import com.opensymphony.xwork2.ActionSupport; public class HelloWorld extends ActionSupport{
private String message;
public String execute() {
message = "hyy";
return SUCCESS;
} public String getMessage() {
return message;
} }
/WEB-INF/content/hello-world.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
你好,世界, ${message}
</body>
</html>
在地址栏输入:http://localhost:8080/项目名/hello-world
即可到达HelloWorld.java这个action,返回的视图就是hello-world.jsp