从头写java文件的方式,编译成CLASS文件,加强对SERVLET容器的理解。
稍后试试JAR和WAR包。
文件内容(跟以前用IDE的一样):
HelloServlet.java:
package cc.openhome; 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; /** * Servlet implementation class HelloServlet */ @WebServlet(urlPatterns = {"/hello.view"}) public class HelloServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public HelloServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String name = request.getParameter("name"); out.println("<html>"); out.println("<head>"); out.println("<title>Hello</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1> Hello!" + name + "! </h1>"); out.println("</body>"); out.println("</html>"); out.close(); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
web.xml(这个文件可有可无的,在用servlet3.0注解的情况下,当里,用了注解,也可以定义另一个URL):
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <servlet> <servlet-name>firstServlet</servlet-name> <servlet-class>cc.openhome.HelloServlet</servlet-class> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>firstServlet</servlet-name> <url-pattern>/first.do</url-pattern> </servlet-mapping> </web-app>
注意目录的摆放:
。HelloServlet.java文件位于C:\apache-tomcat-8.0.30\webapps\First\WEB-INF\classes目录下。 。编译命令为: 。C:\apache-tomcat-8.0.30\webapps\First\WEB-INF\classes>javac -cp .;C:\apache-tomcat-8.0.30\lib\servlet-api.jar -d . HelloServlet.java 。生成的HelloServlet.class文件位于:C:\apache-tomcat-8.0.30\webapps\First\WEB-INF\classes\cc\openhome目录下。 。web.xml当然位于C:\apache-tomcat-8.0.30\webapps\First\WEB-INF目录下。
于是用
http://127.0.0.1:8080/First/first.do?name=hello
http://127.0.0.1:8080/First/hello.view?name=hello
都会指定到同一个servlet.
时间: 2024-09-18 21:46:53