虽然Struts2提供了ActionContext来访问Servlet API,但这种访问毕竟不是直接获得Servlet API的实例。为了在Action中直接访问Servlet API,Struts2还提供了如下几个接口。
① ServletContextAware : 实现该接口的Action可以直接访问Web应用的ServletContext实例。实现该接口需要实现方法setServletContext(ServletContext context)。
② ServletRequestAware : 实现该接口的Action可以直接访问用户请求的HttpServletRequest实例。实现该接口需要实现方法setServletRequest(HttpServletRequest request)。
③ServletResponseAware : 实现该接口的Action可以直接访问服务器响应的HttpServletResponse实例。实现该接口需要实现方法setServletResponse(HttpServletResponse response)。
Login.java :
public class Login implements ServletRequestAware{
private HttpServletRequest request;
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;
}
public String execute(){
if(getUsername().equals("scott")&& getPassword().equals("tiger")){
HttpSession session=request.getSession();
session.setAttribute("username",getUsername());
return "success";
}
return "login";
}
@Override
public void setServletRequest(HttpServletRequest request) {
this.request=request;
}
}
ok.jsp :
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<%
Object obj=session.getAttribute("username");
if(obj==null){
response.sendRedirect("login.jsp");
}
%>
login success! welcome ${username}...
</body>
</html>