본문 바로가기

5월 ~ 7월) 웹/mvc

71Day -

7월 14일 (71Day)

mvc


필터 (중요함)
src/main/java/xyz.itwill.filter)
EncodingFilter .java

package xyz.itwill.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

//필터(Filter) : 클라이언트 요청에 대한 웹프로그램 실행 전 또는 후에 동작될 기능을 제공
// => WAS(웹컨테이너)에 의해 관리되며 XSS 방어, 인코딩 변환 처리, 요청에 대한 인증, 권한 검사 등에 사용 

//필터 클래스 : 클라이언트 요청에 대한 웹프로그램 실행 전 또는 후에 동작될 명령을 작성하기 위한 클래스
// => Filter 인터페이스를 상속받아 작성
// => @WebFilter 어노테이션 또는 [web.xml] 파일의 엘리먼트를 사용하여 필터 클래스를 필터로 
//등록하고 URL 패턴정보를 매핑 처리하여 사용

//클라이언트가 요청하는 모든 웹프로그램 실행 전에 리퀘스트 메세지 몸체부에 저장되어 전달되는
//값에 대한 캐릭터셋를 변경하는 기능을 제공하는 필터 클래스 - 인코딩 필터
public class EncodingFilter implements Filter {
	private String encoding;
	
	//필터를 동작하기 위한 필터 클래스를 객체로 생성한 후 가장 먼저 한번만 호출되는 메소드 
	// => 초기화 작업에 필요한 명령 작성
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		//FilterConfig.getInitParameter(String name) : [web.xml] 파일에서 init-param 엘리먼트로
		//제공되는 값을 얻어와 반환하는 메소드
		encoding=filterConfig.getInitParameter("encoding");
	}
	
	//웹프로그램 실행 전 또는 후에 동작될 명령을 작성하는 메소드
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		//웹프로그램 실행 전에 동작될 명령 작성
		if(request.getCharacterEncoding() == null || 
				!request.getCharacterEncoding().equalsIgnoreCase(encoding)) {
			request.setCharacterEncoding(encoding);
		}

		//FilterChain.doFilter(ServletRequest request, ServletResponseresponse)
		// => 다른 필터 객체 연결하여 사용하기 위한 메소드
		// => 필터 객체가 없는 경우 서블릿 객체와 연결되어 웹프로그램 실행
		chain.doFilter(request, response);
		
		//웹프로그램 실행 후에 동작될 명령 작성
		
	}

}



--------------------

mvc/src/main/webapp/WEB-INF )
web.xml (수정)

<?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_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>mvc</display-name>
  
  <!-- context-param : 모든 웹프로그램에게 값을 제공하기 위한 엘리먼트 -->
  <context-param>
  	<param-name>name</param-name>
  	<param-value>홍길동</param-value>
  </context-param>
  
  <!-- filter : 클래스를 필터(Filter)으로 등록하기 위한 엘리먼트 -->
  <!-- => servlet 엘리먼트 선언 전에 작성하는 것을 권장 -->
  <filter>
  	<filter-name>encoding filter</filter-name>
  	<filter-class>xyz.itwill.filter.EncodingFilter</filter-class>
  	<!-- init-param : 필터 클래스에 필요한 값을 제공하기 위한 엘리먼트 -->
  	<init-param>
  		<param-name>encoding</param-name>
  		<param-value>utf-8</param-value>
  	</init-param>
  </filter>
  
  <!-- filter-mapping : 필터가 실행되기 위한 요청 웹프로그램의 URL 패턴을 등록하기 위한 엘리먼트 -->
  <filter-mapping>
  	<filter-name>encoding filter</filter-name>
  	<!-- 클라이언트가 모든 웹프로그램을 요청한 경우 필터가 동작되도록 URL 패턴 등록 -->
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
  
  <!-- servlet : 클래스를 웹프로그램(서블릿)으로 등록하기 위한 엘리먼트 -->
  <servlet>
  	<servlet-name>controller</servlet-name>
  	<servlet-class>xyz.itwill.mvc.ControllerServlet</servlet-class>
  	<!-- init-param : 서블릿 클래스에 필요한 값을 제공하기 위한 엘리먼트 -->
  	<init-param>
  		<param-name>configFile</param-name>
  		<param-value>/WEB-INF/model.properties</param-value>
  	</init-param>
  	<!-- load-on-startup : 클라이언트 요청 없이 서블릿 클래스를 객체로 생성하기 위한 엘리먼트 -->
  	<!-- => WAS 프로그램 프로그램이 실행될 때 서블릿 클래스로 객체를 미리 생성 --> 
  	<!-- => 서블릿 객체를 생성되고 init() 메소드가 자동 호출되어 초기화 작업 -->
  	<!-- => 엘리먼트의 값은 0 이상의 정수값으로 설정하며 정수값이 작을수록 먼저 서블릿 객체로 생성 -->
  	<load-on-startup>1</load-on-startup>
  </servlet>
  
  <!-- servlet-mapping : 웹프로그램(서블릿)에 URL 패턴을 등록하기 위한 엘리먼트 -->
  <servlet-mapping>
  	<servlet-name>controller</servlet-name>
  	<url-pattern>*.do</url-pattern>
  </servlet-mapping>
  
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.jsp</welcome-file>
    <welcome-file>default.htm</welcome-file>
  </welcome-file-list>
