티스토리 툴바

JSP 액션

JSP 2009/04/25 23:54


1.JSP액션

(1)개요

자바코드에 의해 객체를 생성하는 것이 아니라 태그를 이용하여 객체를 생성하고 사용하는 것 ->JSP태그 및 JSP 액션

 

(2)scope

-객체가 사용될 수 있는 범위(Life Cycle)

-page :pageContext에 저장(디폴트 스코프다.현재 페이지에서만 사용가능)

-request : HttpServletRequest에 저장(다른페이지까지 이동가능,foward방법에 의해서 )

-session:HttpSession에 저장

-application:ServletContext에 저장

 

 

2.jsp:useBean태그 - 객체의 생성

 

(1)구조

<jsp:useBean id="name" scope="page|request| session|applicatio"  -디폴트 :page

         typeSpec/>

         typeSpec ::= class="className" |

                           class ="className"  type="typename" |

                            type="typename" class ="className" |

                            beanName ="beanName" type="typename" |

                            type="typename" beanName ="beanName" |

                             type="typename"

 

 

<jsp:useBean id="name" scope="page|request| session|applicatio" 

         typeSpec/>

 body

</jsp:useBean>

 

(2)객체생성

 

<jsp:useBean id="connection" class ="myapp.Connection"/> //jsp액션을 이용한 객체생성

 

myapp.Connection connection = new myapp.Connection(); //자바코드를 이용한 객체 생성

 

위 아래 코드는 동일하다.

 

 

(3)객체의 속성 값 설정

<jsp:useBean id="connection" class ="myapp.Connection">

<jsp:setProperty name="connection" property="timeout" value= " 33" >

</jsp:useBean>

 

위의코드는 아래의 자바코드와 동일하다.

myapp.Connection connection = new myapp.Connection();

connection.setTmeout("33");

 

 

(4)객체 생성 및 속성값 조회예제

<%@ page contentType="text/html;charset=KSC5601" %>

<jsp:useBean id="time" class="java.util.Date" scope="page" /> ==><% java.util.Date time = new java.util.Date(); %>와 동일
<jsp:useBean id="hello" class="hello.HelloBean" scope="page" />

<html>
 <head><title>useBean 테스트</title></head>
 <body>
  <h3>useBean 테스트</h3>
  Hello..
  <%= hello.getName() %>
  <hr>
  현재 시간 : <%= time.toLocaleString() %>
 </body>
</html>

 

package hello;

public class HelloBean {
 private String name = "월드";
 
 public HelloBean() { }

 public void setName(String name) {
  this.name = name;
 }

 public String getName() {
  return name;
 }
}

get/set으로 할 때는 메소드이름에서 속성이름의 첫글자가 대문자로 적어야한다.

 

(5)application 스코프로 생성하는 경우

<jsp:useBean id="counter" class="foo.Counter" scope="application" />

 

-서블릿코드 (저장)

foo.Counter counter = new foo.Counter();

getServletContext().setAttribute("counter",counter);//데이터 보관

 

-서블릿 코드 - 다른 JSP나 서블릿에서 생성(조회)

foo.Counter counter = (foo.Counter)getServletContext().getAttribute("counter");//object 타입이므로 형변환 필요

 

3.jsp:setProperty태그 -속성에 값설정

(1)개요

자바빈에 속성값을 할당하는 태그

name 속성에 기술된 이름이 jsp:useBean을 이용해서 먼저 정의해야 한다.

name은 객체의 id 속성과 동일하게 한다.

 

 

<jsp:setProperty name="beanName" prop_expr />

           prop_expr ::= property ="*" |

                              property = "propertyName" |

                              property = "propertyName"  param ="parameterName"|

                              property = "propertyName" value="propertyValue"

           propertyValue ::= String

 

(2)jsp:setProperty태그 활용방법

-기본

mybean의 setName()를 호출해서 값을 설정

<jsp:setPropety name ="mybean" property="name" /> //사용자의 입력중 name 속성에 해당하는 값을 객체에 저장하라.

자바코드로 바꾸면 mybean.setName(request.getParameter("name"));

 

-여러개의 속성값을 세팅할 필요가 있는 경우  

<jsp:setProperty name="mybean" property="*" /> //사용자의 입력 모두를 mybean객체에 저장하라.

 

-매개변수의 이름이 다른 경우(클라이언트 코드의 속성과 서버쪽의 속성이 다른 경우)

