<jsp:setProperty> 액션 태그

자바빈 객체의 프로퍼티 값 설정

구문

<jsp:setProperty name="id" property="이름" value=""  />

name - 자바빈 객체의 이름

property - 값을 설정할 프로퍼티

value - 프로퍼티의

<jsp:setProperty name="id" property="이름"
   
param="파라미터이름"  />

param - 프로퍼티의 값으로 사용할 파라미터 이름.

<jsp:setProperty name="id" property="*" />

프로퍼티와 동일한 이름의 파라미터를 이용해서 값을 설정

폼에 입력한 값을 자바 객체에 저장할 때 유용하게 사용




예제)



회원 정보 저장 폼



























Cookie 를 이용한 login 처리

cookie01.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	Cookie[] cookies = request.getCookies();
	boolean found = false;
	if(cookies==null){
		found=false;
	}else{
	for(int i=0;i<cookies.length;i++){
		if(cookies[i].getName().equals("sampleCookie")){
			found = true;
			}
		}
	}
	String msg = null;
	if( ! found){
		Cookie cookie = new Cookie("sampleCookie","This is Sample Cookie");
		response.addCookie(cookie);
		msg = "발견된 쿠키가 없었기 때문에 새로 설정했습니다.";
	}
%>
<!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=EUC-KR">
<title>쿠키 테스트</title>
</head>
<body>
<script type="text/javascript">
	var found = <%=found%>;
	if(!found){
		alert("<%=msg%>");
	}
</script>
</body>
</html>
loginForm.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!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=EUC-KR">
<title>로그인 폼</title>
</head>
<body>
<form action="loginProc.jsp" method="post">
<table>
<tr><th>아이디</th><td><input type="text" name="id"></td></tr>
<tr><th>비	번</th><td><input type="password" name="pwd"></td></tr>
<tr><td colspan="2"><input type="submit" value="로그인"></td></tr>
</table>
</form>
</body>
</html>
loginProc.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	String id= request.getParameter("id");
	String pwd= request.getParameter("pwd");
	if(id.length()> 0&& pwd.length()>0){
		request.setAttribute("login", "pass");
	%>
		<jsp:forward page="loginSuccess.jsp"/>		
 <%}else{%>
		<jsp:forward page="loginFail.jsp"/>
<%}
%>

loginSuccess.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	if(request.getAttribute("login")!=null){
		Cookie cookie = new Cookie("login","pass");
		response.addCookie(cookie);
	}else{
		response.sendRedirect("loginForm.jsp");
		return;
	}
%>
<!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=EUC-KR">
<title>로그인 성공</title>
</head>
<body>
<h1>로그인에 성공했습니다.</h1>
<%=request.getParameter("id") %><br/>
<%=request.getParameter("pwd") %><br/><p/>
<a href="service.jsp">서비스 이용하기</a>
</body>
</html>
service.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ include file="loginCheck.jsp" %>
<!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=EUC-KR">
<title>회원 이용가능 페이지</title>
</head>
<body><p/><p/><p/>
<h1>회원이므로 이 기능을 이용할 수 있습니다.</h1>
</body>
</html>
loginCheck.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
Cookie[] cookies = request.getCookies();
	boolean pass = false;
	if(cookies!=null){
		for(int i=0;i<cookies.length;i++){
			if(cookies[i].getName().equals("login")){
				pass = true;
				break;
			}
		}
	}
	if(!pass){
		response.sendRedirect("loginForm.jsp");
		return;
	}
%>






세션(session)이란

웹 컨테이너에서 클라이언트의 정보를 보관할 때 사용

오직 서버에서만 생성

클라이언트마다 세션이 생성





세션과 session 기본 객체

page 디렉티브의 session 속성 값을 true로 지정

-세션이 존재하지 않을 경우 세션이 생성되고, 세션이 존재할 경우 이미 생성된 세션을 사용

session 기본 객체를 이용해서 세션에 접근

-session의 기본 값은 true이므로 false로 하지 않는 이상 항상 세션 사용

<%@ page contentType = ... %>

<%@ page session = "true" %>

<%

    ...

    session.setAttribute("userInfo", userInfo);

    ...

%>

속성 이용해서 클라이언트 관련 정보 저장



Session을 이용한 login 처리

※위 cookie를 이용한 login 처리 예제와 소스 같고 아래만 소스바꿈

loginSuccess.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	if(request.getAttribute("login")!=null){
		/*상태 정보가 session으로 감  */
		session.setAttribute("login","pass");
	}else{
		response.sendRedirect("loginForm.jsp");
		return;
	}
