note

Struts2 유효성 검사 본문

JSP/Struts2

Struts2 유효성 검사

투한 2012. 2. 21. 14:27









struts-ch4.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
	<package name="ch4-4" namespace="/ch4" extends="struts-default">
		<!-- 데이터 전송 -->
		<action name="helloWorld3" class="com.ch4.action.HelloWorld3">
			<interceptor-ref name="params" />
				<result name="success">hello.jsp</result>
		</action>
		<!-- Action 인터페이스 사용 및 유효성 검사 -->
		<action name="helloWorld4" class="com.ch4.action.HelloWorld4">
			<interceptor-ref name="params" />
			<result name="input">name4.jsp</result>
			<result name="success">hello.jsp</result>
		</action>
	</package>	
</struts>



name4.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>데이터 전송</title>
</head>
<body>
<font color="red">${message}</font>
<form action="helloWorld4.action">
	<input type="text" name="name" value="${param.name}">
	<input type="submit" value="전송">
</form>
</body>
</html>


HelloWorld4.java
package com.ch4.action;

import com.opensymphony.xwork2.Action;

public class HelloWorld4 implements Action{
	
	private String message;
	private String name;
	
	@Override
	public String execute() throws Exception {
		//유효성 검사
		if(name == null || "".equals(name) ||  "World".equals(name)){
			message = "이름이 없거나 'World'라는 이름을 쓸 수 없습니다.";
			return INPUT;
		}
		message = "Hello,"+name;
		return SUCCESS;
	}
	public String getMessage() {
		return message;
	}

	public void setName(String name) {
		this.name = name;
	}

	

}






ActionSupport를 사용하는게 더 바람직하다