<jsp:setProperty name="user" property="user" param="username"/>

//사용자의 입력 중 user속성에 대한 값을 username이라는 속성으로 저장하라.

자바코드로 바꾸면 use.setUser(request.getParameter("username"));

 

-매개변수의 값을 직접 할당하는 방법

<jsp:setProperty name="results" property="row" value="<%=i+1 %>" /> //row라는 속성에 value값을 직접 할당하라

자바코드로 바꾸면 results.setRow(String.valueOf(i + 1) );

 

(3)예제

<html><head><title>연락처</title></head>
<body>
<h3>연락처</h3>

<form method=post action=contact.jsp>
 이름 <input type=text name="name"><br>
 메일 <input type=text name="email"> <br>
 <p>
 <input type=submit value=전송>
 <input type=reset value=취소>
</form>
</body>
</html>

 

 

<%@ page contentType="text/html;charset=KSC5601" %>
<% request.setCharacterEncoding("KSC5601"); %>

<jsp:useBean id="info" class="contact.ContactInfo" scope="page" />
<jsp:setProperty name="info" property="*" /> //모든 데이터 저장

<html>
<head><title>setProperty 테스트</title></head>
 <body>
  <h3>setProperty 테스트</h3>
  이름 : <%= info.getName() %>  
  <p>
  Email : <%= info.getEmail() %>
 </body>
</html>

//ContactInfo.java(Bean클래스 )

package contact;

public class ContactInfo {
 private String name;
 private String email;
 
 public ContactInfo() { }
 
 public void setName(String name) { this.name = name; }
 public String getName() { return name; }
 
 public void setEmail(String email) { this.email = email; }
 public String getEmail() { return email; }
}

4.jsp:getProperty태그

(1)개요

-빈 객체의 속성을 문자열 타입으로 변환해서 out변수를 이용해서 출력한다.

-빈의 getXXX()메소드가 호출한다.

*는 사용 못한다.

<jsp:getProperty name="beanName" property="propertyName"/> 메소드이름

 

(2)활용예

 

<%= info.getName() %> 

<jsp:getProperty name="info" property="name"/>

 

5.jsp:param태그

-키와 값을전달하기 위해서 사용한다

jsp:include,jsp:plugin ,jsp:forward의 서브 원소로 사용

 

<jsp:param name = "name" value="value" />

 

6.jsp:plugin태그

(1)개요

-jsp페이지가 웹브라우저의 종류에 따라 그에 맞는 자바플러그인을 위한 HTML태그를 생성한다

-애플릿과 자바빈을 위해서만 사용할 수 있다.

 