%>
<!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=EUC-KR">
<title>로그인 성공</title>
</head>
<body>
<h1>로그인에 성공했습니다.</h1>
<%=request.getParameter("id") %><br/>
<%=request.getParameter("pwd") %><br/><p/>
<a href="service.jsp">서비스 이용하기</a>
</body>
</html>
loginCheck.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	String login = (String)session.getAttribute("login");
	if(login==null){
		response.sendRedirect("loginForm.jsp");
		return;
	}
%>


모든 페이지에서 로그인체크 해서 세션정보(아이디 비번)값이 없으면 경고 창 띄우고 loginForm으로 이동

loginCheck.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	String login = (String)session.getAttribute("login");
	boolean pass = false;
	if(login!=null){
		pass = true;
	}
	
%>	
<script type="text/javascript">
	var pass = <%=pass%>;
	if(!pass){
		alert("회원으로 로그인한 경우에만 사용할 수 있습니다.");
		location.href="loginForm.jsp";
	}
</script>




자바빈

Bean

-1.기본 생성자

-2.변수

-3.set,get

-4.public



자바빈(JavaBeans)


-자바빈 - 웹 프로그래밍에서 데이터의 표현을 목적으로 사용

-일반적인 구성

값을 저장하기 위한 필드

값을 수정하기 위한 setter

값을 읽기 위한 getter


public class BeanClassName {
    /* 값을 저장하는 필드 */
    private String value;
    
    /* BeanClassName의 기본 생성자 */
    public BeanClassName() {
    }
    
    /* 필드의 값을 읽어오는 값 */
    public String getValue() {
        return value;
    }

    /* 필드의 값을 변경하는 값 */
    public void setValue(String value) {
        this.value = value;
    }
}

<jsp:useBean> 태그

JSP에서 자바빈 객체를 생성할 때 사용

구문

-<jsp:useBean id="[빈이름]" class="[자바빈클래스이름]"    scope="[범위]" />

id - JSP 페이지에서 자바빈 객체에 접근할 때 사용할 이름

class - 패키지 이름을 포함한 자바빈 클래스의 완전한 이름

scope - 자바빈 객체가 저장될 영역을 지정한다. page, request, session, application 중 

하나를 값으로 갖는다. 기본값은 page.

-예

<jsp:useBean id="info" class="chap11.member.MemberInfo" scope="request" />
<%= info.getName() %>







페이지 모듈화



※JSP 주석(TomCat에 의해서 컨버젼 할때 문장 무시) : <%--  문장  --%>


<jsp:include> 액션 태그

-다른 JSP 페이지의 '실행' 결과를 현재 위치에 삽입

-동작 방식


<jsp:include> 액션 태그

구문
<jsp:include page="포함할페이지" flush="true" />
-page 속성 : 포함할 JSP 페이지
-flush 속성 : 지정한 JSP 페이지를 실행하기 전에 출력 버퍼를 플러시 할 지의 여부를 지정한다.
 true이면 출력 버퍼를 플러시하고, false이면 하지 않는다.

중복 영역을 모듈화 하는 데 유용



<jsp:param> 액션 태그
신규 파라미터를 추가하는 데 사용
<jsp:param name="파라미터이름" value="값" />

<jsp:include page="/module/top.jsp" flush="false">
    <jsp:param name="param1" value="value1" />
    <jsp:param name="param2" value="value2" />
</jsp:include>



<jsp:param> 액션 태그의 동작 방식

기존 파라미터는 유지하고 파라미터를 새로 추가
  <jsp:include>로 포함되는 페이지에서만 유효


main.jsp(위와 동일한 결과값 출력)

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!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=EUC-KR">
<title>메인 페이지</title>
</head>
<body>
<jsp:include page="top.jsp"/>
</body>
</html>

top.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>

<div style="border:1px solid red; background-color:#999999; height:100px;">
여기는 Top.jsp
</div>

보고있나






include 디렉티브

코드 차원에서 포함
구문 : <%@ include file="포함할파일" %>
활용
-모든 JSP 페이지에서 사용되는 변수 지정
-저작권 표시와 같은 간단하면서도 모든 페이지에서 중복되는 문장

main.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!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=EUC-KR">
<title>메인 페이지</title>
</head>
<body>
<%-- <jsp:include page="top.jsp"/> --%>
<%@include file="top.jsp" %>
</body>
</html>


※설정파일은 점차 사라지고 있다~~



<jsp:include> 액션 태그와 include 디렉티브




<jsp:forward> 액션 태그
하나의 JSP 페이지에서 다른 JSP 페이지로 요청 처리를 전달할 때 사용
동작 방식





