데이터 검증은 프로젝트 개발에 없어서는 안될 부분입니다. 사용자가 로그인하고 비밀번호 확인이 필요합니다. 물론, 당신이해야 할 일은 사용자가 입력 한 컨텐츠를 얻은 다음 내용을 확인하는 것입니다. 일반적으로 데이터베이스에서 읽은 다음 확인하십시오. 잘못된 경우 프롬프트 메시지가 표시되며 올바른 경우 사용자의 기본 인터페이스가 입력됩니다.
다음은 다음 단계를 설명하는 간단한 예입니다.
1. 색인 양식
다음과 같이 코드를 복사하십시오. <%@ page language = "java"contenttype = "text/html; charset = utf-8"
PageEncoding = "UTF-8"%>
<%
문자열 path = request.getContextPath ();
String BasePath = request.getScheme ()+": //"+request.getServerName ()+":"+request.getServerport ()+path+"/";
%>
<! doctype html public "-// w3c // dtd html 4.01 Transitional // en" "http://www.w3.org/tr/html4/loose.dtd">
<html>
<헤드>
<meta http-equiv = "content-type"content = "text/html; charset = utf-8">
<base href = "< %= basepath %>"/>
<title> 제목을 여기에 삽입하십시오 </title>
</head>
<body>
<H1> 데모 </h1>
<form action = "user/user! check"method = "post">
이름 : <input type = "text"name = "user.name"> </input>
<br/>
age : <입력 유형 = "text"name = "user.age"> </input>
<br/>
<입력 유형 = "제출"값 = "제출"/>
</form>
</body>
</html>
제출시, user.name 및 user.age의 두 변수가 서버로 전달되면 struts.xml 파일 구성의 해당 조치가 호출됩니다.
2. struts.xml 구성
코드 코드를 다음과 같이 복사하십시오. <? xml version = "1.0"encoding = "utf-8"?>
<! doctype struts public
"-// Apache Software Foundation // dtd Struts 구성 2.0 // en"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name = "struts.devmode"value = "true" />
<package name = "front"namespace = "/user"확장 = "struts-default">
<액션 이름 = "사용자">
<결과> /success.jsp </result>
<result name = "error">/error.jsp </result>
</action>
</패키지>
</struts>
분명합니다 - 성공이 반환되면 성공. jsp가 호출됩니다. error.jsp는 호출됩니다.
3. 점검 방법의 내용이 작동합니다
다음과 같이 코드를 복사하십시오 : public String check () {
System.out.println ( "name ="+user.getName ());
System.out.println ( "age ="+user.getage ());
if (user.getName (). equals ( "admin") && user.getage () == 20) {
반환 성공;
}또 다른{
this.addfielderror ( "name", "name is error");
this.addfielderror ( "이름", "이름은 너무 길다");
반환 오류;
}
}
여기서 우리는 Addfielderror 방법을 불렀습니다
4.error.jsp 페이지
다음과 같이 코드를 복사하십시오. <%@ page language = "java"contenttype = "text/html; charset = utf-8"
PageEncoding = "UTF-8"%>
< %@taglib uri = "/struts-tags"prefix = "s" %>
<! doctype html public "-// w3c // dtd html 4.01 Transitional // en" "http://www.w3.org/tr/html4/loose.dtd">
<html>
<헤드>
<meta http-equiv = "content-type"content = "text/html; charset = utf-8">
<title> 제목을 여기에 삽입하십시오 </title>
</head>
<body>
<H2> 검증 실패 </h2>
<s : 속성 값 = "errors.name [0]"/>
<br>
<s : 속성 값 = "errors.name [1]"/>
<S : 디버그> </s : 디버그>
</body>
</html>
내부의 세 번째 줄은 지정된대로 struts2가 추가 된 레이블 라이브러리이며 s로 시작합니다.
네 번째 ~ 마지막 줄과 여섯 번째 줄은 핵심 포인트입니다. 해당 오류. 이름 [0]은 이름이 3의 addfielderror 메소드를 통해 이름 속성에 넣은 오류이며 오류. 이름 [1]은 분명히 이름이 너무 깁니다. 세 번째 마지막 줄은 디버그 정보입니다.
전체 효과는 마침내 다음과 같이 표시됩니다.
위는 Struts2에서 간단한 데이터 검증의 전체 내용입니다. 나는 그것이 당신에게 참조를 줄 수 있기를 바랍니다. 그리고 당신이 wulin.com을 더 지원할 수 있기를 바랍니다.