<jsp:plugin type="bean | applet " code ="objectCode" codebase ="objectCodebase"  code 클래스 /codebase 폴더

    {align="alignment"} { archive="archiveList"} { height = "height"} {hspace = "hspace"}

    {jreversion="jreversion"}{name="componentName"}{vspace="vspace"}

    {width="width"}{nspluginurl="url"} { ieplugin="url"}>

    {<jsp:params>

       {<jsp:param name="paramName" value="paramValue"/>}

    {</jsp:params>}

    {<jsp:fallback>arbitrary_text</jsp:fallback>}

<jsp:plugin>

 

(2)예제

<%@ page contentType="text/html;charset=KSC5601" %>
<html>
<title> plugin 테스트 </title>
<body>
<center><h2>plugin 테스트</h2></center>

<jsp:plugin type="applet" code="PluginApplet.class"
 jreversion="1.5" width="300" height="250" >
  <jsp:params>
   <jsp:param name="data"
    value="<jsp:plugin>테스트입니다." />
  </jsp:params>       
  
    <jsp:fallback>
        Plugin tag OBJECT or EMBED not supported by browser.
    </jsp:fallback>
</jsp:plugin>
</body>
</html>

applet클래스는 jsp파일과 동일한 경로에 두어야한다.

 

//PluginApplet .java

import java.awt.*;
import javax.swing.*;
import java.applet.*;

public class PluginApplet extends JApplet {
 JMenuBar bar;
 JMenu    file, edit;
 JMenuItem fileNew, fileOpen, fileSave;
 JTextArea text;
 
 public void init() {
 
  bar = new JMenuBar();
  file = new JMenu("File");
  edit = new JMenu("Edit");
  bar.add(file);
  bar.add(edit);
  
  fileNew = new JMenuItem("New");
  fileOpen = new JMenuItem("Open");
  fileSave = new JMenuItem("Save");
  
  file.add(fileNew);
  file.add(fileOpen);
  file.add(fileSave);
  
  setJMenuBar(bar);
  
  String data = getParameter("data");//data라는 변수에서 값을 읽어들인다.
  
  text = new JTextArea(data);
  JScrollPane sp = new JScrollPane(text);
  
  getContentPane().setLayout(new BorderLayout());
  getContentPane().add(sp, "Center");
 }
}

6.jsp:forward

(1)개요

현재 클라이언트의 요청을 실행 시에 다른 자원으로 이동시킨다(dispatch)

파라미터를 전달하기 위해<jsp:param>태그 사용

 

a태그나 response.sendRedirect방법으로 열려진 페이지는 전혀 데이터의 이동이 없다.

forward방식으로 사용하면 열려진 페이지에서도 request를 사용할 수 있다.

 

-.<jsp:forward page = "relativeURLspec" />

-.<jsp:forward page ="urlSpec">

     {<jsp:param .../>

  </jsp:forward>

-.<% String whertTo ="/templates/" + somValue;  %>

   <jsp:forward page ='<%= whereTo %>' />

 

(2)예제

//gate.html

<html><head><title>
forward test
</title></head>
<body>
<center><h2>forward 테스트</h2></center>

<form method=POST action=gate.jsp>
이 름 <input type=text name=name> <br>
주 소 <input type=text name=addr>

<br><br>
<input type=submit value="전 송">
</form>
</body>
</html>

//gate.jsp

<%@ page contentType="text/html;charset=KSC5601" %>
<%
request.setCharacterEncoding("KSC5601");
String toWhere = "en.jsp";
String lang = "English";
String from = request.getRemoteHost();
if(from.endsWith("localhost") || from.endsWith("127.0.0.1")) {
 toWhere = "ko.jsp";
 lang = "한국어";
}
%>

<jsp:forward page="<%= toWhere %>">
    <jsp:param name="lang" value="<%= lang %>" /> //추가로 넘겨준 파라미터
</jsp:forward>

 

 

//en.jsp

<html>
<head><title>Welcome</title></head>
<body><center>
<h2>forward test</h2>
</center>
Thank you very much for visiting my site.
Your registed data are : <hr>

<li>Language : <%= request.getParameter("lang") %>
<li>Name : <%= request.getParameter("name") %>
<li>Address : <%= request.getParameter("addr") %>

</body>
</html>

 

//ko.jsp

<%@ page contentType="text/html;charset=KSC5601" %>
<html>
<head><title>환영합니다</title></head>
<body><center>
<h2>forward 테스트</h2>
</center>
저희 사이트를 방문해주셔서 대단히 감사드립니다.
등록하신 데이터는 다음과 같습니다.
<hr>
<%
 request.setCharacterEncoding("KSC5601");
%>
<li>언어: <%= request.getParameter("lang") %>
<li>이름: <%= request.getParameter("name") %>
<li>주소: <%= request.getParameter("addr") %>

</body>
</html>

 

처음요청된 페이지가 그대로 주소표시줄에 남는다.

 

 

7.jsp:include태그

(1)개요

-동일한 컨텍스트에 있는 정적 혹은 동적인 페이지를 현재 페이지에 삽입시킨다.

-.<jsp:include page = "urlSpec" flush="true" />

-.<jps:include page = "urlSpec" flush ="true">

      <jsp:param.../>

  </jsp:include>

 

(2)예제

//jinclude.jsp

<%@ page contentType="text/html;charset=KSC5601" %>

<html><head><title>
jsp:inclde
</title></head>
<body>
<center><h2>jsp:include 테스트</h2></center>

<jsp:include page="/servlet/EmbededServlet" flush="true"/>

<hr>

<jsp:include page="/embeded.jsp" flush="true" />

</body>
</html>

 

//EmbededServlet .java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class EmbededServlet extends HttpServlet {

 public void service(HttpServletRequest req, HttpServletResponse res)
  throws IOException, ServletException {
 
  res.setContentType("text/plain;charset=KSC5601");
  PrintWriter out = res.getWriter();
 
  out.println("안녕하세요");
  out.println("EmbededServlet 입니다.");
 }
}

 

//embedded.jsp

<%@ page contentType="text/html;charset=KSC5601" %>

안녕하세요 embeded JSP 페이지입니다. <br>

<%= request.getRemoteHost() %>에서 방문하셨군요.