【SSH (三)】struts2專案搭建
阿新 • • 發佈:2019-02-16
1,下載struts2 jar包。
http://struts.apache.org/。
2,Eclipse新建web dynamic project,專案預設是沒有web.xml的,通常這時會去網上找,但是又會擔心是否靠譜,每一次建專案都得複製貼上。其實可以讓Eclipse生成一份web.xml檔案,這個更加方便也更靠譜。方法如下圖所示:
填完專案名不要finish,而是選擇next下去,然後勾選generate web.xml檔案即可。
3,配置web.xml:
只是加一個核心filter的配置。url-pattern推薦寫/*,讓struts2來處理所有的請求。<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>Struts2Project</display-name> <!-- 配置struts2為專案的controller --> <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>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>
4,新增jar包:
這裡我們通常會只想新增最少的jar包,而且要讓jar包之前的版本匹配,保證版本一致,最好的辦法就是有一個官方的模版。這時我們可以在下載struts2的官網上面下載一個Example Application,如下圖:
解壓縮之後,裡面有一個struts2-blank.war專案,解壓,然後就可以得到一個官方的空的struts2專案。我們搭建專案可以參照這個專案。
比如jar的最小集可以從blank裡面的lib複製過來。
5,struts.xml:
預設位置在src下面。
同樣可以從blank專案中複製過來。修改成我們所需要的即可。
這裡我們先配置一個index的action,用於返回一個首頁。
<?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.action.extension" value="do,action"/> <package name="index" extends="struts-default"> <action name="index" class="com.action.LoginAction" method="index"> <result name="success">/WEB-INF/jsp/index.jsp</result> </action> </package> <!-- <include file="example.xml"/> --> </struts>
6,LoginAction類:
package com.action;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
//返回index介面
public String index(){
return SUCCESS;
}
}
繼承ActionSupport類,我們可以使用一些struts2提供的功能,比如驗證之類的。還可以使用一些表示返回值的常量,這些常量其實是在Action介面中定義的,ActionSupport類本身實現了這個介面。
7,index.jsp頁面:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Index</title>
</head>
<body>
<h3>index.jsp</h3>
</body>
</html>
8,執行專案,瀏覽器如下:
搭建成功。
總結一下。主要是配置檔案和jar包吧。
1,jar包如果只是小專案搭建,完全可以下載example application,複製即可。如果要用到其他struts2的jar,那麼還是得 下載全部的jar包,即-all.zip的那個。然後需要哪個,就從裡面複製,不要在其他地方下載,可能會有版本衝突。
2,配置檔案,struts.xml和web.xml也都可以找到比較官方的模版,不用擔心。