1、编写一个java类,此类继承HttpServlet
创建完工程(见上一篇随笔:使用eclipse创建在myeclipse中运行的web工程),在src中新建一个包,包名字叫servlet;再新建一个类,名字叫HelloServlet,指定父类是HttpServelt-javax.servlet.http,点击finish。
2、重写doGet()和doPost()方法
右击鼠标,source-override/Implement Methods
//继承于HttpServlet
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("处理Get()请求");
PrintWriter out = response.getWriter();
response.setContentType("text/html;charset=utf-8");
out.println("<strong>Hello Servletgfdgdfgd</strong><br>");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("处理Post()请求");
PrintWriter out = response.getWriter();
response.setContentType("text/html;charset=utf-8");
out.println("<strong>Hello Servletgfdgdfgd</strong>");
}
}
3、在web.xml中注册Servlet,定义两个标签
(1)ctrl+N 新建xml文件,内容:
<?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">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
(2)定义两个标签
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/servlet/HelloServlet</url-pattern>
</servlet-mapping>
4、index.jsp中 设置使用get()方式的 超链接,post()方式的 提交按钮
<a href="servlet/HelloServlet">Get方式请求HelloServlet</a>
<form action="servlet/HelloServlet" method="post">
<input type="submit" value="Post方式请求HelloServlet123123"/>
</form>
流程:
创建工程(新建web.xml 和 index.jsp,修改配置文件)
新建包/servlet,新建项目
添加tomcat,运行