<jsp:forward> 액션 태그의 전형적 사용법
<%@ page contentType = "text/html; charset=euc-kr" %>
<%
    String forwardPage = null;
    
    // 조건에 따라 이동할 페이지를 지정
    if (조건판단1) {
        forwardPage = "페이지URI1";
    } else if (조건판단2) {
        forwardPage = "페이지URI2";
    } else if (조건판단3) {
        forwardPage = "페이지URI3";
    }
%>
<jsp:forward page="<%= forwardPage %>" />


기본 객체의 속성을 이용한 값 전달
속성을 이용해서 JSP 페이지 간 값 전달
 - <jsp:include>나 <jsp:forward>에서 사용



include와 forword의 차이
gugu.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	String sDan = request.getParameter("dan");
	int dan = 0;
	if(sDan==null || sDan.equals("")){
		dan =2;
	}else{
	dan = Integer.valueOf(sDan);
	}
	String str = "";
	for(int i=1;i<=9;i++){
		str += dan + "*" + i+ "="+dan*i +"<br/>";
	}
	request.setAttribute("data", str);
%>
<jsp:forward page="guguView.jsp"/>
guguView.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	String str = (String)request.getAttribute("data");
%>
<!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=EUC-KR">
<title>구구단 보기(guguView.jsp)</title>
</head>
<body style="text-align:center;">
<%=str %>
</body>
</html>




01




에러 페이지 지정 & 에러 페이지 작성

에러 페이지 지정

- <%@ page errorPage = "예외발생시보여질JSP지정" %>


에러 페이지 작성

- <%@ page isErrorPage = "true" %>

isErrorPage 속성이 true인 경우 에러 페이지로 지정

- exception 기본 객체 : 발생한 예외 객체

exception.getMessage() : 예외 메시지

exception.printStackTrace() : 예외 추적 메시지 출력

- IE에서 예외가 올바르게 보여지려면 에러 페이지가 출력한 응답 데이터 크기가 513 바이트보다 커야 함

- <% response.setStatus(HttpServletResponse.SC_OK);%>


※요즘은 web.xml이용하지 않는게 추세




gugu.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ page errorPage="error.jsp" %>    
<%
	String sDan = request.getParameter("dan");
	int dan =  Integer.valueOf(sDan);	
	String str = "";
	for(int i=1;i<=9;i++){
		str += dan + "*" + i+ "="+dan*i +"<br/>";
	}
	request.setAttribute("data", str);
%>
<jsp:forward page="guguView.jsp"/>

error.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%@ page isErrorPage="true" %>
<!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=EUC-KR">
<title>오류발생!!</title>
</head>
<body style="text-align:center;">
<h1>요청을 처리하는 중에 요류가 발생했습니다.</h1>
발생한 예외의 내용<p/><%=exception %>
</body>
</html>






Cookie

이용자의 상태정보를 클라이언트에 저장 할려고 하는 수단, 화면 출력용이 아님


JSP에서 쿠키 생성 / 읽기




쿠키 값의 인코딩/디코딩 처리

쿠키는 값으로 한글과 같은 문자를 가질 수 없음

-쿠키의 값을 인코딩해서 지정할 필요 있음


쿠키 값의 처리

 -값 설정시 : URLEncoder.encode("값", "euc-kr")

예, new Cookie("name", URLEncoder.encode("값", "euc-kr"));



     -값 조회시 : URLDecoder.decode("값", "euc-kr")

Cookie cookie = …; String value = URLDecoder.decode(cookie.getValue(), "euc-kr");



쿠키 값 변경
기존에 존재하는 지 확인 후, 쿠키 값 새로 설정
Cookie[] cookies = request.getCookies();
if (cookies != null && cookies.length > 0) {
    for (int i = 0 ; i < cookies.length ; i++) {
        if (cookies[i].getName().equals(name)) {
        	Cookie cookie = new Cookie(name, value);
        	response.addCookie(cookie);
        }
    }
}


cookie01.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	Cookie[] cookies = request.getCookies();
	boolean found = false;
	if(cookies==null){
		found=false;
	}else{
	for(int i=0;i<cookies.length;i++){
		if(cookies[i].getName().equals("sampleCookie")){
			found = true;
			}
		}
	}
	String msg = null;
	if( ! found){
		Cookie cookie = new Cookie("sampleCookie","This is Sample Cookie");
		response.addCookie(cookie);
		msg = "발견된 쿠키가 없었기 때문에 새로 설정했습니다.";
	}
%>
<!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=EUC-KR">
<title>쿠키 테스트</title>
</head>
<body>
<script type="text/javascript">
	var found = <%=found%>;
	if(!found){
		alert("<%=msg%>");
	}
