52
Struts Tutorial 111111 구구구

Struts Tutorial

  • Upload
    phuong

  • View
    57

  • Download
    1

Embed Size (px)

DESCRIPTION

111111 구성모. Struts Tutorial. Presenter. ㅎㅇㅎㅇ. http://sparcs.org/~breadfish/Struts_tutorial.ppt. Web Application Server. HTML. JS. 웹 서버 (Apache, IIS, …). JPG. Web Application Server. HTML. JS. 웹 서버 (Apache, IIS, …). CGI. DB. Web Application Server. HTML. 웹 어플리케이션 서버 (WAS). JS. - PowerPoint PPT Presentation

Citation preview

Page 1: Struts Tutorial

Struts Tutorial

111111 구성모

Page 2: Struts Tutorial

Presenter

http://sparcs.org/~breadfish/Struts_tutorial.ppt

ㅎㅇㅎㅇ

Page 3: Struts Tutorial

Web Application Server

웹 서버(Apache, IIS, …)

웹 서버(Apache, IIS, …)

HTML

JS

JPG

.

.

.

Page 4: Struts Tutorial

Web Application Server

웹 서버(Apache, IIS, …)

웹 서버(Apache, IIS, …)

HTML

JS

CGI

.

.

.

DB

Page 5: Struts Tutorial

Web Application Server

웹 어플리케이션서버 (WAS)

웹 어플리케이션서버 (WAS)

HTML

JS

Class

.

.

.

웹 서버웹 서버

컨테이너컨테이너 DB

Page 6: Struts Tutorial

Web Application Server

웹서버 기능Servlet/JSP 컨테이너 기능EJB 컨테이너 기능트랜잭션 서버보안 서버네이밍 서버 JDBC 지원

톰캣 , RESIN, 웹로직 , 웹투비

Page 7: Struts Tutorial

Why JSP?

실무

.php .jsp .asp .do .action

Page 8: Struts Tutorial

개발환경구축

톰캣을 설치할 디렉토리 만들기 mkdir struts_tutorial

톰캣 7 다운로드 http://mirror.apache-kr.org/tomcat/tomcat-7/

v7.0.22/bin/apache-tomcat-7.0.22.tar.gztar -xvf

Page 9: Struts Tutorial

개발환경구축

cd apache-tomcat-7.0.22/bin ./catalina.sh start ./catalina.sh stop

vi ../conf/server.xml <Server port=“8005”

• 8005 -> 8041

<Connector port=“8080”• 8080 -> 8042

<Connector port=“8009”• 8009 -> 8043

Page 10: Struts Tutorial

개발환경구축

netstat –antpkill xxxx

http://bit.sparcs.org:8042

Page 11: Struts Tutorial

JSP

cd ../webapps/ROOTmv index.jsp _index.jspvi index.jsp

index.jsp index.jsp

<html>

<head>

</head>

<body>

<% out.println(new java.util.Date()); %>

</body>

<html>

<html>

<head>

</head>

<body>

Hello, World!

</body>

<html>

Page 12: Struts Tutorial

JSP

Java Server Page스크립트언어

Page 13: Struts Tutorial

Context

Page 14: Struts Tutorial

Servlet

cd WEB-INFmkdir classescd classesvi hello.java

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.annotation.WebServlet;

@WebServlet(urlPatterns={"/hello"})