</web-app>



java/mvc/src/main>webapp> jstl)
core_redirect_action .jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%-- Formatter 태그 라이브러리를 JSP 문서에 포함  - 접두사로 [fmt] 사용 --%>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%--
	//POST 방식으로 요청하여 전달된 값에 대한 캐릭터셋 변경
	request.setCharacterEncoding("utf-8");
--%>    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>MVC</title>
</head>
<body>
	<h1>Core -  URL 관리 태그</h1>
	<hr>
	<%-- requestEncoding 태그 : POST 방식으로 요청하여 전달된 값에 대한 캐릭터셋 변경하는 태그 --%>
	<%-- value 속성 : 변경할 문자형태(CharacterSet)에 대한 인코딩 방식을 속성값으로 설정 --%>
	<%-- <fmt:requestEncoding value="utf-8"/> --%>
	<c:choose>
		<c:when test="${!empty(param.name) }">
			<p>${param.name }님, 안녕하세요.</p>
		</c:when>
		<c:otherwise>
			<%-- redirect 태그 : 클라이언트에게 URL 주소를 전달하여 응답하는 태그 --%>
			<%-- => URL 주소를 응답받은 클라이언트는 브라우저의 URL 주소를 변경하여 요청 처리 --%>
			<%-- url 속성 : 클라이언트에게 전달할 URL 주소를 속성값으로 설정 --%>
			<c:redirect url="core_redirect_form.jsp"/>
		</c:otherwise>
	</c:choose>
</body>
</html>


core_redirect_form .jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>MVC</title>
</head>
<body>
	<h1>Core -  URL 관리 태그</h1>
	<hr>
	<form action="core_redirect_action.jsp" method="post">
		이름 : <input type="text" name="name">
		<button type="submit">제출</button>
	</form>
</body>
</html>



java/mvc/src/main>webapp> jstl)
core_url .jsp (코알라 사진)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>MVC</title>
</head>
<body>
	<h1>Core -  URL 관리 태그</h1>
	<hr>
	<%-- 웹자원의 경로를 상대경로로 표현하여 제공 --%>
	<%-- 상대경로 : 요청 웹프로그램의 경로를 기준으로 웹자원의 경로를 표현하는 방법 --%>
	<%-- 문제점)MVC 디자인 패턴을 이용한 JSP Model-2 방식의 웹프로그램 작성시 요청 웹프로그램
	(컨트롤러)의 경로과 응답 웹프로그램(뷰)의 경로가 다른 경우 404 에러 발생 --%>
	<%-- 해결법)웹자원의 경로를 절대경로로 표현하여 제공 --%>
	<img src="images/Koala.jpg" width="200">
	
	<%-- 웹자원의 경로를 절대경로로 표현하여 제공 --%>
	<%-- 절대경로 : 최상위 디렉토리를 기준으로 웹자원의 경로를 표현하는 방법 --%>
	<%-- 문제점)컨텍스트의 이름이 변경될 경우 컨텍스트 경로가 변경되어 404 에러 발생 --%>
	<%-- 해결법)컨텍스트 경로를 제공받아 웹자원의 경로를 절대경로로 표현하여 제공 --%>
	<img src="/mvc/jstl/images/Koala.jpg" width="200">
	
	<%-- request.getContextPath() 메소드를 호출하여 컨텍스트 경로를 반환받아 웹자원의 경로를 절대경로로 표현  --%>
	<img src="<%=request.getContextPath() %>/jstl/images/Koala.jpg" width="200">
	
	<%-- EL 표현식에서 pageContext 내장객체를 사용하여 컨텍스트 경로를 제공받아 웹자원의 경로를 절대경로로 표현 --%>
	<img src="${pageContext.request.contextPath}/jstl/images/Koala.jpg" width="200">
	
	<%-- url 태그 : 컨텍스트 경로가 포함된 웹자원의 절대경로를 제공하는 태그 --%>
	<%-- value 속성 : 컨텍스트 경로를 제외한 웹자원의 절대경로를 속성값으로 설정 --%>
	<img src="<c:url value="/jstl/images/Koala.jpg"/>" width="200">
</body>
</html>



main/java/xyz.itwill.mvc)
ModifyModel .java (수정)

package xyz.itwill.mvc;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import xyz.itwill.dto.UserinfoDTO;
import xyz.itwill.service.UserinfoService;