</script>
</body>
</html>




주요 기본 객체




※println()쓰는 이유
HTML소스코드 줄바꿈 되서 브라우져 소스보기에 출력되기 때문에



영역객체(Scope Object


PAGE 영역 - 하나의 JSP 페이지를 처리할 때 사용되는 영역

REQUEST 영역 - 하나의 HTTP 요청을 처리할 때 사용되는 영역

SESSION 영역 - 하나의 웹 브라우저와 관련된 영역(한 사람의 아이디 비번 ,구매한 물건의 갯수,가격 공유안됨)

APPLICATION 영역 - 하나의 웹 어플리케이션과 관련된 영역




속성(Attribute)





속성의 활용











<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	pageContext.setAttribute("myData", "페이지영역에 저장된 데이타");
%>
<!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=EUC-KR">
<title>Page Scope Test</title>
</head>
<body>
<%=pageContext.getAttribute("myData") %>
</body>
</html>






loginForm.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!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=EUC-KR">
<title>로그인 폼</title>
</head>
<body>
<form action="loginProc.jsp" method="post">
<table>
<tr><th>아이디</th><td><input type="text" name="id"></td></tr>
<tr><th>비	번</th><td><input type="password" name="pwd"></td></tr>
<tr><td colspan="2"><input type="submit" value="로그인"></td></tr>
</table>
</form>
</body>
</html>
loginProc.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	String id= request.getParameter("id");
	String pwd= request.getParameter("pwd");
	if(id.length()> 0&& pwd.length()>0){%>
		<jsp:forward page="loginSuccess.jsp"/>		
 <%}else{%>
		<jsp:forward page="loginFail.jsp"/>
<%}
%>

loginSuccess.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!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=EUC-KR">
<title>로그인 성공</title>
</head>
<body>
<h1>로그인에 성공했습니다.</h1>
<%=request.getParameter("id") %><br/>
<%=request.getParameter("pwd") %><br/>
</body>
</html>
loginFail.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!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=EUC-KR">
<title>로그인 실패</title>
</head>
<body>
<h1>로그인에 실패하셨습니다.</h1>
</body>
</html>



012



camera.jsp
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	if(session.getAttribute("cart")== null){
		session.setAttribute("cart", new java.util.ArrayList<String>());
	}

	ArrayList<String> cart = (ArrayList<String>)session.getAttribute("cart");
	cart.add("Camera,Canon DSLR 450,1000000");
%>
<!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=EUC-KR">
<title>카메라 구입 페이지</title>
</head>
<body>
<h1>카메라를 장바구니에 담았습니다.</h1>
<a href="notebook.jsp">노트북 매장 가기</a>
</body>
</html>
notebook.jsp
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	if(session.getAttribute("cart")==null){
		session.setAttribute("cart", new java.util.ArrayList<String>());
	}

	ArrayList<String> cart = (ArrayList<String>)session.getAttribute("cart");
	cart.add("Notebook,Apple MacBook Pro,1200000");
%>
<!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=EUC-KR">
<title>노트북 구입 페이지</title>
</head>
<body>
<h1>노트북을 장바구니에 담았습니다.</h1>
<a href="car.jsp">자동차 매장 가기</a>
</body>
</html>
car.jsp
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	if(session.getAttribute("cart")==null){
		session.setAttribute("cart", new java.util.ArrayList<String>());
	}

	ArrayList<String> cart = (ArrayList<String>)session.getAttribute("cart");
	cart.add("자동차,현대 소나타,8200000");
%>
<!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=EUC-KR">
<title>자동차 구입 페이지</title>
</head>
<body>
<h1>자동차를 장바구니에 담았습니다.</h1>
<a href="showCart.jsp">장바구니 내용보기</a>
</body>
</html>
showCart.jsp
<%@ page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	ArrayList<String> cart = (ArrayList<String>)session.getAttribute("cart");
%>
<!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=EUC-KR">
<title>장바구니 보기</title>
</head>
<body>
<h1>장바구니 내용</h1>
<ol>
<%
	for(int i=0;i<cart.size();i++){
		String item = cart.get(i);%>
		<li><%=item %>
 <%}
%>

</ol>
</body>
</html>




<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	if(application.getAttribute("count")==null){
		application.setAttribute("count",0);
	}
	int cnt =(Integer)application.getAttribute("count");
	cnt++;
	application.setAttribute("count",cnt);
%>
<!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=EUC-KR">
<title>방문자 수</title>
</head>
<body>
<h1>현재까지의 클릭한 수</h1>
<%=application.getAttribute("count") %>
</body>
</html>


reflash 할때 마다 클릭수가 바뀐다~







































'解憂所' 카테고리의 다른 글

여수 해양 엑스포 ..  (0) 2012.08.09
엑스포는 다음 기회에...ㅡㅡ;  (0) 2012.07.05
검은 대장장이?....  (0) 2012.07.05
HOT!!!!summer....  (0) 2012.06.17
많은 일들......  (0) 2012.06.16

선언부(Declaration)


스크립트릿이나 표현식에서 사용할 수 있는 함수를 작성할 때 사용

선언부 형식


<%!
    public 리턴타입 메서드이름(파라미터목록) {
        자바코드1;                                              메소드, 변수, 클래스 선언 가능
        자바코드2;
        ...
        자바코드n;
        return 값;
    }
%>

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%! 
	private String createGugu(int dan){
		String str ="";
		for(int i=1;i<=9;i++){
			str +=dan + " * " + i + " = " + dan*i + "<br/>"; 
		}
		return str;
	}

%>
<% int dan= Integer.valueOf(request.getParameter("dan")); %>
<!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>Declaration Test</title>
</head>
<body>

	<%=createGugu(dan)%>
</body>
</html>





<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%! 
	private ArrayList<String> createGugu(int dan){
		ArrayList<String> list= new ArrayList<String>();
		for(int i=1;i<=9;i++){
			list.add(dan + " * " + i + " = " + dan*i); 
		}
		return list;
	}

%>
<% int dan= Integer.valueOf(request.getParameter("dan")); %>
<!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>Declaration Test</title>
</head>
<body>

	<%=createGugu(dan)%>
</body>
</html>



↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓



<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%! 
	private ArrayList<String> createGugu(int dan){
		ArrayList<String> list= new ArrayList<String>();
		for(int i=1;i<=9;i++){
			list.add(dan + " * " + i + " = " + dan*i); 
		}
		return list;
	}

%>
<% int dan= Integer.valueOf(request.getParameter("dan")); %>
<!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>Declaration Test</title>
</head>
<body>
<%
	ArrayList<String> list = createGugu(dan);
	for(int i=0;i<list.size();i++){
		String line = list.get(i);%>
		<%=line %><br/>

<%}%>
</body>
</html>





jsp 모델1 방식(JSP, JAVA) 


Gugudan.java

package web.business;

import java.util.ArrayList;

public class Gugudan {
	private int num;

	public int getNum() {
		return num;
	}

	public void setNum(int num) {
		this.num = num;
	}
	public ArrayList<String> createGugu(int dan){
		ArrayList<String> list= new ArrayList<String>();
		for(int i=1;i<=9;i++){
			list.add(dan + " * " + i + " = " + dan*i); 
		}
		return list;
	}
}

gugudan.jsp
<%@page import="web.business.Gugudan"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>

<% 
	int dan= Integer.valueOf(request.getParameter("dan")); 
	Gugudan gugu = new Gugudan();
	ArrayList<String> list = gugu.createGugu(dan);
%>
<!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>Declaration Test</title>
</head>
<body>
<%
	for(int i=0;i<list.size();i++){
		String line = list.get(i);%>
		<%=line %><br/>

<%}%>
</body>
</html>






request 기본 객체


form 처리예

form.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!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=EUC-KR">
<title>Servlet POST 방식으로 요청하기</title>
</head>
<body>
<form  action="formProc.jsp" method="post">
	취미를 선택해주세요(다수개 가능)<p/>
	여행<input type="checkbox" name="hobby" value="여행"/>
	등산<input type="checkbox" name="hobby" value="등산"/>
	게임<input type="checkbox" name="hobby" value="게임"/>
	영화<input type="checkbox" name="hobby" value="영화"/>
	놀기<input type="checkbox" name="hobby" value="놀기"/>
	<input type="submit" value="저장"/>
</form>

</body>
</html>


formProc.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<%
	request.setCharacterEncoding("euc-kr");
	String[] hobby = request.getParameterValues("hobby");
%>    
<!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=EUC-KR">
<title>이용자가 선택한 취미</title>
</head>
<body>
<h2>이용자가 선택한 취미</h2>
<ol>
<%
	for(int i=0;i<hobby.length;i++){%>
		<li><%=hobby[i] %><br/>
<%}
%>
</ol>
</body>
</html>







리다이렉트(Redirect)
특정 페이지로 이동하라고 웹 브라우저에 응답

response.sendRedirect(String location)로 구현















Model 2 ---->MVC


C   servlet  ----HTML (x)

                       veiw (x)

                       controller(o)


V    JSP -------view(0)

                       HTML


M    JAVA







스크립트 요소

표현식(Expression) - 값을 출력                      <%=  %>     안(메소드를 선언 할 수 없다.)

스크립트릿(Scriptlet) - 자바 코드를 실행           <%   %>      


선언부(Declaration) - 자바 메서드(함수)를 정의 <%!  %>     → service 메소드 으로 나간다.


Directive                                                       <%@ %>   




<%@ page contentType = "text/html; charset=euc-kr" %>        → Directive
   include                                                                                 → 개발자가 TomCat한테 

   taglib  - JSTL                                                                                                

         Struts                                                                                              JSP → Servlet으로 바꿀때  

         Spring                                                                                                   └(Conversion Time)

<html>

<head>

  <title>HTML 문서의 제목</title>

</head>

<body>

<%                                                                                    →Scriptlet(service메소드 안쪽으로 들어가는 소스; 지역변수)

    String bookTitle = "JSP 프로그래밍";         

    String author = "최범균";

%>

<b><%= bookTitle %></b>(<%= author %>)입니다.                →Expression("bookTilte"은 service메소드 안쪽으로 간다)

</body>

</html>



<%out.print("bookTiltle");%> == <%= bookTitle %> 위 표현식을 scriptlet에 이렇게 표현 할 수 있지만 소스를 줄이기 위해 표현식으로 쓴다.


무공해 우리집 수박.....크기는 2만원을 넘어서는 크기 였음.....





아직 익지않은 자두....벌레가 먹는다고 해서 약을 쳐야하나 고민중...





어디서 앙탈이니 달콩아....





도라지 꽃...





해바라기를 배경으로.... 이놈의 벌들...






담에 또보자 복돌이 복순아~~~그런데 복순이 넌 언제 복돌이 집으로 넘어왔냐?...

'解憂所' 카테고리의 다른 글

여수 해양 엑스포 ..  (0) 2012.08.09
수원 화성..  (0) 2012.07.08
검은 대장장이?....  (0) 2012.07.05
HOT!!!!summer....  (0) 2012.06.17
많은 일들......  (0) 2012.06.16



팥빙수 먹으로 blackSmith?  아무튼.....사람들 없을 때 한컷....매장이 그냥 시멘트 벽이라 인테리어 비가 별로 안들었을 것 같은.....녹차 빙수 좀 제발 시키지말아줘....

'解憂所' 카테고리의 다른 글

수원 화성..  (0) 2012.07.08
엑스포는 다음 기회에...ㅡㅡ;  (0) 2012.07.05
HOT!!!!summer....  (0) 2012.06.17
많은 일들......  (0) 2012.06.16
화엄사~~~  (2) 2012.05.28

java 설치 확인

 

cmd창 열고

 

java -version     그러면 자바 설치 가 되어 있다면 설치 버젼이 나옴

 

java

 

javac

 

echo %classpath%

이렇게 나오면 오류나니

 

환경 변수에 새로 만들기

CLASSPATH

.;

 

이렇게 해줌~~

 

 

<IDE :통합 개발 환경 [integrated development environment, 統合開發環境] >

1.에디터

2.JSK 툴

3.webbrowser(client)

4.web server를 편리하게

 


JSP(잘할려면)---->servlet



Servlet - 서버(Serv)에 들어가는 작은(let) 프로그램이다..



HTTP Server   -----servlet(요청과 응답을 다룰수 있는 기능이 있음)


       ↑           

(request ) (response)

                      ↓

Webbrowser   ------http client










package test.web.servlet;

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 org.apache.jasper.tagplugins.jstl.core.Out;


public class TestServlet extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/plain;charset=euc-kr");//http header부분
		
		int num = Integer.valueOf(request.getParameter("num"));//request로 부터 num이라는 파라미터를 받겠다.(숫자여도 문자열로 받기 때문에 Integer)
		
		PrintWriter out = response.getWriter();
		for(int i=1;i<=9;i++){
			out.println(num + " * " + i + " = " +num*i+"</br>");
		}
		
		//server client 연결...stream
		out.println("Hello World");
		out.flush();//buffer안에 있는 데이터를 브라우져로 전송
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

}


