一、 构建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国际化
详细请参照第七章