LookupDispatchAction은 getKeyMethodMap() 메서드를 구현하고 리소스 번들의 키와 메소드명을 매핑한다.
파라미터로 메소드 이름을 전달하면 그와 같은 메소드 명을 찾아서 실행하는 것이다.
 HTML 폼에서 동일한 이름을 가진 여러 개의 버튼을 사용하는 경우에 유용하다. 이 버튼의 이름은 해당하는 ActionMapping의 매개 변수 속성에 의해 지정된다.

작업 순서

1) mapping 할 메시지번들을 생성한다.
2) LookupDispatchAction을 상속받는 Class를 만들고 getKeyMethodMap() 메소들를 Override한다.
3) struts-config-lookup.xml 파일을 작성한다.
4) web.xml 파일에 struts-config-lookup.xml 파일 설정을 추가한다.

1. mapping 할 메시지 번들 파일(.properties)를 만든다.

메모장에 아래와 같이 추가하고 InfoMessageResource.properties 파일로 저장한다.
#은 주석을 의미한다.

# struts1 lookup message bundle
# file name : InfoMessageResource.properties

lookup.register = 등록
lookup.list = 리스트
lookup.query = 쿼리
lookup.update = 갱신
lookup.delete = 삭제

# 국제회(Locale) 표준코드 (Unicode)로 변환
# native2ascii [-encoding 코드값] 원시파일 대상파일
# 코드값 : euc-kr, ksc5601, ms949, utf-16

# native2ascii -encoding euc-kr InfoMessageResource.properties InfoMessageResource_ko.properties

이 파일을 이클립스 안으로 복사해서 붙여 넣는다.(이클리스 안에서 properties 파일을 오류를 발생하기 때문이 이렇게 한다.)

그리고 이 파일을 이클립스에서 열을 경우 한글이 깨져서 나오는것을 알 수 있다. 이 문제를 해결하기 위해서 인코딩 타입을 euc-kr로 파일을 native2ascii 변환하는 작업을 해주어야 한다.

변화작업은 다음 글을 참조한다.
http://thinkingblog.tistory.com/14

InfoMessageResource.properties 파일이 있는 위치로 이동한다음에 그대로 작업을 진행하면 된다.

변환 작업을 통해 InfoMessageResource_ko.properties 파일을 생성해 낸다.

변환된 내용

# struts1 lookup message bundle
# file name : InfoMessageResource.properties

lookup.register = \ub4f1\ub85d
lookup.list = \ub9ac\uc2a4\ud2b8
lookup.query = \ucffc\ub9ac
lookup.update = \uac31\uc2e0
lookup.delete = \uc0ad\uc81c

# \uad6d\uc81c\ud68c(Locale) \ud45c\uc900\ucf54\ub4dc (Unicode)\ub85c \ubcc0\ud658
# native2ascii [-encoding \ucf54\ub4dc\uac12] \uc6d0\uc2dc\ud30c\uc77c \ub300\uc0c1\ud30c\uc77c
# \ucf54\ub4dc\uac12 : euc-kr, ksc5601, ms949, utf-16

# native2ascii -encoding euc-kr InfoMessageResource.properties InfoMessageResource_ko.properties

2. InfoLookupDispatchAction.java 파일 작성.

package com.myhome.lookup;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.LookupDispatchAction;

import com.myhome.info.beans.InfoFormBean;
import com.myhome.info.dao.InfoDAO;
import com.myhome.info.dto.InfoDTO;

public class InfoLookupDispatchAction  extends LookupDispatchAction {
 
 
@Override
 protected Map<String,String> getKeyMethodMap() {
  
  Map<String,String> map = new HashMap<String, String>();
  map.put("lookup.register", "register");  
//메시지번들에 있는 키와 같아야 한다. 뒤에는 메소드 명이다.
  map.put("lookup.list", "list");
  map.put("lookup.query", "query");
  map.put("lookup.update", "update");
  map.put("lookup.delete", "delete");
  return map;
 }