http://localhost:8080/WebApp/TestServlet  이러면 오류가 남


http://localhost:8080/WebApp/TestServlet?num=7

이렇게 뒤에다  num 값을 주면 7단 구구단이 출력된다.



'JSP > 2012.04강의(MySQL)' 카테고리의 다른 글

복습3 선언부(Declaration),request 기본 객체,리다이렉트(Redirect)  (0) 2012.07.06
복습2 스크립트 요소  (0) 2012.07.05
예비  (0) 2012.05.30
예비  (0) 2012.05.30
예비  (0) 2012.05.30

RegisterUser1 (redirect 연습)

package com.ch5.action;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import com.opensymphony.xwork2.Action;

public class RegisterUser1 implements Action{

    private String userId;
    
    @Override
    public String execute() throws Exception {
             
        return SUCCESS;
    }
    
    public String getUserId() {
        String id="";
        try {
            id =URLEncoder.encode(userId,"utf-8");
        }catch(UnsupportedEncodingException e){
            e.printStackTrace();
        }
        return id;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }    
}



struts-ch5.xml

<?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>
    <package name="ch5" namespace="/ch5" extends="struts-default">
         
        
        <!-- redirect -->
        <action name="register" class="com.ch5.action.RegisterUser1">
            <interceptor-ref name="params"/>
            <result name="success" type="redirect">registerSuccess.jsp?userId=${userId}</result>
        </action>
    </package>