public class hello extends HttpServlet{

public void doGet(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException{

res.setContentType("text/html");

PrintWriter out = res.getWriter();

out.println("<html>");

out.println("<head>");

out.println("</head>");

out.println("<body>");

out.println("Hello, World!");

out.println("</body>");

out.println("</html>");

out.close();

}

}

Page 15: Struts Tutorial

Servlet

javac –d . hello.java vi ~/.bash_profile

CLASSPATH=$CLASSPATH:.:/home/breadfish/struts_tutorial/apache-tomcat-7.0.22/lib/*

export CLASSPATH source ~/.bash_profile

vi ../web.xml metadata-complete=“true”

• true -> false restart http://bit.sparcs.org:8042/hello

Page 16: Struts Tutorial

Web Application Server

웹 어플리케이션서버 (WAS)

웹 어플리케이션서버 (WAS)

HTML

JS

Class

.

.

.

웹 서버웹 서버

컨테이너컨테이너 DB

Page 17: Struts Tutorial

Web Application Server

웹 서버웹 서버 서블릿

객체

서블릿컨테이너서블릿

컨테이너스레드스레드

WAS

JVM

Page 18: Struts Tutorial

JSP to Servlet

vi ~/struts_tutorial/apache-tomcat-7.0.22/work/Catalina/localhost/_/org/apache/jsp/index_jsp.java

Page 19: Struts Tutorial

Struts Tutorial 2

111115 구성모

Page 20: Struts Tutorial

What we are done

WASContainerTomcat JSPServletContext

Page 21: Struts Tutorial

Context

Page 22: Struts Tutorial

Tomcat

bin lib conf logs

catalina… host-manager… localhost…

temp work webapps

ROOT examples

Page 23: Struts Tutorial

Create new context

cd struts_tutorialmkdir proj1cd proj1mkdir WEB-INFmkdir WEB-INF/classesmkdir WEB-INF/lib

Page 24: Struts Tutorial

Create new context

vi tomcat_dir/conf/server.xml Just before </Host>

<Context path=“proj1”reloadable=“true”docBase=“/home/breadfish/struts_tutorial/proj1”workDir=“/home/breadfish/struts_tutorial/proj1/

work”></Context>

vi hello.jsp Hello

tomcat restart http://bit.sparcs.org:8042/proj1/hello.jsp

Page 25: Struts Tutorial

Struts2

Web FrameworkMVC architecturePOJO

action form

Zero configuration InterceptorTagAjaxPlug-in

Page 26: Struts Tutorial

Struts2 install

cd ~/struts_tutorialhttp://apache.mirror.cdnetworks.com//

struts/binaries/struts-2.2.3.1-all.zipunzipcd struts-2.2.3/libcopy all jars to [docBase]/WEB-INF/lib

Page 27: Struts Tutorial

Struts2 Install

commons-fileupload-1.2.2.jar commons-logging-api-1.1.jar struts2-convention-plugin-2.2.3.jar commons-lang-2.4.jar ognl-3.0.1.jar struts2-dojo-plugin-2.2.3.jar commons-logging-1.1.1.jar struts2-config-browser-plugin-2.2.3.jar asm freemaker xwork struts2-core

Page 28: Struts Tutorial

Struts2 intall

cd [docBase]/WEB-INF/classesvi StrutsFilter.java

javac –d . StrutsFilter.java

import javax.servlet.Filter;

import javax.servlet.annotation.*;

import org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter;

 

@WebFilter(displayName="Struts2", urlPatterns="/*", filterName="struts2",

        initParams={@WebInitParam(name="actionPackages", value="")})

public class StrutsFilter extends StrutsPrepareAndExecuteFilter implements Filter{

    private static final long serialVersionUID = 1L;

} /[ContextPath]/ 하위로 들어오는 모든 url 은 필터디스패처로 들어간다

Page 29: Struts Tutorial

필터 디스패처

스트러츠 2 의 컨트롤러액션을 실행하기 위한 환경을 구축사용자에게 보낼 응답을 처리

Page 30: Struts Tutorial

Struts2 Hello, World

vi HelloWorldAction.java

javac –d . HelloWorldAction.javatomcat restart http://bit.sparcs.org:8042/proj1/hello.action

package com.proj1.action

import org.apache.struts2.convention.annotation.*;

public class HelloWorldAction{

     @Action(value="/hello", results={

         @Result(name="success", location="/HelloWorld.jsp")})

     public String execute(){

         return "success";

     }

 }

vi ../../HelloWorld.jsp Hello, World!

Page 31: Struts Tutorial

Struts2 Annotation

패키지 경로에 action 이 들어갈것 . struts 나 struts2 도 된다 .

Action annotation 을 액션 메소드에 붙여주자 .

Action annotation 을 사용하지 않고 class 에 Result annotation 을 붙여서 액션을 매핑할 수도 있다 .

클래스명은 Action 으로 끝나야한다 .

Page 32: Struts Tutorial

Struts Tutorial 3

111122 구성모

Page 33: Struts Tutorial

Struts2 config browser

http://bit.sparcs.org:8042/proj1/config-browser/index

현재 매핑되어진 모든 액션과 URL 을 확인

Page 34: Struts Tutorial

Print variable

cd [docBase]/WEB-INF/classesvi HelloWorldAction.java

package com.proj1.action;

import org.apache.struts2.convention.annotation.*;

@Namespace("/board")

public class HelloWorldAction{

private String message;

@Action(value="hello", results={

@Result(name="success", location="/HelloWorld.jsp")})

public String execute(){

message = "I'm breadfish";

return "success";

}

public String getMessage(){

return message;

}

public void setMessage(String message){

this.message = message;

}

}

Page 35: Struts Tutorial

Print variable

vi ../../HelloWorld.jsp

http://bit.sparcs.org:8042/proj1/board/hello

Hello, World!

<p>

${message}

Page 36: Struts Tutorial

JSP TAG

종류 사용용도 형식

지시자 (Directive) JSP 페이지의 속성 지정

주석 (Comment) JSP 페이지에 설명을 넣음 <%-- --%>

선언 (declaration) 변수와 메소드 선언 <%! %>

표현식 (expression) 계산식이나 함수를 호출한 결과를 문자열 형태로 출력

<%= %>

스크립트릿(scriptlet)

자바 코드 기술 <% %>

액션 태그 자바 빈이나 애플릿 서버 모듈과 연결 <jsp:action></jsp:action>

Page 37: Struts Tutorial

Directive

종류 사용용도

page 해당 JSP 페이지의 속성을 지정

include 현재 페이지에 다른 파일의 내용을 삽입할 때 사용

taglib 태그 라이브러리에서 태그를 꺼내와 사용할 수 있는 기능 제공

<%@ page import=“java.util.Date” %>

<%@ page contentType=“text/html; charset=utf-8” %>

<%@ include file=“board01.jsp” %>

Page 38: Struts Tutorial

vi ../../HelloWorld.jsp<%@ page contentType=“text/html; charset=utf-8” %><%@ taglib prefix=“s” uri=“/struts-tags” %>

Hello, World!

<p>

${message}

<p>

<s:property value=“message”></s:property>

Page 39: Struts Tutorial

print array

HelloWorldAction.javapackage com.proj1.action;

import org.apache.struts2.convention.annotation.*;

import java.util.List;

import java.util.ArrayList;

@Namespace("/board")

public class HelloWorldAction{

private String message;

private List<String> messages;

@Action(value="hello", results={

@Result(name="success", location="/HelloWorld.jsp")})

public String execute(){

message = "I'm breadfish";

messages = new ArrayList<String>();

for(int i=0 ; i<10 ; i++){

messages.add("breadfish" + i);

}

return "success";

}

public String getMessage(){

return message;

}

public void setMessage(String message){

this.message = message;

}

public List<String> getMessages(){

return messages;

}

public void setMessages(List<String> messages){

this.messages = messages;

}

}

Page 40: Struts Tutorial

print array

HelloWorld.jsp

<%@ page contentType="text/html; charset=utf-8" %>

<%@ taglib prefix="s" uri="/struts-tags" %>

Hello, World!

<p>

${message}

<p>

<s:property value="message"></s:property>

<s:iterator value="messages">

<p>

<s:property></s:property>

</s:iterator>

Page 41: Struts Tutorial

Struts Tutorial 4

111129 구성모

Page 42: Struts Tutorial

RESULT…

@Action(value="hello", results={

@Result(name="success", location="/HelloWorld.jsp"),

@Result(name=“error", type=“dispatcher”, location="/error.jsp")})

public String execute(){

리절트 타입 설명

Chain 액션 체인을 위하여 사용된다 .

Dispatcher JSP 를 포함안 웹 리소스 연동을 위하여 사용된다 .

FreeMarker 프리마커 연동을 위하여 사용된다 .

HttpHeader 특수한 HTTP 작동을 조절하기 위해서 사용

Redirect 다른 URL 로 리다이렉트하기 위해 사용

Stream 브라우저에게 inputStream 을 스트리밍 하기 위해 사용

PlainText 특수한 페이지 (jsp, html 등 ) 의 컨텐츠 원본을 디스플레이

… …

Page 43: Struts Tutorial

form input

HelloWorldAction.java

compile

http://bit.sparcs.org:8042/proj1/board/hello?message=suckstruts

Page 44: Struts Tutorial

HelloWorld.jsp

struts-tags : form tag example

<%@ page contentType="text/html; charset=utf-8" %>

<%@ taglib prefix="s" uri="/struts-tags" %>

<%@ taglib prefix="sx" uri="/struts-dojo-tags" %>

<html>

<head>

<sx:head/>

</head>

<body>

<form action="" method="GET">

<sx:datetimepicker name="sdate"/>

<input type="submit"/>

</form>

${sdate}

</body>

</html>

package com.proj1.action;

import org.apache.struts2.convention.annotation.*;

import java.util.List;

import java.util.ArrayList;

import java.util.Date;

@Namespace("/board")

public class HelloWorldAction{

private Date sdate;

@Action(value="hello", results={

@Result(name="success", location="/HelloWorld.jsp")})

public String execute(){

return "success";

}

public Date getSdate(){

return sdate;

}

public void setSdate(Date sdate){

this.sdate = sdate;

}

}

HelloWorldAction.java

Page 45: Struts Tutorial

struts-tags : control tag example

<%@ page contentType="text/html; charset=utf-8" %>

<%@ taglib prefix="s" uri="/struts-tags" %>

<%@ taglib prefix="sx" uri="/struts-dojo-tags" %>

<html>

<head>

<sx:head/>

</head>

<body>

<s:if test="%{message=='show'}">

<sx:textarea></sx:textarea>

</s:if>

<s:else>

Message : ${message}

</s:else>

</body>

</html>

HelloWorld.jsp

Page 46: Struts Tutorial

Tags

Control Tags

•if•elseif•else•append•generator•iterator•merge•sort•subset

Data Tags

•a•action•bean•date•debug•i18n•include•param•property•push•set•text•url

Page 47: Struts Tutorial

Tags

Form Tags

•checkbox•checkboxlist•combobox•doubleselect•head•file•form•hidden•inputtransferselect•label•optiontransferselect•optgroup•password•radio•reset•select•submit•textarea•textfield•token•updownselect

Ajax Tags

•a•autocompleter•bind•datetimepicker•div•head•submit•tabbedPanel•textarea•tree•treenode

Page 48: Struts Tutorial

More - JSP

ScriptAction TagCookieSessionrequest, responseException handlerBeanOGNLFILE

Page 49: Struts Tutorial

More - Struts

InterceptorAction mapperAnnotationAjaxLogging

Page 50: Struts Tutorial

More

Model DAO, VO

Template FreeMaker SiteMesh Tiles

ORM mybatis hibernate

Page 51: Struts Tutorial

References

스트럿츠 2 프로그래밍 , 현철주 외 3 명 , 에이콘초보 개발자를 위한 서블릿 JSP 프로그래밍 ,

성윤광 외 3 명 , 대림http://struts.apache.org/2.x

Page 52: Struts Tutorial

Thanks

Q&A