下载struts:http://struts.apache.org/development/2.x/
本次使用的版本:struts-2.3.14
最小的struts2模式:
步骤:
1.增加核心jar包
struts2-core-2.x.x.jar :Struts 2框架的核心类库
xwork-2.x.x.jar :XWork类库,Struts 2在其上构建
ognl-2.6.x.jar :对象图导航语言(Object Graph Navigation Language),Struts 2框架使用的一种表达式语言
freemarker-2.3.x.jar :Struts 2的UI标签的模板使用FreeMarker编写
commons-logging-1.1.x.jar :ASF出品的日志包,Struts 2框架使用这个日志包来支持Log4J和JDK 1.4+的日志记录。
commons-fileupload : 拷进去
commons-lang3-3.1,jar
javassist-3.11.0GA.jar
commons-io-2.0.1.jar
2.web.xml中配置加入struts2的过滤器
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>struts</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<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>
</web-app>
3.在classes目录中增加struts.xml,还可以存在struts.properties,用于运行时的配置文件
<?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>
<package name="mystruts2" namespace="/" extends="struts-default">
<action name="helloworld" class="org.senssic.action.HelloWorldAction">
<result name="success">/page/hello.jsp</result>
</action>
</package>
</struts>
4.编写action类
package org.senssic.action;
public class HelloWorldAction {
private String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String execute() throws Exception {
this.msg = "你说王子是因为水晶鞋而注意到灰姑娘的么,还是因为她漂亮。";
return "success";
}
}
此处为什么非要写execute和为啥是success呢,其实都可以写其他方法和使用返回其他字符,我们也可以直接实现Action接口,这样使用起来就更加明良和易懂了,但现在这个pojo和Action没有一点关系,通过反射来做的,我们实现Action是为了更加理解,和方便使用,我看进到Acion接口就明白了
package com.opensymphony.xwork2;
public abstract interface Action
{
public static final String SUCCESS = "success";
public static final String NONE = "none";
public static final String ERROR = "error";
public static final String INPUT = "input";
public static final String LOGIN = "login";
public abstract String execute()
throws Exception;
}
五种结果和一个execute方法,一切就恍然大悟
5.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>
${msg}
</body>
</html>
注:如果遇到 There is no Action mapped for namespace [/] and action name [] associated wi,的错误,请检查struts文件和是否写 了welcome欢迎页面
Action说明
有一个无参的构造方法
有一个excute()普通的一个POJO
如何编写
直接写一个有execute方法的POJO
实现Action接口
继承ActionSupport
Action的属性注入:
action动态方法的三种调用
第一种方式:指定method属性
然后我们通过url访问业务方法:http://localhost:8080/senssic?method=Mdemo
运行结果:
第二种方式:动态方法调用(DMI)
用这种方法需要设置一个常量
<constant name="struts.enable.DynamicMethodInvocation" value="true" />
动态方法调用是指表单元素的action并不是直接等于某个Action的名字,而是以如下形式来指定Form的action属性
<!-- action属性为action!methodName的形式 -->
action = "action!methodName.action"
在struts.xml中定义如下Action
<action name="student"class="com.itmyhome.StudentAction">
<resultname="add">/add.jsp</result>
<resultname="delete">/delete.jsp</result>
</action>
StudentAction代码为
public class StudentAction extends ActionSupport {
public String add(){
return "add";
}
public String delete(){
return "delete";
}
}
则在JSP中用如下方式调用方法
<a href="student!add.action"> 新增学生</a>
<a href="student!delete.action"> 删除学生</a>
第三种方式:通配符(推荐使用)
<action name="student*" class="com.itmyhome.StudentAction" method="{1}">
<result name="{1}">/student{1}.jsp</result>
</action>
<a href="studentadd"> 新增学生</a>
<a href="studentdelete"> 删除学生</a>
studentadd就会调用StudentAction中的add方法 然后跳转到studentadd.jsp
studentdelete就会调用StudentAction中的delete方法 然后跳转到studentdelete.jsp
Struts2支持动态方法调用,它指的是一个Action中有多个方法,系统根据表单元素给定的action来访问不同的方法,而不用写多个Action。
result处理结果
<package ....>
<global-results>
<result name="message">/message.jsp</result>
</global-results>
</package>
下面是redirectAction 结果类型的例子,如果重定向的action中同一个包下:
<result type="redirectAction">helloworld</result>
如果重定向的action在别的命名空间下:
<result type="redirectAction">
<param name="actionName">helloworld</param>
<param name="namespace">/test</param>
</result>
如果没有指定result的name属性,默认值为success。
在result中还可以使用${属性名}表达式,表达式里的属性名对应action中的属性。如下:
<result type="redirect">view.jsp?id=${id}</result>
result的类型在struts-defult.xml中,位于core.jar包中
struts2的常量属性配置
常量可以在struts.xml或struts.properties中配置,建议在struts.xml中配置,两种配置方式如下:
struts.xml
<struts>
<constant name="struts.action.extension" value="do"/>
</struts>
struts.properties
struts.action.extension=do
通常,struts2按如下搜索顺序加载struts2常量:
struts-default.xml
struts-plugin.xml
struts.xml
struts.properties
web.xml
如果在多个文件中配置了同一个常量,则后一个文件中配置的常量值会覆盖前面文件中配置的常量值.
在struts-core.jar中配置了默认的属性
一些常用的struts配置:
<!-- 指定默认编码集,作用于HttpServletRequest的setCharacterEncoding方法 和freemarker 、velocity的输出 -->
<constant name="struts.i18n.encoding" value="UTF-8"/>
<!-- 该属性指定需要Struts 2处理的请求后缀,该属性的默认值是action,即所有匹配*.action的请求都由Struts2处理。
如果用户需要指定多个请求后缀,则多个后缀之间以英文逗号(,)隔开。 -->
<constant name="struts.action.extension" value="do"/>
<!-- 设置浏览器是否缓存静态内容,默认值为true(生产环境下使用),开发阶段最好关闭 -->
<constant name="struts.serve.static.browserCache" value="false"/>
<!-- 当struts的配置文件修改后,系统是否自动重新加载该文件,默认值为false(生产环境下使用),开发阶段最好打开 -->
<constant name="struts.configuration.xml.reload" value="true"/>
<!-- 开发模式下使用,这样可以打印出更详细的错误信息 -->
<constant name="struts.devMode" value="true" />
<!-- 默认的视图主题 -->
<constant name="struts.ui.theme" value="simple" />
<!– 与spring集成时,指定由spring负责action对象的创建 -->
<constant name="struts.objectFactory" value="spring" />
<!–该属性设置Struts 2是否支持动态方法调用,该属性的默认值是true。如果需要关闭动态方法调用,则可设置该属性为false。 -->
<constant name="struts.enable.DynamicMethodInvocation" value="false"/>
struts2的action中获取jsp的内置对象
1.使用ServletActionContext接口
2.实现ServletRequestAware/ServletResponseAware接口3.使用ActionContext直接获取request或response对象
package org.senssic.action;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsStatics;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.ActionContext;
public class HelloWorldAction implements ServletRequestAware {
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private String msg;
private HttpServletRequest request;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String execute() throws Exception {
this.msg = "你说王子是因为水晶鞋而注意到灰姑娘的么,还是因为她漂亮。";
return "success";
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public String Mdome() throws Exception {
this.msg = "带你长发齐腰,用来下面可好?";
// 第一种,最常用
HttpServletRequest req = ServletActionContext.getRequest();
req.setAttribute("one", "窗前明月光");
// 第二种实现相应的接口(ActionSupport implements
// ServletRequestAware,ServletResponseAware,ApplicationAware,SessionAware),接口通过IOC机制注入
request.setAttribute("two", "池塘边的榕树上,大大的花雪");
// 第三种使用ActionContext接口直接获取request或response对象,其实ServletActionContext就是
// 实现ActionContext所以和第一种方法区别不大,也就是第一种方法的原理
HttpServletRequest servletRequest = (HttpServletRequest) ActionContext
.getContext().get(StrutsStatics.HTTP_REQUEST);
servletRequest.setAttribute("three", "头好痛啊,烦死了");
return "success";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// 通过ServletRequestAware接口通过IOC机制注入Request对象
// 该方法必须要实现,而且该方法是自动被调用
// 这个方法在被调用的过程中,会将创建好的request对象通过参数的方式传递给你,你可以用来赋给你本类中的变量,然后request就可以使用了
// 注意:setServletRequest()方法一定会再execute()方法被调用前执行
@Override
public void setServletRequest(HttpServletRequest arg0) {
this.request = arg0;
}
}
至于为什么第二种和第三种差别不大