</struts>




 registerForm1.jsp (redirect 연습)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>chain 연습</title>
</head>
<body>
<form action="register.action" method="post">
id:<input type="text" name="userId"><br/>
<input type="submit" value="로그인">
</form>
</body>
</html>



                 registerSuccess.jsp (redirect 연습)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>redirect 연습</title>
</head>
<body>
<h1>${param.userId}님 환영합니다.</h1>
</body>
</html>




Chapter04.zip


redirectAction


redirectAction 리절트 타입의 동작 원리는 result 리절트 타입과 동일하다. result 리절트 타입은 리다이렉트할 URL을 지정하였지만, redirectAction 리절트 타입은 actionName 파라미터를 사용하여 리다이렉트 대상이 될 액션 이름을 지정한다.


<action name="UserRegAction" class="action.UserRegAction">
     <interceptor-ref name="params"/>
     <result name ="success" type="redirectAction">
       <param name="actionName">LoginAction</param>
       <param name="userId">${userId}</param>
       <param name="message">${message}</param>
     </result>
  </action>

<action name="LoginAction" class="action.LoginAction">
    <intercepter-ref name="params"/>
    <result name="success">/jsp/userRegSuccess.jsp</result>
 </action>




<global-results/>


액션 요청의 결과를 이한 result 요소는 action 요소의 자식 요소로 설정한다. 경우에 따라서는 여러개의 action 요소에 동일한 result 요소가 설정되는 경우가 있다.