 public ActionForward register(ActionMapping mapping,
     ActionForm form,
     HttpServletRequest request,
     HttpServletResponse response)
     throws Exception{

 /*form parameter를 bean으로 받는다*/
  InfoFormBean bean = new InfoFormBean();
  bean.setName(request.getParameter("name"));
  bean.setSex(request.getParameter("sex"));
  bean.setTel(request.getParameter("tel"));
  
  /*bean property 를 dto로 복사한다.*/
  InfoDTO dto = new InfoDTO();
  BeanUtils.copyProperties(dto, bean);
  dto.setWdate(this.getWdate());
  
  /*info table에 연동한다.*/
  
  new InfoDAO().register(dto);
  
  /*result.jsp로 포워드하기 위해 리퀘스트 영역에 dto를 binding한다
  * */
  request.setAttribute("dto", dto);
  
  return mapping.findForward("result");
 }
 
 public ActionForward list(ActionMapping mapping,
     ActionForm form,
     HttpServletRequest request,
     HttpServletResponse response)
     throws Exception{
  
  List<InfoDTO> list = null;
  
  list = new InfoDAO().getAllQuery();
  
  request.setAttribute("list", list);
  
  return mapping.findForward("list");
 }
 
 public ActionForward query(ActionMapping mapping,
     ActionForm form,
     HttpServletRequest request,
     HttpServletResponse response)
     throws Exception{
  InfoFormBean bean = (InfoFormBean)form;
  InfoDTO dto = new InfoDTO();
  BeanUtils.copyProperties(dto, bean);
  
  //쿼리된 object를 리퀘스트 영역에 바인딩 한다.
  
  request.setAttribute("dto", new InfoDAO().getQuery(dto));
  
  return mapping.findForward("query");
 }
 
 public ActionForward update(ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception{
  /*form parameter를 InfoFormBean으로 받는다*/
  
  /**
  *  ActionForm의 역할
  *   Form parameter의 정보를 참조하기 위해
  *   ActionForm의 객체를 초기화 한다 - reset()
  * 
  *   form parameter의 정보를 받아 유효성 검사를 실시한다 - validate()
  * 
  *   참조한 폼 정보를 form-bean에 설정도니 bean으로 전달한다.
  * */

 
  InfoFormBean bean = (InfoFormBean)form;
  
  /*bean의 객체를 Entity(DTO)로 property를 복사한다.*/
  InfoDTO dto = new InfoDTO();
  BeanUtils.copyProperties(dto, bean);
  
  new InfoDAO().update(dto);
  
  
  return mapping.findForward("update");
 }
 
 public ActionForward delete(ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception{
 
  InfoFormBean bean = (InfoFormBean)form;
  
  /*bean의 객체를 Entity(DTO)로 property를 복사한다.*/
  InfoDTO dto = new InfoDTO();
  BeanUtils.copyProperties(dto, bean);
  new InfoDAO().delete(dto);
  return mapping.findForward("delete");
 }
 protected String getWdate(){
  return new java.text.SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date());
 }

}

3. struts-config-lookup.xml 파일 작성

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

<struts-config>
 <action-mappings>
  <action path = "/lookupIndex"
    type = "org.apache.struts.actions.ForwardAction"
    parameter="/lookup/register.jsp"/>
  
  <!--
   unknown은 input속성을 대체하기 위한 속성이다.
   입력폼이 여러개 발생할 때 사용된다.
   template.jsp는 list.do로 보내면 어디로 가야 할지 모르기때문에
  -->

  
  <action path = "/lookup"
    name = "bean"
    scope = "request"
    unknown = "true"
    parameter = "method"
    type = "com.myhome.lookup.InfoLookupDispatchAction">
<!-- method 라는 value를 받아서 type에 선언된 클래스로 이동하고 getKeyMethodMap() 메소드를 통해서 InfoMessageResource.properites 파일안에 맵핑 되는 메소드를 실행하게 된다.-->
   
   <forward name="result" path = "/lookup/result.jsp"/>
   <forward name="list" path = "/lookup/list.jsp"/>
   <forward name="query" path = "/lookup/modify.jsp"/>
   <forward name="update" path = "/lookup/template.jsp"/>
   <forward name="delete" path = "/lookup/template.jsp"/>
  
  </action>
 </action-mappings>
 
 
<!-- Message Resources Definitions -->
 <!-- .property 파일을 설정 -->
 
<message-resources parameter="com.myhome.lookup.InfoMessageResource" />
 
</struts-config>

4. web.xml 에 struts-config-lookup.xml 파일을 추가한다.

<init-param>
 <param-name>config</param-name> 
 <param-value>
 
  /WEB-INF/struts-config-lookup.xml 
</param-value>   /WEB-INF/(기본베이스 - 다른폴더일때는 경로를 설정해주어야 함)폴더 안에 struts-config.xml파일 위치 지정  - 여기까지 작성후 struts-config.xml파일을 생성-->
</init-param>

5. jsp 파일에서 값을 넘겨 줄때

 <form method="POST" name="listform" action="lookup.do">
     <input type="hidden" name="method" value="쿼리">

lookup.query = 쿼리

InfoMessageResource_ko.properties  파일에서 한글로 설정 쿼리 부분과 일치하고, 그 일치한 메소드를 실행한다.

자세한 내용은 파일을 참조 한다.





'FrameWork > Struts1' 카테고리의 다른 글

struts1 커스터마이징하여 사용하기.  (0) 2009.11.11
Struts1 FileDownload  (0) 2009.08.18
Struts1 fileUpload  (0) 2009.08.18
Struts1의 Action 4  (0) 2009.08.16
Struts1의 Action 2  (0) 2009.08.12
Struts1의 Action 1  (0) 2009.07.27
Struts1에서 ActionForm 사용하기.  (0) 2009.07.25
Struts1 에서 iBatis 사용하기  (0) 2009.07.05
Struts 1 을 사용하여 간단한 회원가입, 리스트 불러오기.  (0) 2009.07.05
Struts1 개발환경 설정.  (0) 2009.07.05


Struts1의 다양한 Action들


struts-extras-1.3.8.jar에서 지원하며 다양한 액션을 구현 할 수 있다.

■ Action 상속 관계도



1. ForwardAction



 struts-config.xml 의 ActionMapping에서 action 요소에 parameter 속성으로 지정한 URL로 forward 하게 된다. 직접 해당 URL을 호출하면 RequestProcessor을 통해 바로 View page로 이동하지만
ForwardAction을 사용하게 되면 스트럿츠 컨트롤러 서블릿의 기능(폼 빈의 처리 등)을 사용 할 수 있다는 장점이 있다.

<!--직접 해당 URL 호출-->
<action path="/info/index" forward="/info/register.jsp"/>

<!-- ForwardAction을 사용해서 ViewPage요청 -->
<action path="/info/index"
            type=“org.apache.struts.actions.ForwardAction”
            parameter="/info/register.jsp” />


2. IncludeAction.

 

 ForwardAction과 동일한 방식이며 비즈니스 로직에서 처리 후 RequestProcessor로 진입하지 않고 바로 페이지로 이동한다. View page로의 빠른 이동이 가능하다는 장점이 있지만, Request Prcessor를 통과 하지 않기 때문에 page Encoding,validator 등 을 사용할 수 없다.

<!-- IncludeActiond 사용 -->
<action path="/index"
type = "org.apache.struts.actions.IncludeAction"
parameter = "/info/register.jsp"/>

3. DispatchAction

 하나의 Action에서 두개 이상의 ActionForward를 구현할 때 사용된다.


 JSP form 페이지에서 name이 struts-config.xml 에서 설정해논 parameter의 이름과 일치해야 실행된다.

- struts-config.xml

.... 생략 ....

    <action-mappings>
   
   <action path = "/dispatchIndex"
    type = "org.apache.struts.actions.ForwardAction"
    parameter = "/dispatch/register.jsp"/>
    
  <!-- unknow 은 input 속성을 대체하기 위한 속성이다. 입력 폼이 여러개 발생할 때 사용된다.  -->
  <action path = "/dispatch"
    name = "bean"
    scope = "request"
    unknown = "true"
    parameter = "method"
    type = "com.myhome.dispatch.InfoDispatchAction">
    
<!-- forward 이름이 메소드 마다 달라야 한다 -->
   <forward name="result" path = "/dispatch/result.jsp"/>
   <forward name="list" path = "/dispatch/list.jsp"/>
   <forward name="query" path = "/dispatch/modify.jsp"/>
   <forward name="update" path = "/dispatch/template.jsp"/>
   <forward name="delete" path = "/dispatch/template.jsp"/>
  </action>
    </action-mappings>

.... 생략 ....

- InfoDispatchAction .java

//하나의 Action에서 여러개의 action을 구현했다.

package com.myhome.dispatch;

import java.util.List;

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

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.myhome.info.beans.InfoFormBean;
import com.myhome.info.dao.InfoDAO;
import com.myhome.info.dto.InfoDTO;


public class InfoDispatchAction extends DispatchAction{
 
 public ActionForward register(ActionMapping mapping,
          ActionForm form,
          HttpServletRequest request,
          HttpServletResponse response)
          throws Exception{
  
  /*form parameter를 bean으로 받는다*/
  InfoFormBean bean = new InfoFormBean();
  bean.setName(request.getParameter("name"));
  bean.setSex(request.getParameter("sex"));
  bean.setTel(request.getParameter("tel"));
  
  /*bean property 를 dto로 복사한다.*/
  InfoDTO dto = new InfoDTO();
  BeanUtils.copyProperties(dto, bean);
  dto.setWdate(this.getWdate());
  
  /*info table에 연동한다.*/
  
  new InfoDAO().register(dto);
  
  /*result.jsp로 포워드하기 위해 리퀘스트 영역에 dto를 binding한다*/
  request.setAttribute("dto", dto);
  
  return mapping.findForward("result");
 }
 
 public ActionForward list(ActionMapping mapping,
         ActionForm form,
         HttpServletRequest request,
         HttpServletResponse response)
         throws Exception{
  
  List<InfoDTO> list = null;
  
  list = new InfoDAO().getAllQuery();
  
  request.setAttribute("list", list);

  return mapping.findForward("list");
 }
 
 public ActionForward query(ActionMapping mapping,
         ActionForm form,
         HttpServletRequest request,
         HttpServletResponse response)
         throws Exception{
  InfoFormBean bean = (InfoFormBean)form;
  InfoDTO dto = new InfoDTO();
  BeanUtils.copyProperties(dto, bean);
  
  //쿼리된 object를 리퀘스트 영역에 바인딩 한다.
  
  request.setAttribute("dto", new InfoDAO().getQuery(dto));

  return mapping.findForward("query");
 }
 
 public ActionForward update(ActionMapping mapping,
         ActionForm form,
         HttpServletRequest request,
         HttpServletResponse response)
         throws Exception{
  /*form parameter를 InfoFormBean으로 받는다*/
  
  /**
   *  ActionForm의 역할
   *   Form parameter의 정보를 참조하기 위해
   *   ActionForm의 객체를 초기화 한다 - reset()
   * 
   *   form parameter의 정보를 받아 유효성 검사를 실시한다 - validate()
   * 
   *   참조한 폼 정보를 form-bean에 설정된 bean으로 전달한다.
   * */
  
  InfoFormBean bean = (InfoFormBean)form;
  
  /*bean의 객체를 Entity(DTO)로 property를 복사한다.*/
  InfoDTO dto = new InfoDTO();
  BeanUtils.copyProperties(dto, bean);
  
  new InfoDAO().update(dto);
  

  return mapping.findForward("update");
 }
 
 public ActionForward delete(ActionMapping mapping,
         ActionForm form,
         HttpServletRequest request,
         HttpServletResponse response)
         throws Exception{

  InfoFormBean bean = (InfoFormBean)form;
  
  /*bean의 객체를 Entity(DTO)로 property를 복사한다.*/
  InfoDTO dto = new InfoDTO();
  BeanUtils.copyProperties(dto, bean);
  new InfoDAO().delete(dto);
  return mapping.findForward("delete");
 }
 protected String getWdate(){
  return new java.text.SimpleDateFormat("yyyy-MM-dd").format(new java.util.Date());
 }
 
}


자세한 내용은 파일을 참조한다.





'FrameWork > Struts1' 카테고리의 다른 글

Struts1 FileDownload  (0) 2009.08.18
Struts1 fileUpload  (0) 2009.08.18
Struts1의 Action 4  (0) 2009.08.16
Struts1의 Action 3  (0) 2009.08.16
Struts1의 Action 2  (0) 2009.08.12
Struts1에서 ActionForm 사용하기.  (0) 2009.07.25
Struts1 에서 iBatis 사용하기  (0) 2009.07.05
Struts 1 을 사용하여 간단한 회원가입, 리스트 불러오기.  (0) 2009.07.05
Struts1 개발환경 설정.  (0) 2009.07.05
Struts(스트럿츠) 란?  (0) 2009.06.27
http://thinkingblog.tistory.com/4
에서 update와 delete를 추가하면서 설명. Struts1.war 파일에 추가 됨.



1. InfoFormBean.java 에서 ActionForm을 상속 받는다.

package com.myhome.info.beans;

import org.apache.struts.action.ActionForm;

@SuppressWarnings("serial")
public class InfoFormBean extends ActionForm{

 private int num;
 private String name;
 private String sex;
 private String tel;

...... 생략 ......

2. struts-config.xml에서 form-bean을 설정한다.

<!-- Form Bean Definitions -->
<!-- form으로 들어오는 데이터를 bean객체에 담는다 -->

    <form-beans> 
        <form-bean
            name="bean"  
            type="com.myhome.info.beans.InfoFormBean"/>  <!-- name은 아무거나 하고 type는 담을 object 객체를 써준다.(전달된 파라미터 데이터가 설정된 빈 으로 저장이 된다) -->
       
        <!--
         DynaActionForm은 예측할 수 없는 파라미터를 참조할때 사용한다.
        -->
        <form-bean
         name="dyna"
         type = "org.apache.struts.action.DynaActionForm">
         <!--
          form bean에 존재하지 않는 파라미터를 참조하기 위해 property를 설정한다.
          -->
          <form-property name="num" type="java.lang.Integer"/>
          <form-property name="name" type="java.lang.String"/>
          <form-property name="sex" type="java.lang.String"/>
          <form-property name="tel" type="java.lang.String"/>
          <form-property name="wdate" type="java.lang.String"/>
        </form-bean>
         
    </form-beans>

3. struts-config.xml 에서 <action-mapping> 설정한다.

 <!--
         [action Attributes]
         path = "request 경로"
         name = "폼정보를 받아 줄 빈 클래스 이름" - form-bean에 정의 된 이름
         scope = "request|session|application" - 다음의 영역으로 들어오는 정보
         input = "/info/modify.jsp" - 입력받은 폼 페이지 명 명시
                                             - 정의된 곳에서 들어오는 데이터를 사용하겠다.
         
         forward 부분에서 path만 잡아 주면 주소창은 변하지 않고 페이지만 변경 시킨다.
         그래서 redirect를 true를 설정하면 주소 까지 바뀌어 버린다.
         -->


        <!-- ActionForm을 상속한 bean을 사용할 경우 -->
        <action path = "/update"
          name = "bean"
          scope = "request"
          input = "/info/modify.jsp"
          type = "com.myhome.info.actions.InfoUpdateAction">
         <forward name="success" path="/list.do" redirect="true"/>
        </action>
        
        <!-- DynaActionForm 을 사용할 경우 -->
        <action path="/delete"
          name = "dyna"
          scope = "request"
          input= "/info.modify.jsp"
          type = "com.myhome.info.actions.InfoDeleteAction">
         <forward name = "success"
            path = "list.do"
            redirect="true" />
        </action>
  
  <!--
   path - 다음과 같은 url패턴으로 들어왔을때
   type - 다음에 실행 될  액션을 설정한다.
   forward - 다음페이지로 이동되어질 곳을 정한다.
   -->


4. Action Class 에서 설정.

//ActionForm을 상속한 경우
public class InfoUpdateAction extends Action{

 @Override
 public ActionForward execute(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response)
   throws Exception {
  
  /*form parameter를 InfoFormBean으로 받는다*/
  
  /**
   *  ActionForm의 역할
   *   Form parameter의 정보를 참조하기 위해
   *   ActionForm의 객체를 초기화 한다 - reset()
   * 
   *   form parameter의 정보를 받아 유효성 검사를 실시한다 - validate()
   * 
   *   참조한 폼 정보를 form-bean에 설정된 bean으로 전달한다.
   *
   * */

  
  InfoFormBean bean = (InfoFormBean)form;
  
  /*bean의 객체를 Entity(DTO)로 property를 복사한다.*/
  InfoDTO dto = new InfoDTO();
  BeanUtils.copyProperties(dto, bean);
  
  new InfoDAO().update(dto);
  
  return mapping.findForward("success");
 }
 
}

//DynaActionForm을 사용한 경우
public class InfoDeleteAction extends Action {

 @Override
 public ActionForward execute(ActionMapping mapping,
         ActionForm form,
         HttpServletRequest request,
         HttpServletResponse response)
         throws Exception {
  
  DynaActionForm dyna = (DynaActionForm)form;
  InfoDTO dto = new InfoDTO();
  dto.setNum((Integer)dyna.get("num"));
  new InfoDAO().delete(dto);
  return mapping.findForward("success");
 }
 
}

5. InfoDAO.java, SqlMap.xml에 update, delete 추가.

6. jsp 페이지 수정.


자세한 내용은 war 파일을 참조 한다.

'FrameWork > Struts1' 카테고리의 다른 글

Struts1 FileDownload  (0) 2009.08.18
Struts1 fileUpload  (0) 2009.08.18
Struts1의 Action 4  (0) 2009.08.16
Struts1의 Action 3  (0) 2009.08.16
Struts1의 Action 2  (0) 2009.08.12
Struts1의 Action 1  (0) 2009.07.27
Struts1 에서 iBatis 사용하기  (0) 2009.07.05
Struts 1 을 사용하여 간단한 회원가입, 리스트 불러오기.  (0) 2009.07.05
Struts1 개발환경 설정.  (0) 2009.07.05
Struts(스트럿츠) 란?  (0) 2009.06.27


http://thinkingblog.tistory.com/2

위 글에서 작성한 설정을 다 하고 마지막으로 아래 설정을 하면 struts1을 개발 할 수 있는 환경 설정 완료.

■ struts-config.xml 설정

 
 스트럿츠 사이트에서 struts-1.3.10-all 파일을 다운로드 받는다.

http://struts.apache.org/download.cgi#struts1310

 struts-config.xml은 sturts에서 제공하는 xml을 사용한다.
struts-blank-1.3.10 파일안에 존재하는 struts-config.xml 파일을 이클립스에서 생성한 프로젝트의 WEB-INF에 복사해 넣는다.

struts-1.3.10-all\struts-1.3.10\apps 안에 있는 struts-blank-1.3.10 압축 파일을 풀고 WEB-INF에 있는 struts-config.xml 파일을 복사해 사용한다.

Struts1 환결 설정 끝.

'FrameWork > Struts1' 카테고리의 다른 글

Struts1 FileDownload  (0) 2009.08.18
Struts1 fileUpload  (0) 2009.08.18
Struts1의 Action 4  (0) 2009.08.16
Struts1의 Action 3  (0) 2009.08.16
Struts1의 Action 2  (0) 2009.08.12
Struts1의 Action 1  (0) 2009.07.27
Struts1에서 ActionForm 사용하기.  (0) 2009.07.25
Struts1 에서 iBatis 사용하기  (0) 2009.07.05
Struts 1 을 사용하여 간단한 회원가입, 리스트 불러오기.  (0) 2009.07.05
Struts(스트럿츠) 란?  (0) 2009.06.27

+ Recent posts