public String execute() {
if ("ping".equals(username)) {
/*
* ActionContext可以获得Servlet对象 但是无法获得response响应对象获得
* 获得的request、session、Application 都是Map类型
*/
ActionContext.getContext().put("用户名", username);
ActionContext.getContext().getSession();
ActionContext.getContext().getApplication();
Map request=(Map)ActionContext.getContext().get(StrutsStatics.HTTP_REQUEST);
} else {
ActionContext.getContext().put("info", "信息");
}
return SUCCESS;
}
第二种: 实现ServletRequestAware,ServletResponseAware,ServletSessionAware接口(第三选择 不推荐)
public class LoginAction extends ActionSupport implements ServletRequestAware
private HttpServletRequest request;
//需实现方法 public void setServletRequest(HttpServletRequest request) { this.request=request; } //response示例
public String execute1() throws IOException {
if ("ping".equals(username)) {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.print("<script type='text/javascript'>alert('验证码输入错误!')</script>");
out.print("<script type='text/javascript'>location.href='/index.jsp'</script>");
out.flush();
out.close();
} else {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.print("<script type='text/javascript'>alert('验证码输入错误!')</script>");
out.flush();
out.close();
}
System.out.println(username);
return SUCCESS;
}
第三种:ServletActionContext(第二选择)
public String execute2() throws IOException {
if ("ping".equals(username)) {
ServletActionContext.getResponse();
ServletActionContext.getRequest();
ServletActionContext.getRequest().getSession();
ServletActionContext.getServletContext();
} else {
}
System.out.println(username);
return SUCCESS;
}
第四种:XXXAware接口(类似于第一种)
public class LoginAction2 extends ActionSupport implements RequestAware,SessionAware, ApplicationAware {
private Map<String, Object> request;
private Map<String, Object> session;
private Map<String, Object> application;
//DI dependency injection
//IoC inverse of control
public String execute() {
request.put("r1", "r1");
session.put("s1", "s1");
application.put("a1", "a1");
return SUCCESS;
}
@Override
public void setRequest(Map<String, Object> request) {
this.request = request;
}
@Override
public void setSession(Map<String, Object> session) {
this.session = session;
}
@Override
public void setApplication(Map<String, Object> application) {
this.application = application;
}
}