로그인 페이지나 에러페이작 대표적인 예일것이다. 이런 페이지들이 여러 action 요소에 중복되어 설정되는 것을 피하기 위한  방법으로 global-result를 사용할수있다.


<package name="sample" extends="struts-default">
     <global-results>
          <result name="login">/jsp/login.jsp</result>
          <result name="error">/jsp/error.jsp</result>
     </global-results>
     
     <action name="sample" class"tutorial.SampleAction">
          <result name="success">/jsp/smple.jsp</result>
     </action>
</package>



sample 액션을 수행한후 리턴 코드 값으로 success 를 되돌리면 local result에 정의된 success result 에 의해 sample.jsp를 결과 페이지로 출력한다. 만일 sample 액션의 수행후 리턴 코드 값으로 login혹은 error를 되돌릴 경우에는 일차적으로 결과페이지 localresult에서 찾는다 localresult에서 찾지못하면 패키지 내 정의된 <global-results> 에서 찾는다.

dispatcher방식으로 action을 호출함



LoginAction (Chain 연습)

package com.ch5.action;

import com.opensymphony.xwork2.Action;

public class LoginAction implements Action{
    
    private String userId;
    private String message;
    
    @Override
    public String execute() throws Exception {
        message = (message==null ? "" : message) + userId + "로 로그인 했습니다.";
        return SUCCESS;
    }  

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}



                       RegisterUser (Chain 연습)

package com.ch5.action;

import com.opensymphony.xwork2.Action;

public class RegisterUser implements Action{

    private String userId;
    private String password;
    private String message;
         
    @Override
    public String execute() throws Exception {
        message = userId + "를 등록했습니다.";
        return SUCCESS;
    }
  
    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getMessage() {
        return message;
    }

    public void setPassword(String password) {
        this.password = password;
    }    
}


struts-ch5.xml
<?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>
    <package name="ch5" namespace="/ch5" extends="struts-default">
         
