RadarURL

응용 프로그래밍
2014.05.09 19:08

Conversion Struts to Spring MVC

조회 수 1285 추천 수 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 931219
2503 유닉스/리눅스 리눅스 서버 설치 중 에러 "Failed to find a suitable stage1 device" JaeSoo 2025.10.03 36
2502 유닉스/리눅스 Linux 11 . Linux 설치 시 lvm 수동설정 JaeSoo 2025.10.03 28
2501 유닉스/리눅스 [Rocky Linux] 누구나 쉽게 따라하는 Rocky Linux 9.0 OS 다운로드 및 설치 방법~!! JaeSoo 2025.10.03 40
2500 유닉스/리눅스 Linux/Rocky Linux Rocky Linux : Composer 설치 JaeSoo 2025.09.29 43
2499 유닉스/리눅스 [Rocky Linux] 록키 리눅스 최신 업데이트 적용 방법 JaeSoo 2025.09.29 44
2498 유닉스/리눅스 rocky linux 커널 업데이트 JaeSoo 2025.09.29 36
2497 웹서버,WAS [Windows] OWASP ZAP 사용법 JaeSoo 2025.09.29 50
2496 웹서버,WAS [웹 취약점] 웹서버 디렉토리 리스팅 방지 JaeSoo 2025.09.29 52
2495 유닉스/리눅스 Clonezilla(클론질라) 백업파일 하드디스크로 복구 방법 JaeSoo 2025.09.28 44
2494 유닉스/리눅스 클론질라 사용 방법 - OS 이미지 백업 CloneZilla JaeSoo 2025.09.28 57
2493 유닉스/리눅스 [Linux / Rocky] FTP 접속 관련 설정 실습 예제 JaeSoo 2025.09.23 72
2492 유닉스/리눅스 Could not reliably determine the server's fully qualified domain name JaeSoo 2025.09.23 70
2491 유닉스/리눅스 [아파치] 아파치 웹서버에 .htaccess 파일 설정하는 방법 JaeSoo 2025.09.23 65
2490 유닉스/리눅스 [Linux] Apache web server의 rewrite module 사용하기 [출처] [Linux] Apache web server의 rewrite module 사용하기|작성자 g00dmoney JaeSoo 2025.09.23 61
2489 유닉스/리눅스 록키 리눅스 9.1에서 apache, mysql, PHP 설치 JaeSoo 2025.09.23 68
2488 유닉스/리눅스 [권한문제] 라이믹스 Fatal error: Uncaught Rhymix\Framework\Exception: Cannot write template cache file JaeSoo 2025.09.23 56
2487 유닉스/리눅스 라이믹스 php 에러 표시 JaeSoo 2025.09.23 53
2486 유닉스/리눅스 Rocky Linux - 라이믹스(Rhymix) 설치하기 JaeSoo 2025.09.23 49
2485 유닉스/리눅스 라이믹스(Rhymix) 매뉴얼 JaeSoo 2025.09.23 45
2484 유닉스/리눅스 [ Apache ] 아파치 start/stop/restart 명령어 JaeSoo 2025.09.23 37
Board Pagination Prev 1 2 3 4 5 6 7 8 9 10 ... 126 Next
/ 126


즐겨찾기 (가족)

JAESOO's HOMEPAGE


YOUNGAE's HOMEPAGE


장여은 홈페이지


장여희 홈페이지


장여원 홈페이지


즐겨찾기 (업무)

알리카페 홀릭

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

말레이시아 KL Sentral 한국인 GuestHouse


즐겨찾기 (취미)

어드민아이디

유에코 사랑회

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

JServer.kr

제이서버 메타블로그

재수 티스토리


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

재수 강의 홈페이지


한소리


VTMODE.COM


숭실대 인공지능학과


숭실대 통신연구실


베너