我的操作类通常会有一个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
,它将重定向到动作类,否则,它将继续呈现页面:
<head>
<c:if test="${action == null}">
<c:redirect url="myaction" />
</c:if>
</head>
我这样做是为了确保用户在尝试非法跳转到JSP时首先通过操作。
它按预期工作,但有没有其他优雅的方法来做到这一点?
答案 0 :(得分:1)
从动作上下文中获取名称。它具有当前操作的操作映射,其中包括操作名称。另外你应该知道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() {
}
}