[새싹] 현대IT&E 231114 기록 - JSP / Servlet

최정윤·2023년 11월 14일
0

새싹

목록 보기
21/67
post-thumbnail
post-custom-banner

post: 길이 제한이 없다.

JSP 표준 Action

  • JSP 표준 Action 종류
    • <jsp:include>
    • <jsp:forward>
    • <jsp:param>
    • <jsp:useBean>
    • <jsp:setProperty>
    • <jsp:getProperty>

코드 실습

include/main.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
#top{
	height: 150px;
	background-color: yellow;
}

#menu{
	width:250px; 
	background-color:red; 
	height:450px;
}

#content{
	background-color:green;
}
</style>
</head>
<body style="margin: 0;">
<%
String msg = "안녕하세요~";
%>
<table style="width: 1180px">
<tr>
	<td id="top" colspan="2"><%@include file="top.jsp"%></td>
</tr>
<tr>
	<td id="menu"><%@include file="menu.jsp"%></td>
	<td id="content"><%@include file="content.jsp"%></td>
</tr>
</table>
</body>
</html>

include/top.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>top</h1>
<%=msg %>
</body>
</html>

include/menu.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>menu</h1>
</body>
</html>

include/content.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>content</h1>
<%=msg %>
</body>
</html>

action/main.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
#top{
	height: 150px;
	background-color: yellow;
}

#menu{
	width:250px; 
	background-color:red; 
	height:450px;
}

#content{
	background-color:green;
}
</style>
</head>
<body style="margin: 0;">
<%
String msg = "안녕하세요~";
%>
<table style="width: 1180px">
<tr>
	<td id="top" colspan="2">
		<jsp:include page="top.jsp">
			<jsp:param value="<%=msg %>" name="msg"/>
		</jsp:include>
	</td>
</tr>
<tr>
	<td id="menu">
		<jsp:include page="menu.jsp"/>
	</td>
	<td id="content">
		<jsp:include page="content.jsp"/>
	</td>
</tr>
</table>
</body>
</html>

action/top.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>top</h1>
<%
	String msg = request.getParameter("msg");
	out.println(msg);
%>
</body>
</html>

action/menu.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>menu</h1>
</body>
</html>

action/content.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>content</h1>
</body>
</html>

forward와 redirect

  • Forward
    • Reauest 객체 재사용
    • 조금 빠르다.
    • 상단URL이바꾸지않음
    • 컨테이너 안에서 forward 해 석을 하므로서 forward한 곳 으 자원을 이용하여 응답을 만들어 보내게 됨, 결국 URL 이바뀌지않게됨
  • Redirect
    • Request 객체 새로 생성
    • 조금 느리다.
    • 상단URL이바뀜
    • 클라이언트에서 서버로 요청 을 보내면 서버는 HTTP Protocol 응답헤더 location 에 Redirection 될 곳의 주소 를넣어서 응답을보냄.클 라이언트는 Location 값을 읽 어 다시 그쪽으로 요청을 보 냄, URL주소도 당연히 바뀜

자바빈즈란?

  • Builder Tool에서 시각적으로 조작할 수 있는 재사용 가능한, 자바로 작성된 소프트웨어 컴포넌트
  • 현재 실행되고 있는 JVM 프로세스 내에서 실행되고 있는 인스턴스이며 이 중 어떤 인스턴스들은 필요에 따라 내가 호출하여 사용할 수 있음
  • 자바로 작성한 자바 클래스 중에 바 빈즈 컨벤션(Java Beans Convention) 에 맞게 작성된 클래스를 JSP에서 사용 가능
  • EJB(Enterprise Java Beans)와는 다른 것
    https://velog.io/@imok-_/%EC%9E%90%EB%B0%94-%EB%B9%88%EC%A6%88Java-Beans%EB%9E%80

인코딩하기

파일에서 인코딩하기

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>cjyweb01</display-name>
  <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>
  
<!--   <filter>
  	<filter-name>character encoding</filter-name>
  	<filter-class>org.apache.catalina.filters.SetCharacterEncodingFilter</filter-class>
  	<init-param>
  		<param-name>encoding</param-name>
  		<param-value>UTF-8</param-value>
  	</init-param>
  </filter>
  <filter-mapping>
  	<filter-name>character encoding</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping> -->
  
  <servlet>
  	<servlet-name>helloServlet2</servlet-name>
  	<servlet-class>basic.HelloServlet2</servlet-class>
  	<load-on-startup>20</load-on-startup>
<!--   	<init-param>
  		<param-name>load-on-startup</param-name>
  		<param-value>10</param-value>
  	</init-param> -->
  </servlet>
  
  <servlet-mapping>
	  <servlet-name>helloServlet2</servlet-name>
	  <url-pattern>/helloServlet2</url-pattern>
  </servlet-mapping>
</web-app>

필터를 활용하여 인코딩하기

CharacterEncodingFilter.java

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.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;

@WebFilter(urlPatterns = "/*")
public class CharacterEncodingFilter extends HttpFilter implements Filter {
    public CharacterEncodingFilter() {
        super();
        // TODO Auto-generated constructor stub
    }

	public void destroy() {
		System.out.println("CharacterEncodingFilter 소멸자 수행");
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest hrequest = (HttpServletRequest) request;
		hrequest.setCharacterEncoding("UTF-8");
		chain.doFilter(request, response);
	}

	public void init(FilterConfig fConfig) throws ServletException {
		System.out.println("CharacterEncodingFilter.init() 수행");
	}

}

form 활용하기

  • form에서 서버로 값을 건내주려면 name값이 있어야 한다.
    parameter/form1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
	<style>
		ul { list-style:none;}
		li { line-height:50px; }
		label {
			width:60px;
			float:left;
		}
	</style>
</head>
<body>
	<h1>예약 정보</h1>
	<form action="process1.jsp" method="post">
		<ul>
			<li>
				<label for="r-name">이 름</label>
				<input type="text" id="r-name" name="r-name" autofocus="autofocus" required="required">
			</li>
			<li>
				<label for="r-phone">휴대폰</label>
				<input type="tel" id="r-phone" name="r-phone" required="required">
			</li>
			<li>
				<label for="r-email">이메일</label>
				<input type="email" id="r-email" name="r-mail" required="required">
			</li>
			<li>
				<input type="submit" value="예약하기">
		</ul>
	</form>
</body>
</html>

parameter/process1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<% 
	// out.println(request.getParameter("r-name")); // 권장 x
	String name = request.getParameter("r-name");
	String phone = request.getParameter("r-phone");
	String mail = request.getParameter("r-mail");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
name: <%=name %> <br/>
phone: <%=phone %> <br/>
mail: <%=mail %> <br/>
</body>
</html>

form2.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
    <style>
			#container { 
				width:520px;
				border:1px solid black;
				padding:20px 40px;
				margin:0 auto;
			}
      fieldset { margin-bottom:15px; }
      legend { font-weight:bold; }
			ul {list-style-type: none;}
			li { line-height:30px;}
    </style>
</head>
<body>
	<div id="container">
		<h1>프런트엔드 개발자 지원서 </h1>
		<p>HTML, CSS, Javascript에 대한 기술적 이해와 경험이 있는 분을 찾습니다.</p>
		<hr>
		<form action="process2.jsp" method="get">
			<h4>개인정보</h4>
			<ul>
				 <li>
					 <!-- <input>태그 앞 뒤에 <label></label> 태그로 묶어도 됩니다 -->
						<label for="sname"> 이름 </label>
						<input type="text" id="sname" name="name" required="required" autofocus placeholder="공백없이 입력하세요">
				</li>
				<li>
						<label for="snumber"> 연락처 </label>
						<input type="text" id="snum" name="phone" required="required">
				 </li>
			</ul>
			<h4>지원 분야</h4>
			<ul>
				<li>
					<label><input type="radio" name="field" value="웹 퍼블리싱"> 웹 퍼블리싱</label>
				</li>
				<li>
					<label><input type="radio" name="field" value="웹 애플리케이션 개발"> 웹 애플리케이션 개발</label>
				</li>
				<li>
					<label><input type="radio" name="field" value="개발 환경 개선"> 개발 환경 개선</label>
				</li>
			</ul>
			<h4>취미</h4>
			<ul>
				<li><input type="checkbox" name="hobby" value="잠자기"> 잠자기</li>
				<li><input type="checkbox" name="hobby" value="뒹굴기"> 뒹굴기</li>
				<li><input type="checkbox" name="hobby" value="가위눌리기"> 가위눌리기</li>
			</ul>
			<ul>성별</ul>
			<select name="gender">
				<option value="1" selected>남자</option>
				<option value="2">여자</option>				
			</select>
	      <label>
	        <h4>지원동기</h4>
	        <textarea id="motive" name="motive" cols="60" rows="5" placeholder="본사 지원 동기를 간략히 써 주세요."></textarea>
	      </label>
			<div>
				<input type="submit" value="접수하기">
				<input type="reset" value="다시 쓰기">
				<!-- 다음과 같이 작성해도 됩니다.
					<button type="submit">접수하기</boutton>
					<button type="reset">다시 쓰기</button>
				-->
			</div>
		</form>
	</div>
</body>
</html>

beans/Reservation.java

package beans;

import java.io.Serializable;

public class Reservation implements Serializable {

    private String name;
    private String phone;
    private String email;

    public String getName() {
        return name;
    }

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

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

jstl/jstl01.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<c:set var="i" value="10" scope="page"/>
${i}
<hr/>
\${10 + 5}=${10 + 5}<br/>
\${10 - 5}=${10 - 5}<br/>
\${10 * 5}=${10 * 5}<br/>
\${10 / 5}=${10 / 5}<br/>
\${10 % 5}=${10 % 5}<br/>
\${10 mod 5}=${10 mod 5}<br/>
<hr/>
\${10 > 5}=${10 > 5}<br/>
\${10 < 5}=${10 < 5}<br/>
\${10 >= 5}=${10 >= 5}<br/>
\${10 <= 5}=${10 <= 5}<br/>
\${10 == 5}=${10 == 5}<br/>
\${10 != 5}=${10 != 5}<br/>
</body>
</html>

jstl/view.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<table>
	<caption>북산</caption>
<c:forEach items="${list}" var="mem">
	<tr>
		<td>${mem.no}</td>
		<td>${mem.name}</td>
		<td>${mem.position}</td>
	</tr>
</c:forEach>
</table>
</body>
</html>

basic/Memeber.java

package basic;

import java.io.Serializable;

public class Member implements Serializable{
	public int getNo() {
		return no;
	}
	public Member(int no, String name, String position) {
		super();
		this.no = no;
		this.name = name;
		this.position = position;
	}
	public void setNo(int no) {
		this.no = no;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPosition() {
		return position;
	}
	public void setPosition(String position) {
		this.position = position;
	}
	private int no;
	private String name;
	private String position;
}

basic/JstlServlet.java

package basic;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/JstlServlet")
public class JstlServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		List<Member> list = new ArrayList<>();
		list.add(new Member(4, "채치수", "센터"));
		list.add(new Member(14, "김준호", "스몰포워드"));
		list.add(new Member(7, "송태섭", "포인터가드"));
		list.add(new Member(10, "강백호", "파워포워드"));
		list.add(new Member(11, "서태웅", "스몰포워드"));
		
		request.setAttribute("list", list);
		RequestDispatcher dispatcher = request.getRequestDispatcher("/jstl/view.jsp");
		dispatcher.forward(request, response);
	}

}

mvc.fx/DispatcherServlet.java

package mvc.fx;

import java.io.IOException;
import java.util.Map;

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 pilot.controller.FormController;
import pilot.controller.ProcessController;

@WebServlet(
   urlPatterns = {"/pilot/*"},
   loadOnStartup = 10)
public class DispatcherServlet extends HttpServlet {
   /*
   private Map<String, AbstractController> controllerMap = new HashMap<>();
   @Override
   public void init() throws ServletException {
      
      Properties prop = new Properties();
      
      try {
         prop.load(new FileInputStream(this.getClass().getResource("dispatcher-servlet.properties").getPath()));
         for(Object oKey : prop.keySet()) {
            String key = ((String)oKey).trim();
            Class<?> className = null;
            try {
               className = Class.forName(prop.getProperty(key).trim());
               controllerMap.put(key, (AbstractController) className.getConstructor().newInstance());
               System.out.println("🧡 loaded : " + className + " 🧡");
            } catch (Exception e) {
               e.printStackTrace();
               System.out.println("💔 error : " + className + " 💔");
            }
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
   */
   @Override
   protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      String requestURI = request.getRequestURI();
      System.out.println(requestURI);
      String contextPath = request.getContextPath();
      System.out.println(contextPath);
      String action = requestURI.substring(contextPath.length());
      
      AbstractController controller = null;
      ModelAndView mav = null;
      if(action.equals("/pilot/form")) {
    	  controller = new FormController();
    	  mav = controller.handleRequestInternal(request, response);
      } else if (action.equals("/pilot/process")) {
    	  controller = new ProcessController();
    	  mav = controller.handleRequestInternal(request, response);
      }
      
      /*
      String action = requestURI.substring(contextPath.length());
      
      AbstractController controller = controllerMap.get(action);
      ModelAndView mav = controller.handleRquestInternal(request, response);
      */
      if (mav != null) {
         
         String viewName = mav.getViewName();
         if (viewName.startsWith("redirect:")) {
            response.sendRedirect(viewName.substring(9));
         } else {
            Map<String, Object> model = mav.getModel();
            for(String key : model.keySet()) {
               request.setAttribute(key, model.get(key));
            }            
            RequestDispatcher dispatcher = request.getRequestDispatcher(viewName);
            dispatcher.forward(request, response);
         }
      } else {
         System.out.println("RequestDispatcher에서 길을 잃었다네~");
      }
   }
}

mvc.fx/AbstractController.java

package mvc.fx;

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

public abstract class AbstractController {

	public abstract ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response);
}

mvc.fx/ModelAndView.java

package mvc.fx;

import java.util.HashMap;
import java.util.Map;

public class ModelAndView {
	private String viewName;
	private Map<String, Object> model = new HashMap<>();
	
	public ModelAndView() {}
	
	public ModelAndView(String viewName) {
		setViewName(viewName);
	}
	
	public ModelAndView(String viewName, String key, Object value) {
		setViewName(viewName);
		addObject(key, value);
	}

	public String getViewName() {
		return viewName;
	}

	public void setViewName(String viewName) {
		this.viewName = viewName;
	}

	public Map<String, Object> getModel() {
		return model;
	}

	public void setModel(Map<String, Object> model) {
		this.model = model;
	}
	
	public void addObject(String key, Object value) {
		model.put(key, value);
	}
}

pilot.controller/FormController.java

package pilot.controller;

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

import mvc.fx.AbstractController;
import mvc.fx.ModelAndView;

public class FormController extends AbstractController{
	
	@Override
	public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) {
		
		return new ModelAndView("/WEB-INF/pilot/form.jsp");
	}

}

pilot/form.jsp

package mvc.fx;

import java.util.HashMap;
import java.util.Map;

public class ModelAndView {
	private String viewName;
	private Map<String, Object> model = new HashMap<>();
	
	public ModelAndView() {}
	
	public ModelAndView(String viewName) {
		setViewName(viewName);
	}
	
	public ModelAndView(String viewName, String key, Object value) {
		setViewName(viewName);
		addObject(key, value);
	}

	public String getViewName() {
		return viewName;
	}

	public void setViewName(String viewName) {
		this.viewName = viewName;
	}

	public Map<String, Object> getModel() {
		return model;
	}

	public void setModel(Map<String, Object> model) {
		this.model = model;
	}
	
	public void addObject(String key, Object value) {
		model.put(key, value);
	}
}

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>mvc</h1>
<a href="pilot/form">form</a><br/>
<%-- <h1>Hello Servlet/JSP</h1>
<%
	out.println("Hello World");
%> --%>
</body>
</html>

pilot.controller/ProcessController.java

package pilot.controller;

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

import mvc.fx.AbstractController;
import mvc.fx.ModelAndView;

public class ProcessController extends AbstractController {

	@Override
	public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) {
		String name = request.getParameter("name");
		String iam = "그래, 난 " + name + ".";
		ModelAndView mav = new ModelAndView();
		mav.setViewName("/WEB-INF/pilot/process.jsp");
		mav.addObject("iam", iam);
		return mav;
	}

}
profile
개발 기록장
post-custom-banner

0개의 댓글