2013년 7월 18일 목요일

(130718) 19일차 Login.jsp ServletTest.java, Result.jsp (JSP에서 Servlet 호출 및 Servlet에서 JSP로 넘기기 예제)

 - Login.jsp 소스
<%@page import="jsp.ServletTest"%>
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
<center>
<form action = "ServletTest" method = "post">
아이디 : <input type = "texT" name = "id"><br><br>
비밀번호 : <input type = "password" name = "pass"><br><br>
<input type = "submit" value = "로그인"><br><br>
</form>
</center>
</body>
</html>


 - ServletTest.java 소스
package jsp;

import java.io.IOException;
import java.io.PrintWriter;

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("/ServletTest") // 웹 서버가 자동으로 서블릿 클래스를 인식
public class ServletTest extends HttpServlet {
private static final long serialVersionUID = 1L;
      
protected void doGet(HttpServletRequest req, HttpServletResponse res) 
throws ServletException, IOException {
jspProcess(req, res);
}

protected void doPost(HttpServletRequest req, HttpServletResponse res) 
throws ServletException, IOException {
jspProcess(req, res);
}

private void jspProcess(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {

String id = req.getParameter("id");
String pass = req.getParameter("pass");
res.setCharacterEncoding("euc-kr");

String result = "당신의 id : " + id + "이고 패스워드는 : " +pass;

// jsp를 호출하여 화면에 출력하시오.

// Request 객체의 데이터를 떠 안고
req.setAttribute("result", result);
RequestDispatcher dispatcher = req.getRequestDispatcher("Result.jsp");
// RequestDispatcher의 Result.jsp로 넘겨줌
dispatcher.forward(req, res);

}
}


 - Result.jsp 소스
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
<center>
<h2> 로그인된 페이지 </h2>
${result}
</center>
</body>
</html>


 - 결과