//클라이언트가 [/modify.do]로 요청한 경우 객체로 생성될 모델 역활의 클래스
//=> 회원정보를 전달받아 USERINFO 테이블에 저장된 회원정보를 변경하고 [/view.do]로 
//리다이렉트 이동하기 위한 정보가 저장된 ActionForward 객체 반환 - 아이디 전달
public class ModifyModel implements Action {

	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ActionForward actionForward=new ActionForward();
		try {
			if(request.getMethod().equals("GET")) {
				throw new Exception();
			}
			
			//request.setCharacterEncoding("utf-8");
			
			String userid=request.getParameter("userid");
			String password=request.getParameter("password");
			String name=request.getParameter("name");
			String email=request.getParameter("email");
			int status=Integer.parseInt(request.getParameter("status"));
			
			UserinfoDTO userinfo=new UserinfoDTO();
			userinfo.setUserid(userid);
			if(password==null || password.equals("")) {
				//비밀번호 전달값이 없는 경우 - 기존 회원정보의 비밀번호로 필드값 변경
				userinfo.setPassword(UserinfoService.getService().getUserinfo(userid).getPassword());
			} else {
				//비밀번호 전달값이 없는 경우 - 전달값(비밀번호)으로 필드값 변경
				userinfo.setPassword(password);
			}
			userinfo.setName(name);
			userinfo.setEmail(email);
			userinfo.setStatus(status);
			
			//UserinfoService 클래스의 modifyUserinfo() 메소드를 호출하여 회원정보 변경 처리
			UserinfoService.getService().modifyUserinfo(userinfo);
			
			actionForward.setForward(false);
			actionForward.setPath(request.getContextPath()+"/view.do?userid="+userid);
		} catch (Exception e) {
			e.printStackTrace();
			actionForward.setForward(false);
			actionForward.setPath(request.getContextPath()+"/error.do");
		}
		return actionForward;
	}

}


WriteModel .java (수정)

package xyz.itwill.mvc;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import xyz.itwill.dto.UserinfoDTO;
import xyz.itwill.exception.ExistsUserinfoException;
import xyz.itwill.service.UserinfoService;

//클라이언트가 [/write.do]로 요청한 경우 객체로 생성될 모델 역활의 클래스
// => 회원정보를 전달받아 USERINFO 테이블에 회원정보로 삽입하고 [/loginform.do]로 
//리다이렉트 이동하기 위한 정보가 저장된 ActionForward 객체 반환
public class WriteModel implements Action {

	@Override
	public ActionForward execute(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ActionForward actionForward=new ActionForward();
		UserinfoDTO userinfo=null;
		try {
			if(request.getMethod().equals("GET")) {
				throw new Exception();
			}
			
			//request.setCharacterEncoding("utf-8");
			
			String userid=request.getParameter("userid");
			String password=request.getParameter("password");
			String name=request.getParameter("name");
			String email=request.getParameter("email");
			int status=Integer.parseInt(request.getParameter("status"));
			
			userinfo=new UserinfoDTO();
			userinfo.setUserid(userid);
			userinfo.setPassword(password);
			userinfo.setName(name);
			userinfo.setEmail(email);
			userinfo.setStatus(status);
			
			//UserinfoService 클래스의 addUserinfo() 메소드를 호출하여 회원등록 처리
			// => 전달받은 아이디가 USERINFO 테이블에 저장된 기존 회원정보의 아이디와 중복될 경우
			//ExistsUserinfoException 발생
			UserinfoService.getService().addUserinfo(userinfo);
			
			actionForward.setForward(false);
			actionForward.setPath(request.getContextPath()+"/loginform.do");
		} catch (ExistsUserinfoException e) {
			//아이디가 중복된 경우 발생되는 예외에 대한 예외처리 명령 작성
			request.setAttribute("message", e.getMessage());
			request.setAttribute("userinfo", userinfo);
			actionForward.setForward(true);
			actionForward.setPath("/model_two/user_write.jsp");
		} catch (Exception e) {
			e.printStackTrace();
			actionForward.setForward(false);
			actionForward.setPath(request.getContextPath()+"/error.do");
		}
		return actionForward;
	}

}

 

 

java/mvc/src/main/webapp/jstl)
fmt_formatDate .jsp (날짜와 시간 변환태그)

