一、 構建struts2框架的基本配置
1、 創建項目
2、 導入struts2的五個基本jar包: commons-logging-1.0.4.jar:日誌包、freemarker-2.3.13.jar、ognl-2.6.11.jar、struts2-core-2.1.6.jar:核心包、xwork-2.1.2.jar:webWork的核心包,struts2也依賴於它、commons-fileupload-1.2.1.jar
3、 配置項目下的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">
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
4、 在src目錄下創建struts2的配置文件struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="struts2" extends="struts-default">
<act
<result name="success">/result.jsp</result>
</act
</package>
</struts>
注:package裏的extends與類的繼承相似,struts-default是struts2裏已經存在的包 act
5、 在com.test.act
public class LoginAction extends ActionSupport {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@SuppressWarnings("unchecked")
public String execute() throws Exception {
if ("hello".equals(this.getUsername().trim())
&& "world".equals(this.getPassword().trim())) {
@SuppressWarnings("unused")
Map map=ActionContext.getContext().getSession();
map.put("user","valid");
return "success";
}
else{
this.addFieldError("username","username or password error");
return "failer";
}
}
public void validate() {
if (null == this.getUsername() || "".equals(this.getUsername().trim())) {
this.addFieldError("username", "username required");
}
if (null == this.getPassword() || "".equals(this.getPassword())) {
this.addFieldError("password", "password required");
}
}
}
注:繼承ActionSupport類,實現Act
二、 struts2類型轉換
序:類型轉換就是客戶端用戶輸入的參數轉化爲服務器端java的對象,不管用戶輸入什麼樣的內容,到客戶端都是以字符串的形式存在。
1、 某個Act
第一種是局部屬性文件,即在act
第二種是全局屬性文件,即在src根目錄下創建一個名爲xwork-conversion.properties的屬性文件(名字不可以更改),在裏面寫配置信息。形式是:要轉換類的路徑=作爲轉換器的類路徑
2、 創建類型轉換的類
轉換類繼承StrutsTypeConverter類,分別實現它裏是面的convertToString(Map context, Object o)與convertFromString(Map context, String[] values, Class toClass)兩個抽象方法,代碼如下:
public class PointConverter2 extends StrutsTypeConverter {
public Object convertFromString(Map context, String[] values, Class toClass) {
Point point = new Point();
String[] paramValues = values[0].split(",");
int x = Integer.parseInt(paramValues[0]);
int y = Integer.parseInt(paramValues[1]);
point.setX(x);
point.setY(y);
return point;
}
public String convertToString(Map context, Object o) {
Point point = (Point) o;
int x = point.getX();
int y = point.getY();
String result = " [ x= " + x + ", y=" + y + "]";
return result;
}
}
三、 struts2校驗
序:輸入校驗是驗證用戶輸入的信息是否合法是否有效。輸入校驗是建立在類型轉換的基礎之上的。若驗證有錯則顯示提示信息。輸入校驗的流程是:首先,類型轉換,然後校驗,若都沒錯則執行execute()方法,,若出錯,則跳轉到”input”指向的頁面。假若類型轉換不成功也要進行校驗。
1、類型轉換,如果類型轉換失敗系統有默認的錯誤提示信息,改變這種系統的錯誤提示信息有兩種,就是有創建全局或局部的屬性文件,首先全局的是在classes目錄下寫屬性文件message.properties,內容是xwork.default.invalid.fieldvalue={0} error的鍵值對,在struts.xml中的配置是<constantname="struts.custom.i18n.resources" value="message"></constant>,其次局部的是在act
2、校驗,struts2提供的多種校驗方式:
⑴是在act
public void validate() {
if (null == username || username.length() < 6 || username.length() > 10) {
this.addActionError("username invalid");
}
if (null == password || password.length() < 6 || password.length() > 10) {
this.addActionError("password invalid");
} else if (null == repassword || repassword.length() < 6
|| repassword.length() > 10) {
this.addActionError("repassword invalid");
} else if (!password.equals(repassword)) {
this.addActionError("two password not the same");
}
if (age < 1 || age > 130) {
this
.addActionError("\u8f93\u5165\u5e74\u9f84\u5e94\u8be5\u57280\u5c81\u5230120\u5c81\u4e4b\u95f4");
}
if(null==birthday){
this.addActionError("birthday invalid");
}
if(null==graduation){
this.addActionError("graduation invalid");
}
if (null != birthday && null != graduation) {
Calendar c1 = Calendar.getInstance();
c1.setTime(birthday);
Calendar c2 = Calendar.getInstance();
c2.setTime(graduation);
if (!c1.before(c2)) {
this.addActionError("birthday should before graduation");
}
}
注:錯誤提示信息由act
<s:fielderror cssStyle="color:red" />標籤內顯示,act
⑵是最常用的xml校驗方式,即在act
⑶還以用js在客戶端進行驗證,使用方法是在struts2標籤form中加入on
四、 struts2校驗框架
對上述校驗的細化,可相對第四章。
五、 攔截器
1、創建攔截器類(這是一個驗證用戶是否登錄的實例):
public class AuthInterceptor extends AbstractInterceptor {
public String intercept(ActionInvocation invocation) throws Exception {
Map map = invocation.getInvocationContext().getSession();//得到execute()中保存在session中的值
if (map.get("user") == null) {
return Act
} else {
return invocation.invoke();//若成功則到達指定頁面
}
}
}
注:session在act
@SuppressWarnings("unused")
Map map=ActionContext.getContext().getSession();
map.put("user","valid");
2、 配置struts.xml
Struts.xml中配置攔截器:
<interceptor name="auth" class="com.test.interceptor.AuthInterceptor">
</interceptor>
//應用攔截器:
<interceptor-ref name="auth"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
若驗證用戶沒登錄則跳轉到登錄頁面,在struts.xml中配置全局act
<global-results>
<result name="login" type="redirect">/login2.jsp</result>
</global-results>
注:注意一定要加入<interceptor-ref name="defaultStack"></interceptor-ref>默認攔截器棧,否則出錯。
六、 文件上傳下載
A 上傳
1、 導入兩個jar包:commons-io-1.3.2.jar和commons-fileupload-1.2.1.jar
2、 文件上傳jsp頁面:
表單代碼:
<s:form act
method="post">
<table align="center" border="1" width="50%">
<tr>
<td>
file
</td>
<td id="more">
<s:file name="file"></s:file>
<input type="button" value="Add
More.." on
</td>
</tr>
<tr>
<td>
<s:submit value="submit"></s:submit>
</td>
<td>
<s:reset value="reset"></s:reset>
</td>
</tr>
</table>
</s:form>
js代碼:
<script type="text/javas
function addMore(){
var td=document.getElementById("more");
var br=document.createElement("br");
var input=document.createElement("input");
var button=document.createElement("input");
input.type="file";
input.name="file";
button.type="button";
button.value="Remove";
button.on
td.removeChild(br);
td.removeChild(input);
td.removeChild(button);
}
td.appendChild(br);
td.appendChild(input);
td.appendChild(button);
}
</script>
3、 上傳文件的Act
public class UploadAction extends ActionSupport {
private List<File> file;//上傳多個文件用集合泛型
private List<String> fileFileName;//文件名
private List<String> fileContentType;//文件類型
public List<File> getFile() {
return file;
}
public void setFile(List<File> file) {
this.file = file;
}
public List<String> getFileFileName() {
return fileFileName;
}
public void setFileFileName(List<String> fileFileName) {
this.fileFileName = fileFileName;
}
public List<String> getFileContentType() {
return fileContentType;
}
public void setFileContentType(List<String> fileContentType) {
this.fileContentType = fileContentType;
}
@Override
public String execute() throws Exception {
for (int i = 0; i < file.size(); i++) {
InputStream is = new FileInputStream(file.get(i));
// String root = ServletActionContext.getRequest().getRealPath(
// "/upload");
// String path="D://";
String
path=this.getClass().getResource("/").getPath();//得到d:/tomcat/webapps/工程名WEB-INF/classes/路徑
path=path.substring(1,
path.indexOf("WEB-INF/classes"));//從路徑字符串中取出工程路勁
path=path+"/upload";
File destFile = new File(path, this.getFileFileName().get(i));//在目的路徑下醫院文件名創建文件
OutputStream os = new FileOutputStream(destFile);
byte[] buffer = new byte[400];
int length = 0;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);//寫入硬盤
}
is.close();
os.close();
}
return SUCCESS;
}
}
4、 struts.xml文件上傳配置
<act
<result name="success">/uploadResult.jsp</result>
<result name="input">/upload.jsp</result>
<interceptor-ref name="fileUpload">
<param name="maximumSize">4096000</param>
<param name="allowedTypes">application/vnd.ms-powerpoint</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</act
5、 上傳結果顯示頁面
username:<s:property value="username"/><br>
password:<s:property value="password"/><br>
file:<s:property value="fileFileName"/>
B 下載
1、超鏈接jsp下載頁面
<s:a href="download.act
2、下載核心代碼act
public class DownloadAction extends ActionSupport {
public InputStream getDownloadFile(){
return ServletActionContext.getServletContext().getResourceAsStream("/upload/struts.ppt");
}
@Override
public String execute() throws Exception {
return SUCCESS;
}
}
3、 struts.xml配置
<act
<result name="success" type="stream">
<param name="contentType">application/vnd.ms-powerpoint</param>
<param name="contentDisposition">filename="struts.ppt"</param>
<param name="inputName">downloadFile</param>
</result>
</act
七、 struts2國際化
詳細請參照第七章