我的 Action 类通常会有一个 action
字段变量,该变量在 execute()
方法中赋值:
public class MyAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private String action;
@Override
public String execute() throws Exception {
action = "true";
// code here
return SUCCESS;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
}
在 JSP 中,我检查 action
变量(现在作为请求传递)是否为 null
。如果null
,它将重定向到 Action 类,否则,它将继续呈现页面:
<head>
<c:if test="${action == null}">
<c:redirect url="myaction" />
</c:if>
</head>
我这样做是为了确保用户在尝试非法跳转到 JSP 时首先通过操作。
它按预期工作,但还有其他优雅的方法吗?
最佳答案
从 Action 上下文中获取名称。它具有当前操作的操作映射,其中包括操作名称。您还应该知道,如果没有操作上下文,Struts 标记将无法工作,但前提是 JSP 与映射过滤器一起使用。
<c:set var="actionName"><s:property value="%{#context['struts.actionMapping'].name}"/></c:set>
action name: ${actionName}<br/>
<c:if test="${empty actionName}">
<c:redirect url="myaction" />
</c:if>
编辑:
阻止直接访问 jsp 页面的示例过滤器
public class SimpleFilter implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
if (request.getRequestURI().endsWith(".jsp")) {
DispatcherType dt = request.getDispatcherType();
if (dt == DispatcherType.FORWARD || dt == DispatcherType.INCLUDE)
//handle dispatcher results
filterChain.doFilter(request, response);
else
response.sendError(404, "Direct access to JSP");
} else {
//let's struts handle the request
filterChain.doFilter(request, response);
}
}
@Override
public void destroy() {
}
}
关于java - 在呈现 JSP 之前,用户必须先通过 action,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29555485/