<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>MVC</title>
</head>
<body>
	<h1>Formatter - 날짜와 시간 변환 태그</h1>
	<hr>
	<%-- 서버 시스템의 현재 날짜와 시간이 저장된 Date 객체를 생성하여 스코프 객체의 속성값으로 저장 --%>
	<c:set var="now" value="<%=new Date() %>"/>
	<%-- EL를 이용하여 Date 객체를 제공받아 출력 처리할 경우 toString() 메소드 자동 호출  --%>
	<p>now = ${now }</p>	
	
	<%-- formatDate 태그 : Date 객체에 저장된 날짜와 시간을 원하는 패턴의 문자열로 변환하여 제공하는 태그 --%>
	<%-- => SimpleDateFormat 클래스의 format() 메소드와 유사한 기능 제공 --%>
	<%-- value 속성 : Date 객체를 속성값으로 설정 - EL를 사용하여 Date 객체를 제공받아 속성값으로 사용 --%>
	<%-- type 속성 : date(날짜), time(시간), both(날짜와 시간) 중 하나를 속성값으로 설정 --%>
	<%-- => type 속성값을 [date]로 설정한 경우 기본적으로 [yyyy.M.d.] 패턴의 문자열로 변환되어 제공 --%>
	<p>now(날짜) = <fmt:formatDate value="${now }" type="date"/>

	<%-- dateStyle 속성 : full 또는 short 중에 하나를 속성값으로 설정 --%>
	<%-- => dateStyle 속성값이 [full]인 경우 [yyyy년 M월 d일 E요일]  패턴의 문자열로 변환되어 제공 --%>
	<%-- => dateStyle 속성값이 [short]인 경우 [yy.M.d.]  패턴의 문자열로 변환되어 제공 --%>
	<p>now(날짜) = <fmt:formatDate value="${now }" type="date" dateStyle="full"/>
	<p>now(날짜) = <fmt:formatDate value="${now }" type="date" dateStyle="short"/>

	<%-- type 속성 : date(날짜), time(시간), both(날짜와 시간) 중 하나를 속성값으로 설정 --%>
	<%-- => type 속성값을 [time]로 설정한 경우 기본적으로 [a h:mm:ss] 패턴의 문자열로 변환되어 제공 --%>	
	<p>now(시간) = <fmt:formatDate value="${now }" type="time"/>

	<%-- timeStyle 속성 : full 또는 short 중에 하나를 속성값으로 설정 --%>
	<%-- => timeStyle 속성값이 [full]인 경우 [a h시 mm분 ss초 z]  패턴의 문자열로 변환되어 제공 --%>
	<%-- => timeStyle 속성값이 [short]인 경우 [a h:mm]  패턴의 문자열로 변환되어 제공 --%>
	<p>now(시간) = <fmt:formatDate value="${now }" type="time" timeStyle="full"/>
	<p>now(시간) = <fmt:formatDate value="${now }" type="time" timeStyle="short"/>

	<%-- type 속성 : date(날짜), time(시간), both(날짜와 시간) 중 하나를 속성값으로 설정 --%>
	<%-- => type 속성값을 [both]로 설정한 경우 기본적으로 [yyyy.M.d. a h:mm:ss] 패턴의 문자열로 변환되어 제공 --%>	
	<p>now(날짜와 시간) = <fmt:formatDate value="${now }" type="both"/>
	<p>now(날짜와 시간) = <fmt:formatDate value="${now }" type="both" dateStyle="full" timeStyle="full"/>
	<p>now(날짜와 시간) = <fmt:formatDate value="${now }" type="both" dateStyle="short" timeStyle="short"/>
	
	<%-- pattern 속성 : 날짜와 시간을 변환하기 위한 패턴문자를 속성값으로 설정 --%>
	<p>now(패턴) = <fmt:formatDate value="${now }" pattern="yyyy-MM-dd HH:mm:ss"/></p>
	
	<%-- timeZone 태그 : 타임존(TimeZone)을 변경하는 태그 --%>
	<%-- value 속성 : 변경할 타임존(대륙/도시)을 속성값으로 설정 --%>
	<fmt:timeZone value="Asia/Hong_Kong">
		<p>홍콩의 현재 날짜와 시간 = <fmt:formatDate value="${now }" pattern="yyyy-MM-dd HH:mm:ss"/></p>
	</fmt:timeZone>
</body>
</html>


fmt_formatNumber .jsp  (달러/ 엔화 화폐바꾸기)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>MVC</title>
</head>
<body>
	<h1>Formatter - 숫자 변환 태그</h1>
	<hr>
	<c:set var="price" value="1000000000"/>
	<p>가격 = ${price }원</p>
	
	<%-- formatNumber 태그 : 숫자값을 원하는 패턴의 문자열로 변환하여 제공하는 태그 --%>
	<%-- => DecimalFormat 클래스의 format() 메소드와 유사한 기능 제공 --%>
	<%-- value 속성 : 숫자값을 속성값으로 설정 -  EL를 사용하여 숫자값을 제공받아 속성값으로 사용 --%>
	<%-- => 속성값으로 제공받은 값이 숫자값이 아닌 경우 NumberFormatException 발생 --%>
	<%-- type 속성 : number(숫자) 또는 currency(화폐) 중 하나를 속성값으로 설정 --%>
	<%-- => type 속성을 생략한 경우 [number] 속성값을 기본값으로 사용 --%>
	<%-- => type 속성값을 [number]로 설정한 경우 숫자 3자리마다 [,]기호를 삽입한 문자열로 변환하여 제공 --%>	
	<%-- => type 속성값을 [currency]로 설정한 경우 앞부부분에 화폐단위를 출력하고 숫자 3자리
	마다 [,]기호를 삽입한 문자열로 변환하여 제공 --%>	
	<p>가격 = <fmt:formatNumber value="${price}" type="number"/>원</p>
	<p>가격 = <fmt:formatNumber value="${price}" type="currency"/></p>
	
	<%-- setLocale : 장소를 변경하는 태그 - 나라별로 날짜와 시간 또는 화폐단위를 변경  --%>
	<%-- value 속성 : 장소(언어_나라)를 속성값으로 설정 --%>
	<fmt:setLocale value="en_us"/>
	<p>가격 = <fmt:formatNumber value="${price}" type="currency"/></p>

	<fmt:setLocale value="ja_jp"/>
	<p>가격 = <fmt:formatNumber value="${price}" type="currency"/></p>
	
	<fmt:setLocale value="ko_kr"/>
	<p>가격 = <fmt:formatNumber value="${price}" type="currency"/></p>
	
	<c:set var="pi" value="3.141592"/>
	<p>원주율 = ${pi }</p>
	<%-- pattern 속성 : 숫자값을 변환하기 위한 패턴정보를 속성값으로 설정 --%>
	<%-- => 반올림하여 원하는 소숫점 자릿수만큼 출력 처리 --%>
	<p>원주율 = <fmt:formatNumber value="${pi } " pattern="#.##"/></p>
	<p>원주율 = <fmt:formatNumber value="${pi } " pattern="#.###"/></p>
	
	<c:set var="avg" value="70.5"/>
	<%-- [#] 패턴문자를 사용하면 소숫점 자릿수의 값이 없으면 공백으로 표현 --%>
	<p>평균 = <fmt:formatNumber value="${avg } " pattern="#.##"/></p>
	<%-- [0] 패턴문자를 사용하면 소숫점 자릿수의 값이 없어도 0으로 표현 --%>
	<p>평균 = <fmt:formatNumber value="${avg } " pattern="##.00"/></p>
	<%-- [#] 패턴문자과 [0] 패턴문자를 소숫점 자릿수로 동시에 표현하면 에러 발생 --%>
	<%-- <p>평균 = <fmt:formatNumber value="${avg } " pattern="##.#0"/></p> --%>
</body>
</html>



functions .jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%-- Functions 태그 라이브러리를 JSP 문서에 포함  - 접두사로 [fn] 사용 --%>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>MVC</title>
</head>
<body>
	<h1>Functions - EL 함수</h1>
	<hr>
	<c:set var="phone" value="010-1234-5678"/>
	<p>전화번호 = ${phone }</p>
	<hr>
	
	<%-- split 함수 : 매개변수로 전달받은 문자열을 구분자로 분리하여 배열로 반환하는 함수 --%>	
	<c:set var="array" value="${fn:split(phone, '-') }"/>
	<c:forEach var="num" items="${array }">
		<div>${num }</div>
	</c:forEach>
	<hr>
	
	<%-- substring 함수 : 매개변수로 전달받은 문자열을 시작첨자(첨자 위치의 문자 포함)와 
	종료첨자(첨자 위치의 문자 미포함)로 분리하여 반환하는 함수 --%>
	<div>${fn:substring(phone, 0, 3) }</div>
	<div>${fn:substring(phone, 4, 8) }</div>
	<div>${fn:substring(phone, 9, 13) }</div>
	<hr>

	<c:set var="content" value="안녕하세요.\n반갑습니다."/>
	<div>${content }</div>
	<%-- replace 함수 : 매개변수로 전달받은 문자열에서 검색 문자열을 찾아 치환 문자열로
	변환하여 반환하는 함수 --%>	
	<div>${fn:replace(content, '\\n', '<br>')}</div>	
	<hr>
	
	<c:set var="html" value="<font size='7' color='red'>안녕하세요.</font>"/>
	<%-- EL 표현식으로 HTML 태그가 포함된 문자열을 스코프 객체 속성값으로 제공받아 출력하면
	HTML 태그를 태그로 인식하여 출력 처리 --%>
	<div>${html }</div>
	
	<%-- out 태그를 사용하여 HTML 태그가 포함된 문자열을 스코프 객체 속성값으로 제공받아 
	출력하면 HTML 태그를 문자값으로 인식하여 출력 처리 - XSS 공격에 대한 방어법 --%>
	<div><c:out value="${html }"/></div>
	
	<%-- escapeXml 함수를 사용하여 HTML 태그가 포함된 문자열을 스코프 객체 속성값으로 제공받아 
	출력하면 HTML 태그를 문자값으로 인식하여 출력 처리 - XSS 공격에 대한 방어법 --%>
	<div>${fn:escapeXml(html) }</div>
</body>
</html>

 





src/main>webapp>model_two)
user_login .jsp (수정)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    
<%-- 비로그인 상태의 사용자인 경우 - 사용자로부터 로그인정보를 입력받기 위한 JSP 문서 --%>
<%-- => [로그인] 태그를 클릭한 경우 [/login.do] 페이지 요청 - 입력값 전달 --%>
<%-- 로그인 상태의 사용자인 경우 - 환영메세지를 클라이언트에게 전달하여 응답하는 JSP 문서 --%>
<%-- => [회원목록] 태그를 클릭한 경우 [/list.do] 페이지 요청 --%>
<%-- => [로그아웃] 태그를 클릭한 경우 [/logout.do] 페이지 요청 --%>
<%-- => [회원등록] 태그를 클릭한 경우 [/writeform.do] 페이지 요청 - 관리자에게만 링크 제공 --%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>MVC</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<%-- 요청 서블릿(컨트롤러)의 URL 주소 경로와 응답하는 JSP 문서의 경로가 서로 다르므로
웹자원의 경로는 절대경로로 표현하는 것을 권장 --%>
<%-- <link rel=stylesheet href="<%=request.getContextPath() %>/model_two/css/user.css" type="text/css"> --%>
<%-- <link rel=stylesheet href="${pageContext.request.contextPath}/model_two/css/user.css" type="text/css"> --%>
<link rel=stylesheet href="<c:url value="/model_two/css/user.css"/>" type="text/css">
<script language="JavaScript">
function userLogin() {
	if ( f.userid.value == "" ) {
		alert("아이디를 입력하십시요.");
		f.userid.focus();
		return;
	} 
	if ( f.password.value == "" ) {
		alert("비밀번호를 입력하십시요.");
		f.password.focus();
		return;
	}	
	
	f.action = "<c:url value="/login.do"/>";
	f.submit();
}
</script>
</head>
<body bgcolor=#FFFFFF text=#000000 leftmargin=0 topmargin=0 marginwidth=0 marginheight=0>
<br>
<table width=780 border=0 cellpadding=0 cellspacing=0>
	<tr>
	  <td width="20"></td>
	  <td style="color: red;">${message }</td>			
	</tr>

	<tr>
	  <td width="20"></td>
	  <td>
  	  <!--contents-->
	  <table width=590 border=0 cellpadding=0 cellspacing=0>
		  <tr>
			<td bgcolor="f4f4f4" height="22">&nbsp;&nbsp;<b>회원관리 - 로그인</b></td>
		  </tr>
	  </table>  
	  <br>
	  
	  
	  <c:choose>  
		<%-- //비로그인 상태의 사용자인 경우 --%>
		<c:when test="${empty(loginUserinfo) }">   	
		  <!-- login Form  --> 
		  <form name="f" method="post">
		  <table border="0" cellpadding="0" cellspacing="1" width="590" bgcolor="BBBBBB">
			  <tr>
				<td width=100 align=center bgcolor="E6ECDE" height="22">사용자 아이디</td>
				<td width=490 bgcolor="ffffff" style="padding-left:10px;">
					<input type="text" style="width:150" name="userid" value="${userid }">
				</td>
			  </tr>
			  <tr>
				<td width=100 align=center bgcolor="E6ECDE" height="22">비밀번호</td>
				<td width=490 bgcolor="ffffff" style="padding-left:10px;">
					<input type="password" style="width:150" name="password">
				</td>
			  </tr>
		  </table>
		  </form>
		  <br>
		  
		  <table width=590 border=0 cellpadding=0 cellspacing=0>
			  <tr>
				<td align=center>
					<input type="button" value="로그인" onClick="userLogin();"> &nbsp;
				</td>
			  </tr>
		  </table>
	  	</c:when>
	  	<c:otherwise><%-- 로그인 상태의 사용자인 경우 --%>

		  <table border="0" cellpadding="0" cellspacing="1" width="590" bgcolor="BBBBBB">
			  <tr>
				<td align=center bgcolor="E6ECDE" height="22">
					${loginUserinfo.name}님, 환영합니다.
				</td>
			  </tr>
		  </table>
		  <br>
		  
		  <table width=590 border=0 cellpadding=0 cellspacing=0>
			  <tr>
				<td align=center>
					<button type="button" onclick="location.href='<c:url value="/list.do"/>';">회원목록</button>
					<button type="button" onclick="location.href='<c:url value="/logout.do"/>';">로그아웃</button>
					<c:if test="${loginUserinfo.status == 9 }">
						<button type="button" onclick="location.href='<c:url value="/writeform.do"/>';">회원등록</button>
					</c:if>
				</td>
			  </tr>
		  </table>
		</c:otherwise>
	  </c:choose>
	  </td>
	</tr>
</table>  

</body>
</html>

 


user_list.jsp (수정)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>    
<%-- request 객체의 속성값으로 저장된 회원목록을 반환받아 클라이언트에게 전달하여 응답하는 JSP 문서 --%>
<%-- => 회원정보에서 [회원이름] 태그를 클릭한 경우 [view.do] 페이지 요청 - 아이디 전달 --%>
<%-- => [회원등록] 태그를 클릭한 경우 [writeform.do] 페이지 요청 - 관리자에게만 링크 제공 --%>
<%-- => [로그아웃] 태그를 클릭한 경우 [logout.do] 페이지 요청 --%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>MVC</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel=stylesheet href="<c:url value="/model_two/css/user.css"/>" type="text/css">
</head>
<body bgcolor=#FFFFFF text=#000000 leftmargin=0 topmargin=0 marginwidth=0 marginheight=0>
<br>
<table width=780 border=0 cellpadding=0 cellspacing=0>
<tr>
	<td width="20"></td>
	<td>
	  	<table width=590 border=0 cellpadding=0 cellspacing=0>
		  	<tr>
				<td bgcolor="f4f4f4" height="22">&nbsp;&nbsp;<b>회원관리 - 회원목록</b></td>
		  	</tr>
	  	</table>  
	  	<br>
	  
	  	<table border="0" cellpadding="0" cellspacing="1" width="590" bgcolor="BBBBBB">
		  	<tr>
				<td width=190 align=center bgcolor="E6ECDE" height="22">아이디</td>
				<td width=200 align=center bgcolor="E6ECDE">이름</td>
				<td width=200 align=center bgcolor="E6ECDE">이메일</td>
		  	</tr>
		  	
			<c:forEach var="userinfo" items="${userinfoList }">
			  	<tr>
					<td width=190 align=center bgcolor="ffffff" height="20">
						${userinfo.userid }
					</td>
					<td width=200 align=center bgcolor="ffffff">
						<a href="<c:url value="/view.do"/>?userid=${userinfo.userid}" class="user">
							${userinfo.name }
						</a>
					</td>
					<td width=200 align=center bgcolor="ffffff">
						${userinfo.email }
					</td>
			  	</tr>
		  	</c:forEach>
	  	</table>

		<br>
	  	<table border="0" cellpadding="0" cellspacing="1" width="590">
			<tr>
				<td align="right">
					<c:if test="${loginUserinfo.status == 9 }">
						<input type="button" value="회원등록" onclick="location.href='<c:url value="/writeform.do"/>';"/>
					</c:if>	
					<input type="button" value="로그아웃" onclick="location.href='<c:url value="/logout.do"/>';"/>
				</td>
			</tr>
		</table>		
	</td>
</tr>
</table>  
</body>
</html>

 


user_modify.jsp (수정)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>    
<%-- request 객체의 속성값으로 저장된 회원정보를 반환받아 입력태그의 초기값으로 설정한 후 
사용자로부터 변경값을 입력받기 위한 JSP 문서 --%>
<%-- => [수정] 태그를 클릭한 경우 [modify.do] 페이지 요청 - 입력값(회원정보) 전달 --%>
<%-- => [목록] 태그를 클릭한 경우 [list.do] 페이지 요청 --%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>MVC</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel=stylesheet href="<c:url value="/model_two/css/user.css"/>" type="text/css">
<script language="JavaScript">
function userModify() {
	if ( f.name.value == "" ) {
		alert("이름을 입력하십시요.");
		f.name.focus();
		return false;
	}
	f.action = "<c:url value="/modify.do"/>";
	f.submit();
}
</script>
</head>
<body bgcolor=#FFFFFF text=#000000 leftmargin=0 topmargin=0 marginwidth=0 marginheight=0>
<br>
<table width=780 border=0 cellpadding=0 cellspacing=0>
	<tr>
	  <td width="20"></td>
	  <td>
	  <table width=590 border=0 cellpadding=0 cellspacing=0>
		  <tr>
			<td bgcolor="f4f4f4" height="22">&nbsp;&nbsp;<b>회원관리 - 회원정보수정</b></td>
		  </tr>
	  </table>  
	  <br>
	  
	  <form name="f" method="post">
	  <input type="hidden" name="userid" value="${userinfo.userid }">
	  <table border="0" cellpadding="0" cellspacing="1" width="590" bgcolor="BBBBBB">
		  <tr>
			<td width=100 align=center bgcolor="E6ECDE" height="22">아이디</td>
			<td width=490 bgcolor="ffffff" style="padding-left:10px;">
				${userinfo.userid }
			</td>
		  </tr>
		  <tr>
			<td width=100 align=center bgcolor="E6ECDE" height="22">비밀번호</td>
			<td width=490 bgcolor="ffffff" style="padding-left:10px;">
				<input type="password" style="width:150" name="password">
				<span style="color: red;">** 비밀번호를 변경하지 않을 경우 입력하지 마세요.</span>
			</td>
		  </tr>
		  <tr>
			<td width=100 align=center bgcolor="E6ECDE" height="22">이름</td>
			<td width=490 bgcolor="ffffff" style="padding-left:10px;">
				<input type="text" style="width:240" name="name" value="${userinfo.name }">
			</td>
		  </tr>
		  <tr>
			<td width=100 align=center bgcolor="E6ECDE" height="22">이메일 주소</td>
			<td width=490 bgcolor="ffffff" style="padding-left:10px;">
				<input type="text" style="width:240" name="email" value="${userinfo.email }">
			</td>
		  </tr>		  
		  <tr>
			<td width=100 align=center bgcolor="E6ECDE" height="22">회원등급</td>
			<td width=490 bgcolor="ffffff" style="padding-left:10px;">
				<select name="status">
					<option value="1" <c:if test="${userinfo.status == 1 }">selected</c:if>>일반회원</option>
					<option value="9" <c:if test="${userinfo.status == 9 }">selected</c:if>>관리자</option>
				</select>
			</td>
		  </tr>	
	  </table>
	  </form>
	  <br>
	  
	  <table width=590 border=0 cellpadding=0 cellspacing=0>
		  <tr>
			<td align=center>
			<input type="button" value="수정" onClick="userModify();">
			<input type="button" value="목록" onClick="location.href='<c:url value="/list.do"/>';">
			</td>
		  </tr>
	  </table>

	  </td>
	</tr>
</table>  

</body>
</html>


user_view.jsp (수정)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>    
<%-- request 객체의 속성값으로 저장된 회원정보를 반환받아 클라이언트에게 전달하여 응답하는 JSP 문서 --%>
<%-- => [수정] 태그를 클릭한 경우 [modifyform.do] 페이지 요청 - 아이디 전달 --%>
<%-- => [삭제] 태그를 클릭한 경우 [remove.do] 페이지 요청 - 아이디 전달 --%>
<%-- => [목록] 태그를 클릭한 경우 [list.do] 페이지 요청 --%>
<%-- => [수정] 태그와 [삭제] 태그는 관리자에게만 링크 제공 --%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>MVC</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel=stylesheet href="<c:url value="/model_two/css/user.css"/>" type="text/css">
<script language="JavaScript">
function userRemove(userid) {
	if (confirm("정말로 삭제 하시겠습니까?") ) {
		location.href='<c:url value="/remove.do"/>?userid='+userid;
	}
}
</script>
</head>
<body bgcolor=#FFFFFF text=#000000 leftmargin=0 topmargin=0 marginwidth=0 marginheight=0>
<br>
<table width=780 border=0 cellpadding=0 cellspacing=0>
	<tr>
	  <td width="20"></td>
	  <td>
	  <table width=590 border=0 cellpadding=0 cellspacing=0>
		  <tr>
			<td bgcolor="f4f4f4" height="22">&nbsp;&nbsp;<b>회원관리 - 회원정보</b></td>
		  </tr>
	  </table>  
	  <br>
	  
	  <table border="0" cellpadding="0" cellspacing="1" width="590" bgcolor="BBBBBB">
		  <tr>
			<td width=100 align=center bgcolor="E6ECDE" height="22">아이디</td>
			<td width=490 bgcolor="ffffff"  style="padding-left:10px;">
				${userinfo.userid}
			</td>
		  </tr>
		  <tr>
			<td width=100 align=center bgcolor="E6ECDE" height="22">이름</td>
			<td width=490 bgcolor="ffffff"  style="padding-left:10px;">
				${userinfo.name}
			</td>
		  </tr>
		  <tr>
			<td width=100 align=center bgcolor="E6ECDE" height="22">이메일</td>
			<td width=490 bgcolor="ffffff"  style="padding-left:10px;">
				${userinfo.email}
			</td>
		  </tr>		  
	  </table>
	  <br>
	  
	  <table width=590 border=0 cellpadding=0 cellspacing=0>
		  <tr>
			<td align=center>
			<c:if test="${loginUserinfo.status == 9 }">
				<input type="button" value="수정" onClick="location.href='<c:url value="/modifyform.do"/>?userid=${userinfo.userid}';">
				<input type="button" value="삭제" onClick="userRemove('${userinfo.userid}');">
			</c:if>
			<input type="button" value="목록" onClick="location.href='<c:url value="/list.do"/>';"> 
			</td>
		  </tr>
	  </table>

	  </td>
	</tr>
</table>  
</body>
</html>