필터 생성시 인터페이스 상속받음
서블릿 필터
package 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;
public class FilterEx01 implements Filter {
@Override
public void destroy() {
// 클래스 메모리 제거시 호출
System.out.println("destory()");
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException {
//request 처리
System.out.println("전처리 부분");
arg2.doFilter(arg0, arg1);
//response 처리
System.out.println("후처리부분");
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// 클래스 생성시 자동 호출
System.out.println("init()");
}
}
필터 등록
<?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" id="WebApp_ID" version="3.1">
<display-name>FilterEx01</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 필터 web.xml 등록 -->
<filter>
<filter-name>FirstFilter</filter-name>
<filter-class>filter.FilterEx01</filter-class>
</filter>
<filter-mapping>
<filter-name>FirstFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
</web-app>
test.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
System.out.println("Hello Filter");
out.println("Hello Filter");
%>
2. 필터가 여러개
filterEx01
package 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;
public class FilterEx01 implements Filter {
@Override
public void destroy() {
// 클래스 메모리 제거시 호출
System.out.println("destory1()");
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException {
//request 처리
System.out.println("전처리 부분1");
arg2.doFilter(arg0, arg1);
//response 처리
System.out.println("후처리부분1");
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// 클래스 생성시 자동 호출
System.out.println("init1()");
}
}
filterEx01
package 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;
public class FilterEx02 implements Filter {
@Override
public void destroy() {
// 클래스 메모리 제거시 호출
System.out.println("destory2()");
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException {
//request 처리
System.out.println("전처리 부분2");
arg2.doFilter(arg0, arg1);
//response 처리
System.out.println("후처리부분2");
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// 클래스 생성시 자동 호출
System.out.println("init2()");
}
}
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_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>FilterEx01</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 필터 등록 -->
<!-- FilterEx02 2번을 먼저 등록함 //web.xml에 등록한 순서로 필터가 체인식으로 적용됨 -->
<filter>
<filter-name>FirstFilter</filter-name>
<filter-class>filter.FilterEx02</filter-class>
</filter>
<filter-mapping>
<filter-name>FirstFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
<!-- 필터 등록 -->
<filter>
<filter-name>SecondFilter</filter-name>
<filter-class>filter.FilterEx01</filter-class>
</filter>
<filter-mapping>
<filter-name>SecondFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
</web-app>
test.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
System.out.println("Hello Filter");
out.println("Hello Filter");
%>
3.필터 초기값 전처리
package 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;
public class FilterEx01 implements Filter {
private String id;
private String password;
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException {
//실행순서 2
//필터 전처리
arg0.setAttribute("id", "전처리된 아이디 "+id);
arg0.setAttribute("password", "전처리된 비밀번호 "+password);
arg2.doFilter(arg0, arg1);
//실행순서 4
System.out.println((String)arg0.getAttribute("id"));
System.out.println((String)arg0.getAttribute("password"));
}
@Override
public void init(FilterConfig arg0) throws ServletException {
//실행순서 1
//web.xml 설정된 초기데이터 읽어오기
id = arg0.getInitParameter("id");
password = arg0.getInitParameter("password");
System.out.println("읽어온 아이디 : "+ id);
System.out.println("읽어온 비밀번호 : "+ password);
}
}
<?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" id="WebApp_ID" version="3.1">
<display-name>FilterEx02</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 필터 등록, 초기값 세팅 -->
<filter>
<filter-name>filter</filter-name>
<filter-class>filter.FilterEx01</filter-class>
<init-param>
<param-name>id</param-name>
<param-value>scott</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>tiger</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>filter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
</web-app>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
//실행순서 3
String id = (String)request.getAttribute("id");
String password = (String)request.getAttribute("password");
request.setAttribute("id", "리턴된 "+ id);
request.setAttribute("password", "리턴된 "+ password);
%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%= id + " / " +password %>
</body>
</html>
init1(), init2()은 다른 프로젝트 폴더에 있는 필터 클래스 이지만 톰캣이 전체 프로젝트를 실행함으로 호출이됨
4. dispatcher
package filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class FilterEx01 implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException {
//결과를 없애고 새로운 방향으로 바꿈
//test.jsp ▶ error.jsp
RequestDispatcher dispatcher = arg0.getRequestDispatcher("error.jsp");
dispatcher.forward(arg0, arg1);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
<?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" id="WebApp_ID" version="3.1">
<display-name>FilterEx03</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 필터 등록, 초기값 세팅 -->
<filter>
<filter-name>filter</filter-name>
<filter-class>filter.FilterEx01</filter-class>
</filter>
<filter-mapping>
<filter-name>filter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>
</web-app>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
난 test.jsp
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
난 error.jsp
</body>
</html>
5. 필터의 활용: 모든페이지에 한글 인코딩 적용
form.htm
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<center>
<form name="data_form" method="post" action="Servlet_01">
이름: <input type="text" name="name" /><br>
전번: <input type="text" name="tel" /><br>
주소: <input type="text" name="addr" /><br>
<input type="submit" value="전송" />
</form>
</center>
</body>
</html>
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;
public class ServletEx01 extends HttpServlet {
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
String tel = request.getParameter("tel");
String addr = request.getParameter("addr");
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<style type='text/css'>");
out.println(".n_border {border:none}");
out.println("</style>");
out.println("</head>");
out.println("<body>");
out.println(" <center>");
out.println(" 전송된 이름 =");
out.println(" <input type='text' class='n_border' value='"+name +"'/><br>");
out.println(" 전송된 전번 =");
out.println(" <input type='text' class='n_border' value='"+tel +"'/><br>");
out.println(" 전송된 주소 =");
out.println(" <input type='text' class='n_border' value='"+addr +"'/><br>");
out.println(" </center>");
out.println("</body>");
out.println("</html>");
}
@Override
public void destroy() { }
@Override
public void init() { }
}
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;
import javax.servlet.http.HttpServletRequest;
public class FilterEx01 implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest h_request = (HttpServletRequest)request;
String method = h_request.getMethod();
if(method.equalsIgnoreCase("POST")){
request.setCharacterEncoding("utf-8");
}
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
<?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" id="WebApp_ID" version="3.1">
<display-name>FilterEx00</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 서블릿 등록 -->
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>ServletEx01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/Servlet_01</url-pattern>
</servlet-mapping>
<!-- 필터 등록 -->
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>FilterEx01</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/Servlet_01</url-pattern>
</filter-mapping>
</web-app>
6.Listener
클래스를 만들때 인터페이스 상속
package listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ListenerEx01 implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent arg0) {
//웹 컨테이너가 끝났을 때 실행
System.out.println("contextDestroyed 호출");
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
//웹 컨테이너가 시작시
System.out.println("contextInitialized 호출");
}
}
<?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" id="WebApp_ID" version="3.1">
<display-name>ListenerEx01</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>listener.ListenerEx01</listener-class>
</listener>
</web-app>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
test.jsp context 리스너
</body>
</html>
package listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ListenerEx01 implements ServletContextListener {
@Override
public void contextDestroyed(ServletContextEvent arg0) {
//웹 컨테이너가 끝났을 때 실행
System.out.println("contextDestroyed 호출");
}
//context 내용 변화
@Override
public void contextInitialized(ServletContextEvent arg0) {
//웹 컨테이너가 시작시
System.out.println("contextInitialized 호출");
}
}
7.attribute listener 속성값이 변할때 마다 호출
listener
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class Servlet_Listener implements ServletContextListener, ServletContextAttributeListener {
@Override
public void attributeAdded(ServletContextAttributeEvent arg0) {
// TODO Auto-generated method stub
System.out.println("Context 영역에 값이 추가 되었습니다.");
System.out.println("added = " +arg0.getName()+" : " + arg0.getValue());
}
@Override
public void attributeRemoved(ServletContextAttributeEvent arg0) {
// TODO Auto-generated method stub
System.out.println("Context 영역에 값이 삭제 되었습니다.");
System.out.println("removed = " +arg0.getName()+" : " + arg0.getValue());
}
@Override
public void attributeReplaced(ServletContextAttributeEvent arg0) {
// TODO Auto-generated method stub
System.out.println("Context 영역에 값이 변경 되었습니다.");
System.out.println("replaced = " +arg0.getName()+" : " + arg0.getValue());
}
@Override
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
System.out.println("ServletContext 가 소멸 되었습니다.");
System.out.println("destroy context = " +arg0.getServletContext());
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
// TODO Auto-generated method stub
System.out.println("ServletContext 가 초기화 되었습니다.");
System.out.println("init context = " +arg0.getServletContext());
}
}
servlet
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletEx01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
out.println("<html><body><center>");
out.println("<form method='post'>");
out.println("<input type='submit' value='Context 값 할당하기' />");
out.println("</form>");
out.println("</center></body></html>");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
context.setAttribute("my_name", "김승현");
context.setAttribute("my_name", "승현");
context.removeAttribute("my_name");
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
out.println("<html><body><center>");
out.println("Context 값 추가, 변경, 삭제 성공!");
out.println("</center></body></html>");
}
}
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_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>ListenerEx02</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 리스너 등록 -->
<listener>
<listener-class>Servlet_Listener</listener-class>
</listener>
<!-- 서블릿 등록 -->
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>ServletEx01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/ServletEx01</url-pattern>
</servlet-mapping>
</web-app>
8.model2
package servlet;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ControllerEx01
*/
@WebServlet("/controller")
public class ControllerEx01 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doProcess(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doProcess(request, response);
}
protected void doProcess(HttpServletRequest request, HttpServletResponse response) {
//메서드 안에서 예외 처리를 해줘서 에러메시지 볼수 있도록 함
//뒤에 붙은 값에 따라서 서로다른 웹페이지로 이동
//http://localhost/ParameterEx01/controller
//http://localhost/ParameterEx01/controller?action=view1 → view1.jsp
//http://localhost/ParameterEx01/controller?action=view2 → view2.jsp
try {
request.setCharacterEncoding("utf-8");
String action = request.getParameter("action");
String url = "";
if(action == null || action.equals("view1")){
url = "view1.jsp";
}else if(action.equals("view2")){
url = "view2.jsp";
}
if(!url.equals("")){
//와 비슷함 출력을 바꿔서 보여줌
//서블릿에서 각각다른 JSP페이지를 봄
RequestDispatcher dispatcher = request.getRequestDispatcher(url);
dispatcher.forward(request, response);
}
} catch (UnsupportedEncodingException e) {
System.out.println("에러 : "+ e.getMessage());
} catch (ServletException e) {
System.out.println("에러 : "+ e.getMessage());
} catch (IOException e) {
System.out.println("에러 : "+ e.getMessage());
}
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
난 view1.jsp
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
난 view2.jsp
</body>
</html>
9. controller에서 model 접속후 view 띄우기
package servlet;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.view1Model;
@WebServlet("/controller")
public class ControllerEx01 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doProcess(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doProcess(request, response);
}
protected void doProcess(HttpServletRequest request, HttpServletResponse response) {
//메서드 안에서 예외 처리를 해줘서 에러메시지 볼수 있도록 함
//뒤에 붙은 값에 따라서 서로다른 웹페이지로 이동
//http://localhost/ParameterEx01/controller
//http://localhost/ParameterEx01/controller?action=view1 → view1.jsp
//http://localhost/ParameterEx01/controller?action=view2 → view2.jsp
try {
request.setCharacterEncoding("utf-8");
String action = request.getParameter("action");
String url = "";
if(action == null || action.equals("view1")){
//Model 호출
view1Model viewModel = new view1Model();
viewModel.execute(request, response);
//View 호출 //JSP페이지를 직접 접속하지 못하게 WEB-INF 폴더에 넣어둠
url = "/WEB-INF/view1.jsp";
}else if(action.equals("view2")){
view1Model viewModel = new view1Model();
viewModel.execute(request, response);
url = "/WEB-INF/view2.jsp";
}
if(!url.equals("")){
//와 비슷함 출력을 바꿔서 보여줌
//서블릿에서 각각다른 JSP페이지를 봄
RequestDispatcher dispatcher = request.getRequestDispatcher(url);
dispatcher.forward(request, response);
}
} catch (UnsupportedEncodingException e) {
System.out.println("에러 : "+ e.getMessage());
} catch (ServletException e) {
System.out.println("에러 : "+ e.getMessage());
} catch (IOException e) {
System.out.println("에러 : "+ e.getMessage());
}
}
}
package model;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class view1Model {
public void execute(HttpServletRequest request, HttpServletResponse response){
System.out.println("View1Model 호출");
}
}
package model;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class view2Model {
public void execute(HttpServletRequest request, HttpServletResponse response){
System.out.println("View2Model 호출");
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
난 view1.jsp
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
난 view2.jsp
</body>
</html>
10.controller, model, view 간의 데이터 공유
form
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- controller로 데이터 보냄 -->
<form action='./controller' method='post'>
<input type='hidden' name='action' value='view1' />
아이디 : <input type='text' name='id' />
패스워드 : <input type='text' name='password' />
<input type='submit' value='전송' />
</form>
</body>
</html>
controller
package servlet;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.ViewModel;
import model.view1Model;
@WebServlet("/controller")
public class ControllerEx01 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doProcess(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doProcess(request, response);
}
protected void doProcess(HttpServletRequest request, HttpServletResponse response) {
//메서드 안에서 예외 처리를 해줘서 에러메시지 볼수 있도록 함
//뒤에 붙은 값에 따라서 서로다른 웹페이지로 이동
//http://localhost/ParameterEx01/controller
//http://localhost/ParameterEx01/controller?action=view1 → view1.jsp
//http://localhost/ParameterEx01/controller?action=view2 → view2.jsp
try {
request.setCharacterEncoding("utf-8");
String action = request.getParameter("action");
String url = "";
//인터페이스 참조변수
ViewModel viewModel =null;
if(action == null || action.equals("view1")){
//Model 호출
viewModel = new view1Model();
viewModel.execute(request, response);
//View 호출 //JSP페이지를 직접 접속하지 못하게 WEB-INF 폴더에 넣어둠
url = "/WEB-INF/view1.jsp";
}else if(action.equals("view2")){
viewModel = new view1Model();
viewModel.execute(request, response);
url = "/WEB-INF/view2.jsp";
}
if(!url.equals("")){
//와 비슷함 출력을 바꿔서 보여줌
//서블릿에서 각각다른 JSP페이지를 봄
RequestDispatcher dispatcher = request.getRequestDispatcher(url);
dispatcher.forward(request, response);
}
} catch (UnsupportedEncodingException e) {
System.out.println("에러 : "+ e.getMessage());
} catch (ServletException e) {
System.out.println("에러 : "+ e.getMessage());
} catch (IOException e) {
System.out.println("에러 : "+ e.getMessage());
}
}
}
model_interface
package model;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//Model 1, 2가 같은매서드를 사용함으로 인터페이스로 합침
public interface ViewModel {
public abstract void execute(HttpServletRequest request, HttpServletResponse response);
}
model1
package model;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class view1Model implements ViewModel {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) {
System.out.println("View1Model 호출");
//controller에서 model로 넘어온 데이터 받음
System.out.println("id :" + request.getParameter("id"));
System.out.println("password :" + request.getParameter("password"));
//model에서 view로 데이터 보낼때
request.setAttribute("url", "View1Model");
}
}
model2
package model;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class view2Model implements ViewModel {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) {
System.out.println("View1Model 호출");
}
}
view1
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
난 view1.jsp<br>
<!-- controller에서 view로 넘어온 데이터 받음 -->
<%=request.getParameter("id") %><br>
<%=request.getParameter("password") %><br>
<!-- model에서 넘어온 데이터 받음 -->
<%=request.getAttribute("url") %><br>
${url }
</body>
</html>
view2
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
난 view2.jsp
</body>
</html>
11.요청url 따라서 다른 url경로의 view페이지 전송
package servlet;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("*.do")
public class ControllerEx01 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doProcess(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doProcess(request, response);
}
protected void doProcess(HttpServletRequest request, HttpServletResponse response) {
//http://localhost/URLEx01/view1.do → view1.jsp
//http://localhost/URLEx01/view2.do → view2.jsp
//System.out.println(request.getRequestURI());
//System.out.println(request.getContextPath());
try {
request.setCharacterEncoding("utf-8");
String path = request.getRequestURI().replaceAll(request.getContextPath(), "");
String url = "";
if(path.equals("/view1.do")){
url= "/WEB-INF/view1.jsp";
}else if(path.equals("/view2.do")){
url= "/WEB-INF/view2.jsp";
}
if(!url.equals("")){
RequestDispatcher dispatcher = request.getRequestDispatcher(url);
dispatcher.forward(request, response);
}
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
view1
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
난 view1.jsp
</body>
</html>
view2
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="ko">
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
난 view2.jsp
</body>
</html>
댓글 없음:
댓글 쓰기