您的位置:首页 > 理论基础 > 计算机网络

通过struts2实现Http只允许POST请求

2015-11-27 17:34 531 查看
通过struts2实现Http只允许POST请求,有需要的朋友可以参考下。

前两天工作中需要做安全限制工作,今天把代码整理一下。

整体的一个思路就是使用Struts2过滤器拦截请求,反射得到对应请求反正只允许POST请求。

先看一下主要拦截器代码:import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.renrendai.common.RequestTypeAnnotation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.StrutsStatics;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
* 过滤器为request类型请求过滤,当方法中有RequestTypeAnnotation注解时,request必须要注解中对应类型一致。
*/
public class RequestTypeInterceptor extends AbstractInterceptor {

private static final long serialVersionUID = -4204585527913002611L;
protected final Log _log = LogFactory.getLog(RequestTypeInterceptor.class);

public String intercept(ActionInvocation invocation) throws Exception {

Action action = (Action) invocation.getAction();
try {
Method method = action.getClass().getMethod(invocation.getProxy().getMethod(), new Class[] {});
Annotation[] annotations = method.getAnnotations();
String methodName = ServletActionContext.getRequest().getMethod();
for (Annotation annotation : annotations) {
if (annotation instanceof RequestTypeAnnotation) {
RequestTypeAnnotation reqTypeAnnotation = (RequestTypeAnnotation) annotation;
if (!reqTypeAnnotation.value().name().equalsIgnoreCase(methodName)) {
// 当前台用户请求类型不是方法注解中对应类型时提示此信息
return "input";
}
}
}
} catch (Exception e) {
_log.error(e);
return "error";
}
return invocation.invoke();
}
}
主要是通过invocation获得调用方法、对应注解及http请求方式。

拦截器配置

<interceptor name="requestType" class="com.xxx.interceptor.RequestTypeInterceptor" />

配置到对应的action上

<action name="xxxTransfer" class="xxxTransfer">
<interceptor-ref name="requestType"/>
<result name="success" type="redirectAction">
<param name="actionName">xxx</param>
<param name="xxx">${xxxx}</param>
</result>
<result name="error">
/exceptions/network-busy/500.html
</result>
<result name="input">
/exceptions/network-busy/404.html
</result>
</action>

在对应action的方法上添加注解

@RequestTypeAnnotation(RequestType.POST)
public String execute() throws Exception{
return SUCCESS;
}


注解设计
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface RequestTypeAnnotation {

RequestType value();
}


enum设计

public enum RequestType {
/**
* post方式的http请求
*/
POST,
/**
* get方式的http请求
*/
GET
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: