RadarURL

응용 프로그래밍
2014.05.09 19:08

Conversion Struts to Spring MVC

조회 수 4581 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

가 크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

가 크게 작게 위로 아래로 댓글로 가기 인쇄

기존 Struts로 개발되어있는 웹프레임워크를 Spring MVC기반으로 전환하기 위한 방법을 소개한다.

web.xml 변경

  • Spring 속성정의 파일 위치 지정
  • 웹단에서 호출하는 서비스들이 Spring bean으로 정의되어 있는 속성 정의 파일의 위치를 다음과 같이 지정해 준다.
    <context-param>
    	<param-name>contextConfigLocation</param-name>
    	<param-value>
    		/config/spring/applicationContext-*.xml
    	</param-value>
    </context-param>
  • Listener 등록
  • Spring에서 제공해주는 Listener를 등록한다.
    <listener>
    	<listener-class>
    		org.springframework.web.context.ContextLoaderListener
    	</listener-class>
    </listener>
  • servlet class 변경 및 contextConfigLocation 정의
  • servlet class를 다음과 같이 변경하고 param-name을 config 대신 contextConfigLocation으로 정의한 후 config파일 위치를 지정해 준다.
    • 변경 전
    • <servlet>
      	<servlet-name>action</servlet-name>
      	<servlet-class>
      		anyframe.web.struts.common.action.DefaultActionServlet
      	</servlet-class>
      	<init-param>
      		<param-name>config</param-name>
      		<param-value>
      			/config/struts/struts-config.xml
      		</param-value>
      	</init-param>
      	<load-on-startup>1</load-on-startup>
      </servlet>
    • 변경 후
    • <servlet>
      	<servlet-name>action</servlet-name>
      	<servlet-class>
      		org.springframework.web.servlet.DispatcherServlet
      	</servlet-class>
      	<init-param>
      		<param-name>contextConfigLocation</param-name>
      		<param-value>
      			/config/springmvc/*-servlet.xml
      		</param-value>
      	</init-param>
      	<load-on-startup>1</load-on-startup>
      </servlet>
  • 인코딩 필터 추가
  • 폼입력 데이터 값이 한글일 경우 한글 깨짐 현상을 방지하기 위해 다음과 같이 인코딩 필터를 추가 한다.
    <filter>
    	<filter-name>encodingFilter</filter-name>
    	<filter-class>
    		org.springframework.web.filter.CharacterEncodingFilter
    	</filter-class>
    	<init-param>
    		<param-name>encoding</param-name>
    		<param-value>euc-kr</param-value>
    	</init-param>
    </filter>
    ※ 참고로 Tomcat 5.0이상에서는 JSP 폼의 method가 post방식일 경우 한글 인코딩을 지원하지 않는다. 이경우 Tomcat의 server.xml파일에 다음과 같이 uri인코딩을 현재 작업 인코딩에 맞게 지정해줘야 한다.
    <Connector port="8080" maxHttpHeaderSize="8192"
    	maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
    	enableLookups="false" redirectPort="8443" acceptCount="100"
    	connectionTimeout="20000" disableUploadTimeout="true" URIEncoding="euc-kr"/>
  • message properties의 한글 인코딩을 위한 character-encoding 추가
  • Spring에서 제공해주는 <spring:message> 태그를 사용할 경우 유니코드가 아닌 다른 인코딩 방법(ex>UTF-8, euc-kr)으로 인코딩된 한글 메시지가 깨지는 현상이 발생된다.
    <context-param>
    	<param-name>character-encoding</param-name>
    	<param-value>utf-8</param-value>
    </context-param>
    이 경우 다음과 같은 characer-encoding부분을 web.xml에 추가해주고 anyframe에서 확장해서 제공하는 <anyframe:message>태그를 사용한다.
    단, resource bundle editor등을 이용한 유니코드로 직접 작성된 경우는 기존의 <spring:message>태그를 사용한다.

Controller 단 변경

Anyframe Java의 Struts 웹 프레임워크의 Action은 결과적으로 Struts에서 제공하는 Action을 상속받게 되어 있는데, 이를 Spring MVC로 전환하기 위해서는 Spring Fraemwork에서 제공해주는 Controller를 상속받도록 구현해야한다. Struts 웹 프레임워크를 사용할 때 대표적으로 Anyframe Java에서 제공하는 DefaultActionSupport와 DefaultDispatchActionSupport를 상속받게 되는데 이는 모두 Anyframe Web에서 제공하는 AnyframeFormController로 대체될 수 있으며 그 예는 아래와 같다.
  • DefaultActionSupport
  • 한 Action에서 하나의 요청만 처리하면 DefaultActionSupport, 여러 요청을 처리하면 DefaultDispatchAction을 상속받아 구현하도록 되어있다. 이중 DefaultActionSupport를 Anyframe Spring MVC로 Conversion하기 위해서는 Anyframe Web의 AnyframeFormControlle를 상속 받고 process() 메소드를 구현하며 데이터 바인딩은 bind()메소드를 통해 할 수 있다. 또한 ApplicationContext의 getBean을 사용하여 Service를 호출하는 것이 아니라 Setter Injection을 통해 Service를 호출한다.
    • 변경 전
    • public class GetUserAction extends DefaultActionSupport {
      	public Log getLogger() throws Exception {
      		return DefaultActionUtils.getLogger(this.getClass().getName());
      	}
      	public ActionForward process(ActionMapping mapping, ActionForm form,
      			HttpServletRequest request, HttpServletResponse response)
      			throws Exception {
      		ApplicationContext ctx = getWebApplicationContext();
      		UserService userService = (UserService) ctx.getBean("userService");
      		
      		....중략...
      		UserForm userForm = (UserForm) form;
      		
      		....중략...
      		request.setAttribute("userVO", userVO);
      		request.setAttribute("flag", "user");
      
      		return mapping.findForward("success");
      	}
      }
    • 변경 후
    • public class GetUserController extends AnyframeFormController {
      
      	//Setter Injection을 통해 서비스를 호출한다.
      	private UserService userService = null;
      	public void setUserService(UserService userService) {
      		this.userService = userService;
      	}
      
      	//process 메소드 구현
      	protected ModelAndView process(HttpServletRequest request,
      			HttpServletResponse response{
      
      		....중략... 
      		UserVO uesrVO = new UserVO();
      		//bind() 메소드를 이용한 request에 parameter로 넘어온 폼 입력 데이터 바인딩 
      		bind(request, userVO);
      		
      		....중략... 
      		request.setAttribute("userVO", userVO);
      		request.setAttribute("flag", "user");
      
      		// return할 페이지 지정
      		return new ModelAndView("/sample/user/updateUser.jsp");
      	}
      }
  • DefaultDispatchActionSupport
  • DefaultDispatchActionSupport 또한 AnyframeFormContoller로 변경한 후 각 요청별 처리에 맞는 메소드를 구현해야한다. 마찬가지로 bind() 메소드를 사용하여 데이터를 바인딩한다. DefaultActionSupport의 전환과정과 마찬가지로 ApplicationContext의 getBean을 사용하여 Service를 호출하는 것이 아니라 Setter Injection을 통해 Service를 호출한다.
    • 변경 전
    • public class AdminCompanyMgmtAction extends DefaultDispatchActionSupport {
      	public ActionForward getCompanyList(ActionMapping mapping,
      			ActionForm form, HttpServletRequest request,
      			HttpServletResponse response) throws Exception{	
      		ApplicationContext ctx= getWebApplicationContext();
      		AdminCompanyMgmt compMgmt 		= (AdminCompanyMgmt) ctx.getBean(AdminCompanyMgmt.ROLE);		
      		AdminCompanyForm companyForm 	= (AdminCompanyForm) form;
      		PageInfo compListInfo 			= null;
      		HashMap searchArgs 				= new HashMap();
      		this.getLogger().debug("test Logger");
      		
      		...중략...
      		request.setAttribute("LinesPerPage", new Integer(pageSize));
      		request.setAttribute("searchPage", new Integer(searchPage));
      		
      		String forward = request.getParameter("type");
      		if (forward == null || "".equals(forward))
      		    forward = "success";
      		return mapping.findForward(forward);
      	}
      
      	public ActionForward getCompany(ActionMapping mapping, ActionForm form,
      			HttpServletRequest request, HttpServletResponse response)
      			throws Exception {
      		ApplicationContext ctx = getWebApplicationContext();
      		AdminCompanyForm companyForm 	= (AdminCompanyForm) form;
      		AdminCompanyMgmt companyMgmt 	= (AdminCompanyMgmt) ctx.getBean(AdminCompanyMgmt.ROLE);
      		AdminCompanyVO companyVO 		= companyMgmt.getCompanyDetail(companyForm.getCom_sq());
      		String forward = request.getParameter("type");
      		
      		if ( forward == null ){
      			forward = "readView";
      		}else{
      			forward = "UpdateView";
      		}
      
      		request.setAttribute("companyDetail", companyVO);
      		return mapping.findForward(forward);
      	}
      }
    • 변경 후
    • public class AdminCompanyMgmtController extends AnyframeFormController {
      	private AdminCompanyMgmt compMgmt = null;
      
      	public void setAdminCompanyMgmt(AdminCompanyMgmt compMgmt) {
      		this.compMgmt = compMgmt;
      	}
      
      	//view객체이름을 프로퍼티로 xml파일에 지정해 주었을 경우 Setter Injection을 통해 호출한다.
      	private String successView = null;
      	
      	public void setSuccessView(String view){
      		this.successView=view;
      	}
      	public ModelAndView getCompanyList(HttpServletRequest request,
      			HttpServletResponse response) throws Exception {
      		AdminCompanyForm companyForm = new AdminCompanyForm();
      		this.getLogger.debug("before bind=========="+request.getParameter("searchCompany"));
      		
      		//bind메소드를 통한 데이터 바인딩
      		bind(request, companyForm);
      		String a = companyForm.getSearchCompany();
      		this.getLogger.debug("searchCompany============"+a);
      		this.getLogger.debug("encoding=========="+request.getCharacterEncoding());
      		
      		...중략.. 
      		request.setAttribute("LinesPerPage", new Integer(pageSize));
      		request.setAttribute("searchPage", new Integer(searchPage));
      
      		String forward = request.getParameter("type");
      		if (forward == null || "".equals(forward))
      			forward = "success";
      		request.setAttribute("companyForm", companyForm);
      		return new ModelAndView(successView);
      
      	}
      
      	public ModelAndView getCompany(HttpServletRequest request,
      			HttpServletResponse response) throws Exception {
      
      		AdminCompanyVO companyVO = new AdminCompanyVO();
      		bind(request, companyVO);
      
      		companyVO = compMgmt.getCompanyDetail(companyVO.getCom_sq());
      		String forward = request.getParameter("type");
      		request.setAttribute("companyDetail", companyVO);
      		if (forward == null) {
      
      			return new ModelAndView("/admin/AU0202_R1.jsp");
      
      		} else {
      			return new ModelAndView("/admin/AU0202_UD1.jsp");
      		}
      
      	}
      }
    AnframeFormController에 대한 자세한 설명은 여기를 참고한다.

configuration 파일 변경

기존 struts-config로 정의되어있던 request요청에 따른 매핑정보를 spring에서 지원하는 형태의 xml로 모두 변경해야 한다. 작성 방법은 여기를 참고한다.

JSP파일 내의 태그 변경

기존 Struts의 태그를 쓴 경우 JSTL및 Spring에서 제공하는태그로 변경해 줘야 한다. 여기서는 간단히 Struts 태그와 같은 역할을 하는 태그를 간단히 소개한다.
  • tag library 추가
  • <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
    <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
    <%@ taglib prefix="anyframe" uri="http://www.sds.samsung.com/tags"%>
  • 태그 변경
    • 변경 전
      <html:rewrite page="/companyList.do"/>
      변경 후
      <c:url value='/companyList.do'/>
    • 변경 전
      <bean:message bundle="admin" key="admin.action.nothingselected"/>
      변경 후
      <spring:message code="admin.action.nothingselected"/>
    • 변경 전
      <bean:define id="deCom_desc" >
      변경 후
      <c:set var="deCom_desc" >
    • 변경 전
      <bean:write name="companyDetail" property="fax_no" ignore="true"/>
      변경 후
      <c:out value="${companyDetail.com_nm}"/>
    • 변경 전
      <logic:present name="compList">
      변경 후
      <c:if test="${compList != null}">
    • 변경 전
      <logic:iterate name="compList" id="company">
      변경 후
      <c:forEach var="company" begin="0" items="${compList}">
    • 변경 전
      <bean:write name='company' property='com_sq' format="#" ignore="true"/>
      변경 후
      <fmt:formatNumber value='${company.com_sq}' pattern='#'/>
    • 변경 전
      <logic:notEmpty name="company" property="com_desc">
      변경 후
      <c:if test="${not empty company.com_desc}">
    ※ Spring mvc 에서는 Form 객체를 사용하지 않고 직접 입력값의 데이터를 도메인 객체에 매핑시켜준다. 이 때 입력값의 타입에 따라 자동으로 도매인 객체 타입과 맞춰 바인딩을 해주는데int로 정의되어있는 도메인 객체의 입력값이 null일경우 빈 String으로 인식하여 타입 미스매치 에러가 나게 된다. 그러므로 이러한 int형의 데이터는 반드시 초기값을 가지고 있어야 한다.만약 초기값이 도매인객체에 정의되어 있으면, input데이터의 value값으로 ${companyForm.pageIndex}와 같이 지정해줘야한다.

 

출처 : http://dev.anyframejava.org/anyframe/doc/web/3.0.1/webfw/springmvc/tip/conversion.html

?

공부 게시판

공부에 도움되는 글을 올려주세요.

List of Articles
번호 분류 제목 글쓴이 날짜 조회 수
공지 [공지] 공부 게시판 입니다. 처누 2003.08.18 2004052
2615 공지 대전, 인천, 세종 하수구 막힘 문제 해결 방법 new 정열적인코요테90 2026.10.05 1
2614 취미 <문경맥주> 구입 할 수 있는 곳은 새 창 열림 new 타오르는드래곤61 2026.10.05 1
2613 데이터베이스 강남건전지❤️OlO-8655-OO53❤️친절문의환영 #강남건전지 #강남유니콘 #선릉유니콘 #강남건전지위치 #선릉역건전지#대치동유니콘 #강남바커스 #선릉바커스 #선릉역바커스 #강남룸클럽 #선릉룸클럽 #강남베터리 #강남바데리 new 괴랄한재규어89 2026.10.05 1
2612 사무 소프트웨어 용인두피문신 고민? 만족 후기 보려면 new 날카로운꿩11 2026.10.05 1
2611 논문 카­톡 gusim8003 급전/내구제 (24시문의) 폰테크 소액대출 선불폰 가개통 new 타오르는켄타우로스86 2026.10.05 1
2610 윈도우즈 웨딩누브라, 완벽한 드레스 핏을 위한 선택 new 날카로운감시자22 2026.10.05 1
2609 인터넷 성공적인 중고화물차 선택, 현명한 가이드 new 붉은드래곤50 2026.10.05 2
2608 가상화 인천맛집 순위 new 차가운파편97 2026.10.05 2
2607 응용 프로그래밍 완벽한 웨딩드레스 핏의 비밀, 웨딩누브라 new 힘겨운암석76 2026.10.05 1
2606 카메라 파주누수업체, 신속 해결 전문가의 비결 new 차가운에메랄드79 2026.10.05 1
2605 u-E(통합센터) 올해의 핫플 선정 간석동 마블! 010&&8923&&0291 new 교활한감시자99 2026.10.05 1
2604 웹서버,WAS 손목터널증후군 치료, 현명한 선택 기준은? new 괴상한두루미52 2026.10.05 1
2603 u-E(통합센터) 손목터널증후군, 두팔로정형외과에서 해답을 찾다 new 눈부신백마법사86 2026.10.05 1
2602 응용 프로그래밍 골든타워 010 2817 0845 골타문의 편하게 알아보는 셔츠룸 new 속삭이는미노타우르93 2026.10.05 2
2601 u-E(TestBed) 특별한 기념품제작, 판촉물365 new 광기의태풍18 2026.10.05 1
2600 건강 대전누수 문제, 청년연합누수가 답이다 new 몽환적인삵34 2026.10.05 2
2599 u-E(법,정책) 양산싱크대막힘, 뚫자하수구에서 한 번에 해결 new 낙관적인유니콘42 2026.10.05 1
2598 가상화 최근 테헤란로 벤처 밸리의 핵심 리더들 사이에서 ‘클래스가 다른 정통 수질과 프라이빗 무드’로 소문 자자한 '선릉 룸싸롱' 기습 방문, 인공미를 거부하는 무결점 뉴페이스들과 심장을 마비시킨 사심 플러팅에 제대로 저격당하고 온 솔직 후기 new 희미한홍학99 2026.10.05 3
2597 웹서버,WAS 카­톡 gusim8003 급전/내구제 (24시문의) 선불폰 소액결제 일수 급전대출 new 황금빛섬광82 2026.10.05 2
2596 웹광고 해외선물 메타5 거래소와 GFS컴퍼니의 장점과 고려사항 new 울리는이구아나69 2026.10.05 2
Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 ... 131 Next
/ 131


즐겨찾기 (가족)

JAESOO's HOMEPAGE


장여은 홈페이지


장여희 홈페이지


장여원 홈페이지


즐겨찾기 (업무)

알리카페 홀릭

숭실대 컴퓨터 통신연구실 (서창진)

말레이시아 KL Sentral 한국인 GuestHouse


즐겨찾기 (취미)

어드민아이디

유에코 사랑회

아스가르드 좋은사람/나쁜사람

JServer.kr

제이서버 메타블로그

재수 티스토리


즐겨찾기 (강의, 커뮤니티)

재수 강의 홈페이지


한소리


VTMODE.COM


숭실대 인공지능학과


숭실대 통신연구실


베너