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">
<!-- 定义Struts2的FilterDispathcer的Filter -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<!-- FilterDispatcher用来初始化struts2并且处理所有的WEB请求。 -->
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 有时文件上传时common-io.jar,commons-fileupload-1.1.1.jar,有时会出错,加入org.apache.struts2.dispatcher.ActionContextCleanUp这个过滤器就行 -->
<welcome-file-list>
<welcome-file>index.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.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- 配置国际化信息 -->
<constant name="struts.custom.i18n.resources" value="messages"/>
<!-- 设置使用的解码集 -->
<constant name="struts.i18n.encoding" value="utf-8"/>
<package name="wang" extends="struts-default">
<action name="login" class="wang.actions.LoginAction">
<result name="input">/index.jsp</result>
<result name="error">/error.jsp</result>
<result name="success">/login.jsp</result>
</action>
<action name="upload" class="wang.actions.UploadFileAction">
<!-- 动态设置action的属性值 -->
<param name="savePath">d:/upload</param>
<result name="input">/upload.jsp</result>
<result name="success">/upload_suc.jsp</result>
</action>
</package>
</struts>
LoginAction文件:
package wang.actions;
import java.util.Map;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport {
private String userName;
private String userPwd;
//result
private String tip;
private String[] books;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPwd() {
return userPwd;
}
public void setUserPwd(String userPwd) {
this.userPwd = userPwd;
}
public String getTip() {
return tip;
}
public void setTip(String tip) {
this.tip = tip;
}
public String[] getBooks() {
return books;
}
public void setBooks(String[] books) {
this.books = books;
}
public String execute() throws Exception {
ActionContext ctx = ActionContext.getContext();
//以下相当于在session保存东西(session.setAttribute(key,value);
//页面中用 ${sessionScope.user}输出结果信息
ctx.getSession().put("user", this.getUserName());
ctx.getSession().put("pwd", this.getUserPwd());
/* //这种也可以
Map map = ctx.getSession();
map.put("user", this.getUserName());
map.put("pwd", this.getUserPwd());
*/
//以下相当于在request中保存东西(request.setAttribute(key,value);
//页面中用 ${requestScope.test}输出结果信息
ctx.put("test", "request put test");
//保存结果,页面中用<s:property value="tip"/>输出结果信息
//备注:页面中引入标签<%@taglib prefix="s" uri="/struts-tags"%>可以在struts2-core-2.0.11.1.jar\META-INF\struts-tags.tld中找到定义
this.setTip("Login OK!");
return this.SUCCESS;
}
public void validate() {
if(userName == null || userName.equals("")){ //fieldName 为表单域的名字
//this.addFieldError("userName", "User Name is NULL"); //也是OK
this.addFieldError("userName", this.getText("userName.required")); //国际化
//页面的国际化可用: '%{getText("messageKey")}'
}
if(userPwd == null || userPwd.equals("")){
this.addFieldError("userPwd", this.getText("userPwd.required"));
}
}
}
UploadFileAction文件:
package wang.actions;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import com.opensymphony.xwork2.ActionSupport;
public class UploadFileAction extends ActionSupport {
private String title;
//封装上传文件域的属性
private File upload; //和表单域的name相同
//封装上传文件类型的属性
private String uploadContentType; //一定要是name+ContentType
//封装上传文件名的属性
private String uploadFileName; //一定要是name+FileName
//接受依赖注入的属性
private String savePath;
public String getSavePath() {
return savePath;
}
//接受依赖注入的方法
public void setSavePath(String savePath) {
this.savePath = savePath;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public File getUpload() {
return upload;
}
public void setUpload(File upload) {
this.upload = upload;
}
public String getUploadContentType() {
return uploadContentType;
}
public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
public String getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
public String execute() throws Exception
{
System.out.println("开始上传单个文件-----------------------");
System.out.println(getSavePath());
System.out.println("==========" + getUploadFileName());
System.out.println("==========" + getUploadContentType());
System.out.println("==========" + getUpload());
//以服务器的文件保存地址和原文件名建立上传文件输出流
//自己的修改的:ServletActionContext.getServletContext().getRealPath("/UploadImages")
FileOutputStream fos = new FileOutputStream(getSavePath() + "\\" + getUploadFileName());
FileInputStream fis = new FileInputStream(getUpload());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) > 0)
{
fos.write(buffer , 0 , len);
}
return SUCCESS;
}
}
index.jsp文件:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8" contentType="text/html;charset=utf-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
This is my JSP page. <br>
<s:fielderror></s:fielderror>
<s:form action="login.action" method="post">
<s:textfield name="userName" label='%{getText("userName.label")}'></s:textfield>
<s:password name="userPwd" label="密码"></s:password>
<s:submit value="Login"></s:submit>
</s:form>
<form action="login.action" method="post">
UserName:<input type="text" name="userName">
UserPwd :<input type="password" name="userPwd">
<input type="submit" name="sbm" value="OK">
</form>
</body>
</html>
login.jsp文件:
输出结果2种方式如下:
<body>
<s:property value="tip"/>
${sessionScope.user}<br/>
${sessionScope.pwd}<br/>
${requestScope.test}<br/>
</body>
upload.jsp文件:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'upload.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form action="upload.action" method="post" enctype="multipart/form-data">
文件标题:<input type="text" name="title" /><br>
选择文件:<input type="file" name="upload" /><br>
<input value="上传" type="submit" />
</form>
</body>
</html>