如何在Myeclipse中写servlet
2017-07-20
1.建立web工程
2.实现servlet
package lin;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class servlet extends GenericServlet{
public void service(ServletRequest request,ServletResponse response)throws IOException , ServletException{
response.setCharacterEncoding("GBK");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet 简单例子</title>");
out.println("</head>");
out.println("<body>");
out.println("<center>");
out.println("<h2>这是第一个Servlet的例子</h2>");
out.println("</center>");
out.println("</body>");
out.println("</html>");
out.close();
}
}
3.在工程的web.xml配置servlet访问url
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
<servlet>
<servlet-name>ServletSample</servlet-name>
<servlet-class>lin.servlet</servlet-class>
</servlet>
<!-- 配置Servlet映射路径 -->
<servlet-mapping>
<servlet-name>ServletSample</servlet-name>
<url-pattern>/servlet</url-pattern>
</servlet-mapping>
</web-app>
4.发布工程到tomcat
5.启动tomcat
6.locatlhost:8080/工程名/servlet路径
例如我给出来的例子就是运行这个:localhost:8888/SampleServlet/servlet
补充:
1、在xm中有多个<servlet-name></servlet-name>,其之间的值要不能相同。
2. MyEclipse 8.5 会自动配置web.xml文件,只需注意查看xml文件中的servlet访问路径。