<!-- chain -->
        <action name="registerAndLogin" class="com.ch5.action.RegisterUser">
            <interceptor-ref name="params"/>
            <result name="success" type="chain">
                <param name="actionName">login</param>
                <param name="namespace">/ch5</param>
            </result>
        </action>
        <action name="login" class="com.ch5.action.LoginAction">
            <interceptor-ref name="chain"/>
            <interceptor-ref name="params"/>
            <result name="success" type="dispatcher">result.jsp</result>
        </action>

    </package>
</struts>


registerForm.jsp (Chain 연습)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>chain 연습</title>
</head>
<body>
<form action="registerAndLogin.action" method="post">
id:<input type="text" name="userId"><br/>
비밀번호:<input type="password" name="password"><br/>
<input type="submit" value="로그인">
</form>
</body>
</html>



result.jsp (Chain 연습)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>chain 연습</title>
</head>
<body>
${message}
</body>
</html>



                 userForm3.jsp (Chain 연습)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>도메인 오브젝트 테스트</title>
</head>
<body>
<form action="createUser3.action" method="post">
    이름: <input type="text" name="name"><br/>
    나이: <input type="text" name="age"><br/>
    이메일: <input type="text" name="email"><br/>
    <input type="submit" value="전송">
</form>
</body>
</html>






Chapter04.zip



dispatcher 와 redirect 리절트 타입 : 전달된 데이터가 계속 전달되지 않고 페이지가 이동하는것이 특징


redirect 리절트 타입은 JSP에서 response.sendRedirect("...") 메소드를 호출한 것과 같은 효과를 낸다.

redirect 리절트 타입은 리다이렉트할 URL을 응답으로 웹 브라우저에 보낸다.

URL로 새롭게 서버와 연결이 되므로 request가 새롭게 생성되는 것을 의미한다. 웹브라우저에 나타나는 URL로 바뀐다.


dispatcher는 request가 유지된다. 서버와 새롭게 연결이 되는 것이 아니므로 처음 접속 했던 request 정보를 가지고 있다. 

dispatcher는 요청 처리를 다른 웹 리소스로 위임 하는 것이다 따라서 웹 브라우저에 요청 URL이 바뀌지 않는다. 


         <!-- dispatcher와 redirect 리절트 타입 -->
        <action name="LoginAction1" class="action.LoginAction">
            <interceptor-ref name="params"/>
            <result name="success" type="dispatcher">loginSuccess.jsp</result>
        </action>



=> URL이 바뀌지않고 이전페이지의 정보가 유지되어  userid와 message값이 출력되도록할수있다.

        

    <!-- redirect -->
        <action name="LoginAction2" class="action.LoginAction">
            <interceptor-ref name="params"/>
            <result name="success" type="redirect">loginSuccess.jsp</result>
        </action>


=> URL이  loginSuccess.jsp로 변경되고 이전 페이지의 정보가 유지되지 않아 실행결과 페이지에 userid와 message값이 출력되지않았다.

리절트의 타입의종류


체인리절트를 활용한 액션 체인 : 계속 다른 페이지로 데이터를 보낼수있다.


2개의 액션을 체인 리절트 활용하여 회원 등록 액션 처리 후 로그인 액션이 처리되도록 하자.

ex)


1. 최초 회원 가입 페이지를 출력할 액션인 UserRegForm.action

2. 회원가입 정보를 저장할 액션인 UserRegLoginAction.action

3. 로그인 정보를 조회할 액션인 LoginAction.action


UserRegForm.action => UserRegForm.jsp => UserRegLoginAction.action (UserRegLoginAction.java 의 execute()메소드):UserRegLoginAction는 jsp가없다.

          

                                        ====chain===> LoginAction.action (LoginAction.java의 execute()메소드) ===>

 userRegsuccess.jsp  


UserRegForm,LoginAction 2개의 액션을 체인리절트활용

 <!-- chain -->
        <action name="registerAndLogin" class="com.ch5.action.RegisterUser">
            <interceptor-ref name="params"/>           
<result name="success" type="chain">
                <param name="actionName">login</param>
                <param name="namespace">/ch5</param>
            </result>
        </action>

        <action name="login" class="com.ch5.action.LoginAction">      
      <interceptor-ref name="chain"/>
            <interceptor-ref name="params"/>
            <result name="success" type="dispatcher">result.jsp</result>
        </action>

   

'Struts2 > 기본(Oracle)' 카테고리의 다른 글

struts2 chain  (0) 2012.06.27
struts2 dispatcher 와 redirect 리절트 타입  (0) 2012.06.27
struts2 커스텀 인터페이스  (0) 2012.06.27
struts2 커스텀 인터셉터  (0) 2012.06.21
struts2 인터셉터란?  (0) 2012.06.21

+ Recent posts