특별한딸기이야기

예외처리(프로그램적인 방법) 본문

딸기 공부방/struts and spring

예외처리(프로그램적인 방법)

특별한녀석 2008. 11. 13. 10:34


struts-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC
 "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN"
 "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">
<struts-config>
 <form-beans>  
  <form-bean name="memberForm" type="org.apache.struts.action.DynaActionForm">
   <form-property name="id" type="java.lang.String"/>
   <form-property name="password" type="java.lang.String"/>
   <form-property name="name" type="java.lang.String"/>
   <form-property name="phone" type="java.lang.String"/>
  </form-bean> 
 </form-beans>
 <global-forwards>
  <forward name="success" path="/insertResult.do" module="" redirect="true"/>
 </global-forwards>
 <action-mappings>
  <action path="/insertForm" forward="/InsertForm.jsp"/>
  <action path="/insertResult" forward="/InsertResult.jsp"/>
  <action path="/insert" type="com.tistory.special0strawberry.MemberInserAction"
   name="memberForm" scope="request" validate="false">
   <forward name="fail" path="/insertForm.do"/>
  </action>
 </action-mappings>
</struts-config>
<!-- 특별히 바뀐 부분은 없다. -->

MemberInserAction class

package com.tistory.special0strawberry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.util.RequestUtils;

import com.tistory.special0strawberry.Member;

public class MemberInserAction extends Action
{
 @Override
 public ActionForward execute(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response)
   throws Exception {

  //DynaActionForm use and Exception
  ActionErrors errors = new ActionErrors();
  DynaActionForm member = (DynaActionForm)form;
  String id = member.getString("id");
  ActionForward forward = null;
  
  try
  {
   if(id == null || id.length() == 0)
   {
    throw new MemberInsertException();
   }  
  
   System.out.println("member.id : " + id);
   System.out.println("member.password : " + member.getString("password"));
   System.out.println("member.name : " + member.getString("name"));
   System.out.println("member.phone : " + member.getString("phone"));
   
   forward = mapping.findForward("success");
  }
  catch(Exception e)
  {
   errors.add("id", new ActionMessage("id 입력이 이상합니다.", false));
   forward = mapping.findForward("fail");
  }
  
  this.saveErrors(request, errors);
   
  return forward;
 }
}
// 에러가 발생하면 catch에서 처리할 수 있다. 여기서는 id에 관한 부분만 처리하였으나 추가적인 부분도 고려할 수 있겠다.

InsertForm.jsp

<%@
 page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"
%>
<%@
 page import="org.apache.struts.action.*"
%>
<%@
 page import="java.util.*"
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%!
 private String getError(HttpServletRequest request, String propname)
 {
  String strmessage = "";
  ActionMessages messages = (ActionMessages)request.getAttribute("org.apache.struts.action.ERROR");
  
  if(messages != null)
  {
   Iterator propnames = messages.properties();
   
   while(propnames.hasNext())
   {
    String propertyname = (String)propnames.next();
    
    if(propertyname.equals(propname))
    {
     ActionMessage message = (ActionMessage)(messages.get(propertyname).next());
     String key = message.getKey();
     
     try
     {
      ResourceBundle rb = ResourceBundle.getBundle("MessageResource");
      strmessage = rb.getString(propertyname);
     }
     catch(Exception e)
     {
      strmessage = key;
     }
     break;
    }
   }
  }
  
  return strmessage;
 }
%>
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
  <title>
   Insert Form
  </title>
 </head>
 <body>
  <form action="/Tytolee/insert.do" name="insert">
   Id :
   <input type="text" name="id"/>
   <%=getError(request, "id") %>
   <br/>
   Password :
   <input type="password" name="password"/>
   <%=getError(request, "password") %>
   <br/>
   Name :
   <input type="text" name="name"/>
   <%=getError(request, "name") %>
   <br/>
   Phone :
   <input type="text" name="phone"/>
   <%=getError(request, "phone") %>
   <br/>
   <input type="submit" value="확인"/>
  </form>
 </body>
</html>

<!-- getError 함수를 살펴보면 request에 저장된 에러 메세지를 받아와서 처리하는 함수이다. 조금 복잡한 면이 있다. 변수명에 신경써서 본다면(s가 붙고 안붙고를 잘 생각하면서 보면...) 얼추 돌아가는 장면이 보인다. 개인적으로 별로 쓰고 싶은 생각이 없는 부분... ^^;;; -->

MemberInsertException class

package com.tistory.special0strawberry;

public class MemberInsertException extends Exception
{

 public MemberInsertException() {
  super();
  // TODO Auto-generated constructor stub
 }

 public MemberInsertException(String s) {
  super(s);
  // TODO Auto-generated constructor stub
 } 
}

// 특별히 하는 것 없는 클래스다. -0-;;;