자바 의 Struts 2 프레임 워 크 차단기 인 스 턴 스 코드
차단기 의 작은 예 를 보기 전에 sturts 2 의 원 리 를 살 펴 보 겠 습 니 다.
struts 2 자신 은 차단기 가 있 습 니 다.차단 기 를 통 해 사용자 의 요청 을 차단 하고 처리 할 수 있 습 니 다.
차단기 의 작용 은 매우 많다.예 를 들 어:
1.Action 안에 속성 이 있 습 니 다.이 속성 은 action 이 실행 되 기 전에 다른 값 으로 바 꾸 고 싶 습 니 다.차단기 로 해결 할 수 있 습 니 다.
2.예 를 들 어 모든 사람 이 action 을 실행 하기 전에 나 는 그들 이 이 action 을 실행 할 수 있 는 권한 이 있 는 지 확인 할 수 있다.
차단 기 를 설정 하지 않 으 면 모든 action 방법 전에 판정 프로그램 을 설정 해 야 합 니 다.매우 번 거 롭 습 니 다.
차단기 interceptor 는 AOP(절단면 프로 그래 밍)라 는 프로 그래 밍 이념 을 구현 했다.
인 스 턴 스 1:token 차단기 로 중복 제출 제어
token 은 다음 문 제 를 해결 하 는 데 사 용 됩 니 다.
누군가가 양식 을 통 해 데 이 터 를 제출 하면 양식 을 제출 할 때 페이지 의 제출 속도 가 너무 느 리 고 사용자 가 계속 갱신 합 니 다.만약 에 하나의 메커니즘 을 하지 않 으 면 데이터 베이스 에 쓰레기 데이터 가 많이 나 옵 니 다.
폼 제출 은 보통 post 로 작성 합 니 다.(첫 번 째 해결 방법 은 브 라 우 저 에서 중복 제출 여 부 를 알려 줍 니 다)
차단기 해결 방법:
struts 2 는 차단기(interceptor)를--token 이 라 고 정의 했다.
token 의 뜻 은"영패"입 니 다.데 이 터 를 제출 하 시 려 면 제 가 먼저 영패 하 나 를 보 내 드 리 겠 습 니 다.당신 의 영패 가 저 와 맞 을 수 있 으 면 제출 하 세 요.맞 출 수 없 으 면 제출 할 수 없습니다.
token 은 왜 중복 제출 을 방지 할 수 있 습 니까?
답:인터페이스 에 접근 할 때 서버 쪽 session 에서 무 작위 수 를 만 든 다음 에 무 작위 수 를 form 에 기록 하고 데 이 터 를 제출 할 때 session 은 서버 로 가 져 갑 니 다.제출 이 끝 난 후 session 의 값 이 비 워 졌 습 니 다.다시 제출 할 때 이 token 값 이 session 에 존재 하지 않 는 것 을 발견 하면 제출 되 었 음 을 설명 합 니 다.이 때 우호 인터페이스 알림 사용자 가 표 시 됩 니 다.
구현 코드:
struts.xml:
<package name="test" namespace="/javaee" extends="struts-default">
<action name="pinput" class="cn.edu.hpu.action.PinputAction">
<result>/input.jsp</result>
</action>
<action name="person" class="cn.edu.hpu.action.PersonAction">
<result>/addOK.jsp</result>
<interceptor-ref name="defaultStack"></interceptor-ref>
<interceptor-ref name="token"></interceptor-ref>
<result name="invalid.token">/error.jsp</result>
</action>
</package>
PersonAction.java:
package cn.edu.hpu.action;
import com.opensymphony.xwork2.ActionSupport;
public class PersonAction extends ActionSupport {
private String name;
private int age;
@Override
public String execute() throws Exception {
System.out.println("a person added!");
return super.execute();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
input.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>" rel="external nofollow" >
<title>My JSP 'input.jsp' starting page</title>
</head>
<body>
<form action="<%=basePath %>javaee/person" method="post">
name:<input name="name">
age:<input name="age">
<input type="submit" value="add">
</form><br/>
</body>
</html>
addOK.jsp:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'addOK.jsp' starting page</title>
</head>
<body>
add ok!! <br/>
</body>
</html>
error.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'error.jsp' starting page</title>
</head>
<body>
!!! <br>
</body>
</html>
결과:name 과 age 를 입력 하면 인터페이스 addOK.jsp 에 들 어 갑 니 다.콘 솔 은 a person added 를 출력 합 니 다!
다시 제출 할 때 error.jsp 인터페이스 로 이동 하여 중복 제출 할 수 없습니다.
폼 에
<input type="hidden" name="struts.token.name" value="struts.token" />
<input type="hidden" name="struts.token" value="PZOQNKARYVQYDEVGNKTWFBF17735K6AI" />
<!-- -->
원 리 는 제출 페이지 에 token 이 형성 되 었 습 니 다.이 token 은 서버 측 에 대응 하 는 session 에 이미 있 습 니 다.제 가 조금 제출 했 을 때<interceptor-ref name="token"></interceptor-ref>(
token 의 차단기 가 추가 되 었 기 때문에 서버 에서 차단 해 주 었 습 니 다.session 에 token 의 값 이 있 는 지 확인 해 주 었 습 니 다.만약 에 제출 하지 않 았 다 면 session 안에 이 token 값 이 있 었 습 니 다.지난번 에 제출 하면 session 은 token 값 을 지 웁 니 다.페이지 의 token 값 이 서버 의 session 에서 찾 을 수 없 음 을 발견 하면 서버 에서 오류 가 발생 했 습 니 다.error.jsp 로 다시 설정 하여 오류 정 보 를 표시 합 니 다.인 스 턴 스 2:사용자 정의 차단기
struts.xml:
<pre name="code" class="html"><pre name="code" class="html"><pre name="code" class="html"><pre name="code" class="html"><?xml version="1.0" encoding="GBK" ?>
<!-- struts2 DTD -->
<!DOCTYPE struts PUBLIC
"-//apache Software Foundation//DTD Struts Configuation 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<!-- struts struts2 -->
<struts>
<constant name="struts.devMode" value="true"></constant>
<constant name="struts.i18n.encoding" value="UTF-8"></constant>
<!-- -->
<constant name="struts.ognl.allowStaticMethodAccess" value="true"></constant>
<package name="test" namespace="/" extends="struts-default">
<interceptors>
<interceptor name="my" class="cn.edu.hpu.interceptor.MyInterceptor"></interceptor>
</interceptors>
<action name="test" class="cn.edu.hpu.action.TestAction">
<result>/test.jsp</result>
<interceptor-ref name="my"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</action>
</package>
</struts>
TestAction.java:
package cn.edu.hpu.action;
import com.opensymphony.xwork2.ActionSupport;
public class TestAction extends ActionSupport{
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return super.execute();
}
}
MyInterceptor.java:
package cn.edu.hpu.interceptor;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class MyInterceptor implements Interceptor{
public void destroy() {
}
public void init() {
}
// ( action )
public String intercept(ActionInvocation invocation) throws Exception {
long start=System.currentTimeMillis();
String r=invocation.invoke();
long end=System.currentTimeMillis();
System.out.println("Action Time="+(end-start));
return r;
}
}
접근:http://localhost:8080/struts2_LanJieQi/test 후콘 솔 출력:
Action Time=200
이상 은 이 글 의 전체 내용 입 니 다.본 논문 의 내용 이 여러분 의 학습 이나 업무 에 어느 정도 참고 학습 가치 가 있 기 를 바 랍 니 다.궁금 한 점 이 있 으 시 면 댓 글 을 남 겨 주 셔 서 저희 에 대한 지지 에 감 사 드 립 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
한 편의 문장으로 Struts2의 유형 전환을 해결하다우리는 HTTP를 통해 백그라운드에 제출된 데이터가 모두 문자열의 형식이라는 것을 알고 있으며, 우리가 필요로 하는 데이터 형식은 당연히 문자열 형식 하나만 있는 것이 아니다.그래서 우리는 유형 전환이 필요하다!다음...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.