目录
1、参数传递
入参:set
出参:get
代码:
public class HelloAction4 implements Action {
//入参
private String name;
public void setName(String name) {
this.name = name;
}
//出参
private String message;
public String getMessage() {
return message;
}
@Override
public String execute() throws Exception {
System.out.println("Params:" + name);
message = "WelCome :" + name;
return SUCCESS;
}
}
JSP:
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false"%>
<html>
<head>
<title>Title</title>
<meta charset="UTF-8">
</head>
<body>
<form action="hello4" method="post">
姓名:<input name="name">
<input type="submit" value="提交">
</form>
${requestScope.message}
</body>
</html>
struts.xml
<action name="hello4" class="com.steven.HelloAction4">
<result name="success">/message.jsp</result>
</action>
2、传递对象
User对象:
public class User {
private String id;
private String desc;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
@Override
public String toString() {
return "User{" +
"id='" + id + '\'' +
", desc='" + desc + '\'' +
'}';
}
}
action:
struts:
<action name="hello4" class="com.steven.HelloAction4">
<result name="success">/message.jsp</result>
</action>
Jsp:
<form action="hello4" method="post">
id:<input name="user.id">
name:<input name="user.desc">
<input type="submit" value="提交">
${requestScope.user}
</form>
3、返回Json
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-json-plugin</artifactId>
<version>2.5.13</version>
</dependency>
返回user的json格式
public class HelloAction5 extends ActionSupport {
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public String execute() throws Exception {
user = new User();
user.setId("001");
user.setDesc("I am first");
return SUCCESS;
}
}
struts.xml:
<action name="hello5" class="com.steven.HelloAction5">
<result type="json">
<param name="root">user</param>
</result>
</action>
注意,有的环境下struts.xml会出现红色的错误,可以忽略:
效果:
4、拦截器
Java:
public class TimeInterceptor implements Interceptor {
@Override
public void destroy() {
}
@Override
public void init() {
}
@Override
public String intercept(ActionInvocation actionInvocation) throws Exception {
long start = System.currentTimeMillis();
String result = actionInvocation.invoke();//将请求放入。进入action
long end = System.currentTimeMillis();
System.out.println("Time:" + (end - start));
return result;
}
}
然后:
那想要在哪一个action里面用这个拦截器呢?
运行后看日志:
注意,这里的拦截器会使系统默认的拦截器无效 ,怎么办:
但是一个个写太麻烦了,有没有写在一些的呢,有,那就是拦截器栈: