본문 바로가기
kosta/Servlet,JSP,JDBC,MyBatis

[Servlet, JSP] Intellij JSP, Servlet Setting 및 실습

by 엑츄얼리 2022. 4. 12.

Intellij JSP, Servlet 환경 구성하기

진짜 intellij로 이부분 세팅하는데 고생을 너무 많이했다 ㅠㅠ

 

 

1.

Next 클릭

 

 

2.

Project name 입력 후 Finish

 

 

3. 

프로젝트 이름 우클릭 -> Add Framework Support
Add Frameworks Support에서 Web Application -> WebService 체크

 

 

4. web -> web-INF내부에 server-config.wsdd 삭제 및 web.xml 내부 수정

web.xml 수정

 

 

5. tomcat 설정 (요건 기억안나면 검색하는게 더 빠름)

 

 

6. File -> ProjectStructure -> libraries

다운로드 되어있는 tomcat 폴더 내부 -> lib -> jsp-api.jar와 servlet-api.jar를 libraries에 추가

 

=> tomcat 실행해서 jsp, html파일 등 실행해보면 잘 된다.

 

- 끝 - 

 

 


1-1. HTML과 Servlet(JAVA)

form.servlet.html -> CalcServlet.java

 

<- WAS는 디렉토리의 구성과 파일의 위치를 잘 맞춰주어야 한다.

 

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/CalcServlet" method="post">
<!--    action = "CalcServlet"도 가능 제일 앞에 /가 중요하진 않은 듯-->
<!--<form action = "cals.jsp" method="post">    -->
    숫자1 : <input type="text" name="num1"><br>
    숫자2 : <input type="text" name="num2"><br>
    이름  : <input type="text" name="userName"><br>
    <input type="submit" value="계산">
</form>
</body>
</html>

<form_servlet.html>

 

package servlet;

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 java.io.IOException;
import java.net.URLEncoder;

@WebServlet("/CalcServlet")
public class CalcServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int num1 = 0;
        int num2 = 0;
        String name = "";

        request.setCharacterEncoding("utf-8");
        num1 = Integer.parseInt(request.getParameter("num1"));
        num2 = Integer.parseInt(request.getParameter("num2"));
        name = request.getParameter("userName");

        int result = num1 + num2;
        request.setAttribute("result", result);
        request.setAttribute("userName", name);

        //1. Dispatcher
        RequestDispatcher re =
                request.getRequestDispatcher("/basic/result_dispatcher.jsp");
        re.forward(request, response);

        //2. Redirect 방식으로 이동(새로운 request발생)
//        String encodeName = URLEncoder.encode(name, "UTF-8");
//        response.sendRedirect("/basic/result_redirect.jsp?result=" + result + "&userName=" + encodeName);
    }
}

<CalcServlet.java>

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
</head>
<body>
    결과 : <b>${result}</b><br>
    이름 : <b>${userName}</b>
</body>
</html>

<result_dispatcher.jsp>

 

<%@ page import="java.net.URLDecoder" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%
    String userName = request.getParameter("userName");
    String decodeName = URLDecoder.decode(userName, "utf-8");
%>
redirector
결과 : <b>${param.result}</b>
이름 : <b>$<%=decodeName%></b>
<%--${param.userName}--%>
</body>
</html>

<result_redirect.jsp>

 

 

1-2. HTML과 JSP

form_jsp.html -> calc.jsp

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/basic/calc.jsp" method="post">
<!--<form action = "cals.jsp" method="post">    -->
    숫자1 : <input type="text" name="num1"><br>
    숫자2 : <input type="text" name="num2"><br>
    이름  : <input type="text" name="userName"><br>
    <input type="submit" value="계산">
</form>
</body>
</html>

<form_jsp.html>

 

<%@page import="java.net.URLEncoder" %>
<%@page language="java" contentType="text/html; charset=utf-8"
        pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
</head>
<body>
<%
    int num1 = 0;
    int num2 = 0;
    String name = "";

    request.setCharacterEncoding("utf-8");
    num1 = Integer.parseInt(request.getParameter("num1"));
    num2 = Integer.parseInt(request.getParameter("num2"));
    name = request.getParameter("userName");

    int result = num1 + num2;

    request.setAttribute("result", result);
    request.setAttribute("userName", name);

//    //Dispatcher
//    RequestDispatcher rd = request.getRequestDispatcher("/basic/result_dispatcher.jsp");
//    rd.forward(request, response);

    //Redirect
    String encodeName = URLEncoder.encode(name, "utf-8");
    response.sendRedirect("/basic/result_redirect.jsp?result=" + result + "&userName=" + encodeName);
%>
</body>
</html>

<calc.jsp>

 

+ result_dispatcher.jsp와 result_redirect.jsp는 1-1과 공통된다.

 

 

2. JSP to JSP

registerForm.jsp -> registerProc

 

출력결과는 위와 같고, 아래 파일 순서는 호출되는 순서대로 작성하였다. 내부에 다음 파일을 어디에서 어떤 함수로 호출해서 진행되는지를 유의해서 진행하면 이해에 도움이 될 것 같다.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
   <<form action="registerProc.jsp" method="post">
      이름: <input type="text" name="name"><br>
      주소: <input type="text" name="address"><br>
      <input type="checkbox" name="hobby" value="야구">야구</input>  
      <input type="checkbox" name="hobby" value="독서">독서</input>  
      <input type="checkbox" name="hobby" value="영화">영화</input>  <br>
      <input type="submit" value="전송">
   </form>
</body>
</html>

<registerForm.jsp>

 

<%@page language="java" contentType="text/html; charset=utf-8"
        pageEncoding="utf-8"%>
<%
    request.setCharacterEncoding("utf-8");

    String name = request.getParameter("name");
    String address = request.getParameter("address");
    String arr[] = request.getParameterValues("hobby");//배열에 저장할 때는 getParameterValues

    request.setAttribute("name", name);
    request.setAttribute("address", address);
    request.setAttribute("hobby", arr);
%>

<%--dispatcher--%>
<jsp:forward page="result_dispatcher.jsp"/>
<!DOCTYPE html>
<html>
<head>
</head>
</html>

<registerProc.jsp>

 

<%@ page import="java.util.Arrays" %>
<%@ page language="java" contentType="text/html charset=utf-8"
         pageEncoding="utf-8"%>

<!DOCTYPE html>
<html>
<body>
    <%
        String arr[] = (String[])(request.getAttribute("hobby"));
    %>
    <h3>회원가입내역</h3>
    이름:${name}<br>
    주소:${address}<br>
    취미:<%=Arrays.toString((String[])request.getAttribute("hobby"))%>;
<%--Arrays.toString(arr)    --%>
</br>
</br>
</body>
</html>

<result_dispatcher.jsp>

 

3. jsp 액션테그 : useBean, setProperty

<jsp:useBean id="{Object name}" class="{java클래스의 패키지 기반 위치}"/>

<jsp:setProperty property="*" name="{Object name}"/>

 

userBean에 의해 생성된 이름이 Object name인 객체에

setProperty를 통해 post로 요청된 모든 테그들을 저장

 

 

 

 

 

<%--
  Created by IntelliJ IDEA.
  User: JKM
  Date: 2022-04-11
  Time: 오후 3:10
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="Insert_Action.jsp" method="post">
    작성자 : <input type="text" name="writer"><br>
    제목 : <input type="text" name="title"><br>
    내용 : <br>
    <textarea rows="6" cols="70" name="contents"></textarea>
    <br>
    <input type="submit" value="submit">
</form>
</body>
</html>

<Insert_form.jsp>

 

<%@ page import="bean.BoardDao" %><%--
  Created by IntelliJ IDEA.
  User: JKM
  Date: 2022-04-11
  Time: 오후 3:11
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<%
    request.setCharacterEncoding("utf-8");

//    1.
//    Board board = new Board();
//    board.setTitle(request.getParameter("title"));
//    board.setWriter(request.getParameter("writer"));
//    board.setContents(request.getParameter("contents"));
%>
<%--2. JAVA => Action Tag 대신    --%>
<jsp:useBean id="board" class="bean.Board"/>
<jsp:setProperty property="*" name="board"/>

<%
    BoardDao dao = new BoardDao();
    dao.insertBoard(board);
%>
<html>
<head>
    <title>Title</title>
</head>
<body>

</body>
</html>

<Insert_Action.jsp>

 

package bean;

public class Board {
    private int seq;
    private String title;
    private String writer;
    private String contents;
    private String regdate;
    private int hitcount;

    @Override
    public String toString() {
        return "Board{" +
                "seq=" + seq +
                ", title='" + title + '\'' +
                ", writer='" + writer + '\'' +
                ", contents='" + contents + '\'' +
                ", regdate='" + regdate + '\'' +
                ", hitcount=" + hitcount +
                '}';
    }

    public int getSeq() {
        return seq;
    }

    public void setSeq(int seq) {
        this.seq = seq;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getWriter() {
        return writer;
    }

    public void setWriter(String writer) {
        this.writer = writer;
    }

    public String getContents() {
        return contents;
    }

    public void setContents(String contents) {
        this.contents = contents;
    }

    public String getRegdate() {
        return regdate;
    }

    public void setRegdate(String regdate) {
        this.regdate = regdate;
    }

    public int getHitcount() {
        return hitcount;
    }

    public void setHitcount(int hitcount) {
        this.hitcount = hitcount;
    }
}

<Board.java>

 

package bean;

public class BoardDao {
    public void insertBoard(Board board){
        System.out.println(board);
    }
}

<BoardDao.java>

 

 

4-1. cookies

 

jsp에 등록된 (DB에서 받아왔다는 가정) 아이디와 비밀번호가 맞다면 로그인 화면으로 이동하고

 로그아웃 과정까지 진행

 

 

<%@ 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>
   <form action="loginProc.jsp" method="post">
      아이디 : <input type="text" name="id"><br>
      비밀번호 : <input type="text" name="pass"><br>
      <input type="submit" value="로그인">
   </form>
</body>
</html>

<loginForm.jsp>

 

<%@page import="java.net.URLEncoder"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%
   String m_id = "kosta";
   String m_pass = "1234";

   String id = request.getParameter("id");
   String pass = request.getParameter("pass");

   String m_name = "홍길동";
   String name = URLEncoder.encode(m_name, "utf-8");

   if(id.equals(m_id) && pass.equals(m_pass)){
      Cookie cookie = new Cookie("name", name);//쿠키 생성
      response.addCookie(cookie);//생성된 쿠키를 클라이언트에 전달
   }else{
      response.sendRedirect("loginForm.jsp");
   }
%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
   <a href="main.jsp">메인페이지</a>
</body>
</html>

<loginProc.jsp>

 

<%@page import="java.net.URLDecoder" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%
    Cookie[] cookies = request.getCookies();
    String name = "";
    boolean find = false;


    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals("name")) {
                name = URLDecoder.decode(cookies[i].getValue(), "utf-8");
                find = true;
                break;
            }
        }
    }

    if(find != true){
        response.sendRedirect("loginForm.jsp");
    }
%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
</head>
<body>
<b><%= name %>
</b>님 반갑습니다.
<a href="logout.jsp">로그아웃</a>
</body>
</html>

<main.jsp>

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%
    Cookie[] cookies = request.getCookies();
    boolean find = false;
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals("name")) {
                cookies[i].setMaxAge(0);
                response.addCookie(cookies[i]);
                find = true;
                break;
            }
        }
    }

    if (find == true) {
        response.sendRedirect("loginForm.jsp");
    }
%>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
</head>
<body>

</body>
</html>

<logout.jsp>

* 로그인 정보가 저장된 cookie가 존재하지 않는다면 main.jsp에 접근할 수 없도록 만들어져있다.

 

 

4-2. Session

* 로그인 과정 이후에 [추가]버튼을 통해 추가된 상품을 list에 저장 후 계산을 누르면 list에 있는 상품들이 출력되는 예제

 

<%@ 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>ch06 : login.jsp</title>
</head>
<body>
<%
session.setAttribute("init", true);
%>
<div align="center">
   <H2>로그인</H2>
   <form name="form1" method="POST" action="selProduct.jsp">
      <input type="text" name="username"/>
      <input type="submit" value="로그인"/>
   </form>
</div>
</body>
</html>

<login.jsp>

 

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.util.*"%>
<%
   request.setCharacterEncoding("utf-8");
   String username = request.getParameter("username");
   session.setAttribute("username", username);
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML>
<HEAD>
<title>ch06 : selProduct.jsp</title>
</head>
<%
   String m_id = "alswkdrb1";

   String id = request.getParameter("username");

   if (m_id.equals(id)){
      session.setAttribute("username", id);
   }else{
      response.sendRedirect("login.jsp");
   }

%>
<body>
<div align="center">
   <H2>상품선택</H2>
   <HR>
   ${username } 님 환영합니다!!!!
   <HR>
   <form name="form1" method="POST" action="add.jsp">
      <SELECT name="product">
         <option>사과</option>
         <option>귤</option>
         <option>파인애플</option>
         <option>자몽</option>
         <option>레몬</option>
      </SELECT>
      <input type="submit" value="추가"/>
   </form>
   <a href="checkOut.jsp">계산</a>
</div>
</body>
</html>




<selProduct.jsp>

 

<%@page import="java.util.List"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
    <%! List<String> list = new ArrayList<String>(); %>
    
    <%
      boolean init = (boolean)session.getAttribute("init");
      if (init == false){
         list.clear();
         session.setAttribute("init", true);
      }
       request.setCharacterEncoding("utf-8");
       String product = request.getParameter("product");
      list.add(product);

      for (int i = 0; i < list.size(); i++){
         out.write(list.get(i));
      }
      session.setAttribute("list", list);
    
    %>
<!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>Insert title here</title>
</head>
<body>
   <a href="javascript:history.back()">뒤로가기</a>
   <%=product %>
</body>
</html>

<add.jsp>

 

<%@page import="java.util.ArrayList"%>
<%@ page import="java.util.List" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%
        List<String> list = (List<String>)session.getAttribute("list");
       for (int i = 0; i < list.size(); i++){
            out.write(list.get(i) + '\n');
        }
        session.setAttribute("init", false);
    %>
<!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>Insert title here</title>
</head>
<body>
   
</body>
</html>

<checkOut.jsp>

 

4-3. session

위 문제에 가격과 개수 input을 추가하고, 이를 저장할 Product.java라는 클래스를 생성하여 객체의 형태로 저장

계산 버튼을 클릭 시 이전까지 추가한 모든 객체를 통해 총 가격 계산

 

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ch06 : login.jsp</title>
</head>
<body>
<%
%>
<div align="center">
	<H2>로그인</H2>
	<form name="form1" method="POST" action="selProduct.jsp">
		<input type="text" name="username"/>
		<input type="submit" value="로그인"/>
	</form>
</div>
</body>
</html>

<login.jsp>

 

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.util.*"%>
<%
	request.setCharacterEncoding("utf-8");
	String username = request.getParameter("username");
	session.setAttribute("username", username);
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML>
<HEAD>
<title>ch06 : selProduct.jsp</title>
</head>
<%
	String m_id = "alswkdrb1";

	String id = request.getParameter("username");

	if (m_id.equals(id)){
		session.setAttribute("username", id);
	}else{
		response.sendRedirect("login.jsp");
	}

%>
<body>
<div align="center">
	<H2>상품선택</H2>
	<HR>
	${username } 님 환영합니다!!!!
	<HR>
	<form name="form1" method="POST" action="add.jsp">
		<SELECT name="product">
			<option>사과</option>
			<option>귤</option>
			<option>파인애플</option>
			<option>자몽</option>
			<option>레몬</option>
		</SELECT>
		<br>
		개당 가격 : <input type="text" name="price"><br>
		수량     : <input type="text" name="amount"><br>
		<input type="submit" value="추가"/>
	</form>
	<a href="checkOut.jsp">계산</a>
</div>
</body>
</html>

<selProduct.jsp>

 

package bean_mission;

public class Product {
    private String product;
    private int amount;
    private int price = 0;

    public void setProduct(String product) {
        this.product = product;
    }

    public void setAmount(int amount) {
        this.amount = amount;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public String getProduct() {
        return product;
    }

    public int getAmount() {
        return amount;
    }

    public int getPrice() {
        return price;
    }

    public String print(){
        return "product : " + product + "\namount : " + amount + "\nprice : " + price + "<br>";
    }
}

<Product.java>

 

<%@page import="java.util.List"%>
<%@page import="java.util.ArrayList"%>
<%@ page import="bean_mission.Product" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
    <%!List<Product> productList = new ArrayList<Product>();%>

	<jsp:useBean id="productInfo" class="bean_mission.Product"/>
	<%request.setCharacterEncoding("utf-8");%>
	<jsp:setProperty property="*" name="productInfo"/>

    <%
		productList.add(productInfo);
		//출력 확인
		for (int i = 0; i < productList.size(); i++){
			out.write(productList.get(i).print());
		}
		session.setAttribute("productList", productList);
    %>
<!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>Insert title here</title>
</head>
<body>
	<a href="javascript:history.back()">뒤로가기</a>
</body>
</html>

<add.jsp>

 

<%@page import="java.util.ArrayList" %>
<%@ page import="java.util.List" %>
<%@ page import="bean_mission.Product" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%
    List<Product> productList = (List<Product>) session.getAttribute("productList");

    int total = 0;
    for (int i = 0; i < productList.size(); i++) {
        Product product = productList.get(i);
        out.write(product.print() + '\n');
        total += product.getAmount() * product.getPrice();
    }
    out.println("<br>총 가격은 " + total + "입니다.");
    productList.clear();
    session.setAttribute("productList", productList);
%>
<!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>Insert title here</title>
</head>
<body>

</body>
</html>

<checkOut.jsp>

댓글