본문 바로가기

Java/java 기초

servlet a 태그 받아오기

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

<a href="hello">hello</a>

</body>
</html>

HelloServlet ("바로 이곳으로 이동")

@WebServlet("/hello") 를 사용해서 a href와 일치시켜준다 

package sample09;

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("/hello") // namespace -> 이름공간 (주석)
public class HelloServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("HelloServlet doGet");
		PrintWriter pw = resp.getWriter();

		pw.println("<html>");

		pw.println("<head>");
		pw.println("<title>제목</title>");
		pw.println("</head>");

		pw.println("<body>");

		pw.println("<h1>Hello Servlet Start</h1>");
		//include
		//RequestDispatcher dis = req.getRequestDispatcher("include");
		//dis.include(req, resp);
		
		//forward
		RequestDispatcher dis = req.getRequestDispatcher("forward");
		dis.forward(req, resp);

		pw.println("<h1>Hello Servlet End</h1>");

		pw.println("</body>");

		pw.println("</html>");

		pw.close();

		// include(가져오다), forward(그쪽으로 이동)
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

	}

}

ForwardServlet.java

 

package sample09;

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

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("/forward")
public class ForwardServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		PrintWriter pw = resp.getWriter();

		pw.println("<html>");

		pw.println("<head>");
		pw.println("<title>제목</title>");
		pw.println("</head>");

		pw.println("<body bgcolor='blue'>");

		pw.println("<h1>Forward Servlet</h1");

		pw.println("</body>");

		pw.println("</html>");

		// pw.close();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
	}
	
}