servlet是运行在服务器端上的,用普通的.java文件不同,它没有main方法。
建立一个包后然后新建一个class文件,
之后要在WebXml文件里面配置
配置的内容注意:
1、<servlet></servlet>和<servlet-mapping> </servlet-mapping>里面的<servlet-name>标签的内容要一致。
2、 <url-pattern>/HelloWinney</url-pattern>里面记得加上/(斜杠)
<servlet-name>HelloWinney</servlet-name>
<servlet-class>com.winney.www.Javaservelet</servlet-class>
</servlet>```
<servlet-mapping>
<servlet-name>HelloWinney</servlet-name>
<url-pattern>/HelloWinney</url-pattern>
</servlet-mapping>
package com.winney.www;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Javaservelet extends HttpServlet
{
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println("<html><head><title>Fighting</title></head><body><h1>Hello, Winney!</h1></body></html>");
out.flush();
}
}
总之,我们可以将Servlet看做是嵌套了 HTML代码的java类,可以将JSP看作是嵌套了java代码的HTML页面。