-
스트럿츠2.5 기본 환경설정 및 MVC구현DEV/Struts 2021. 1. 21. 15:20
1. Dynamic Web Project 생성
프로젝트명 : Struts2
2. Struts2 다운로드
- http://struts.apache.org
- Download
- Full Distribution or Essential Dependencies Only zip파일 다운 및 압축해제
저는 간단하게 JSP호출 테스트만 해볼거라서 Essential Dependencies를 다운받았습니다.
3. 라이브러리 추가
압축해제 후 lib폴더에 있는 jar파일들
WebContent-WEB-INF-lib에 복붙
4. web.xml 작성
WEB-INF안에 web.xml이 없다면
프로젝트 우클릭 > Java EE tools > Generate Deployment Descriptor Stub
1234567891011121314<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"><display-name>Struts2</display-name><filter><filter-name>struts2</filter-name><filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class></filter><filter-mapping><filter-name>struts2</filter-name><url-pattern>/*</url-pattern></filter-mapping></web-app>cs 이렇게 바꿔주기!
<url-pattern>에서 url의 주소가 *.action일 경우 struts2의 이름을 가진 필터를 실행되도록 맵핑
- /* : 모든 요청 처리
- Struts2의 기본 확장자 : *.action
처음에 다른 블로그를 참고해서 작성하다가 오류가 났는데
Struts core 버전마다 filter class가 다르다.
"java.lang.ClassNotFoundException: org.apache.struts2.dispatcher.FilterDispatcher" 에러가 날경우
java.lang.ClassNotFoundException: org.apache.struts2.dispatcher.FilterDispatcher
log when start the tomcat Apr 28, 2011 10:52:57 AM org.apache.catalina.core.AprLifecycleListener init INFO: The APR based Apache Tomcat Native library which allows optimal performance in production
stackoverflow.com
버전에 따라 참고해서 작성하기
5. struts.xml 생성
- MVC 패턴의 Controller 역할
- src 아래 생성
1234567891011121314<?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><constant name="struts.action.extension" value="action,do"/><constant name="struts.i18n.encoding" value="UTF-8"/><package name="struts2" extends="struts-default"><action name="hello" class="struts2.action.Action"><result>/test/hello.jsp</result></action></package></struts>cs <constant name="struts.action.extension" value="action,do"/>
: 확장자 설정 *.action, *.do 둘 다 사용
<constant name="struts.i18n.encoding" value="UTF-8"/>
: 인코딩 설정
<package name="struts2" extends="struts-default">
: struts-default의 내용을 상속 받아 struts2의 이름으로 패키지 생성
<action name="hello" class="struts2.action.Action">
<result>/test/hello.jsp</result>
</action>
: hello.action 요청이 들어오면 struts2.action.Action 클래스에서 기본값인 execute 메서드를 호출.
execute메서드의 리턴값이 success일때 결과를 /test/hello.jsp에 뿌려준다.
- action 속성 중 method가 없으면 execute가 기본 값
- result 속성 중 name이 없으면 success가 기본 값
6. model 생성
1234567891011121314package struts2.model;public class MessageVO {private String msg;public MessageVO() {msg = "Hello Struts User";}public String getMsg() {return msg;}}cs 7. action 생성
12345678910111213141516171819202122package struts2.action;import com.opensymphony.xwork2.ActionSupport;import struts2.model.MessageVO;public class Action extends ActionSupport {private MessageVO messageVO;public String execute(){messageVO = new MessageVO();return "success";}public MessageVO getMessageVO(){return messageVO;}}cs 8. view 생성
WebContent 아래 test 폴더 생성 후 hello.jsp 생성
12345678910111213<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><%@ taglib prefix="s" uri="/struts-tags"%><!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>Hello.jsp</title></head><body><h2><s:property value="messageVO.msg"/></h2></body></html>cs taglib를 추가해 스트럿츠태그 사용
9. 서버 실행
localhost:8080/Struts2/hello.action
저는 path값을 /로 바꿔서 프로젝트명 생략
만약에
ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath.
이러한 에러가 난다면
프로젝트 우클릭 > Configure > Convert to Maven Project
pom.xml 생성
1234567891011121314151617181920212223<dependencies><dependency><groupId>org.apache.struts</groupId><artifactId>struts2-core</artifactId><version>2.5.26</version><exclusions><exclusion><artifactId>org.apache.commons</artifactId><groupId>commons-lang3</groupId></exclusion><exclusion><artifactId>log4j-api</artifactId><groupId>org.apache.logging.log4j</groupId></exclusion></exclusions></dependency><dependency> <!-- Redirecting from log4j2 to slf4j --><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-to-slf4j</artifactId><version>2.10.0</version></dependency></dependencies>cs dependency추가
스트럿츠 낮은 버전에서는 안나는 오류 같은데 이유를 모르겠으나
구글링을 통해 log4j2를 slf4j로 리다이렉팅하여 해결했다.ㅜ 아래 주소 참고
stackoverflow.com/questions/49948768/migrating-to-struts-2-5-16-causing-log4-issue/51531933
Migrating to Struts 2.5.16 causing log4 issue
I'm migrating existing Struts Application 2.3.34 to 2.5.16. I've updated my Project with all the libs from min distribution needed for the upgrade. At Server (Tomcat 8.5) startup I see ERROR in the
stackoverflow.com
코드동작원리
1. 브라우저에서 localhost:8080/Struts2/hello.action 으로 요청을 보냄.
2. 컨테이너가 요청을 받으면 web.xml에 정의되어있는 필터를 보고org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter 로 라우트 시킨다.
3. StrutsPrepareAndExecuteFilter 는 프레임워크의 시작점!!
4. 이제 프레임워크는 "hello"라는 이름을 갖는 <action>태그 찾아 Action클래스와 연결되어 있음(struts.xml파일에 설정되어있음)을 알아내고 해당 객체의 excute메소드를 실행한다.
5. execute메소드가 success를 return 하면 (기본값:<result name="success">)
/test/hello.jsp로 이동하여 웹 브라우저에 출력
'DEV > Struts' 카테고리의 다른 글
스트럿츠2 프레임워크란 ? (0) 2021.01.21