Servlet与Jsp学习笔记--1、Handles a Request
1、 Handles a Request
Problem
动态在请求时包含一个存在的servlet.
Solution
Use the javax.servlet.RequestDispatcher.include(request,response)method in the doGet( ) method of the servlet
Code:
import javax.servlet.*;
import javax.servlet.http.*;
public class IncludeServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
java.io.IOException {
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter( );
out.println("<html>");
out.println("<head>");
out.println("<title>Include Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Welcome To Our Universe</h1>");
out.println("Imagine the rest of the page here.<br><br>");
//Include the copyright information
RequestDispatcher dispatcher = request.getRequestDispatcher("/copyright");
dispatcher.include(request, response);
out.println("</body>");
out.println("</html>");
}//doGet
}
import javax.servlet.*;
import javax.servlet.http.*;
public class Copyright extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
java.io.IOException {
java.io.PrintWriter out = response.getWriter( );
out.println("Copyright© 2003-2004 EmbraceAndExtend Corp.");
}
}
部署
javac -classpath d:"tomcat"common"lib"servlet-api.jar -d WEB-INF/classes IncludeServlet.java
javac -classpath d:"tomcat"common"lib"servlet-api.jar -d WEB-INF/classes Copyright.java
在web.xml增加配置:
<servlet>
<servlet-name>IncludeServlet</servlet-name>
<servlet-class>IncludeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>IncludeServlet</servlet-name>
<url-pattern>/IncludeServlet/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Copyright</servlet-name>
<servlet-class>Copyright</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Copyright</servlet-name>
<url-pattern>/copyright/*</url-pattern>
</servlet-mapping>
目前维护的开源产品:https://gitee.com/475660