作者:莺妈 | 来源:互联网 | 2024-10-14 17:14
实现Servlet程序的三种方法
1.手动实现Servlet程序
1.编写一个类去实现Servlet接口
2.实现service方法,处理请求并响应数据
示例代码:
//HelloServlet.java
package servlet;
import javax.servlet.*;
import java.io.IOException;
public class HelloServlet implements Servlet {
@Override
public void init(ServletConfig servletConfig) throws ServletException {
}
@Override
public ServletConfig getServletConfig() {
return null;
}
// service方法专门来处理请求和响应
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("Hello,Servlet! 被访问了");
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
}
}
3.到web.xml配置Servlet程序的访问地址
HelloServlet
servlet.HelloServlet
HelloServlet
/hello
2.通过HttpServlet实现Servlet程序
在一般项目开发中一般很少使用Servlet接口来实现Servlet程序,一般都是使用继承HttpServlet类的方式去实现Serlvet程序
步骤:
1.编写一个类去继承HttpServlet类
2.根据需要重写doGet和doPost方法
3.去web.xml去配置访问地址
4.最后运行测试就可以接收到值了
示例代码:
//HttpServlet.java
package servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
//继承HttpServlet
public class HttpServlet02 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doGet方法");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doPost方法");
}
}
```css
```bash
```handlebars
```sql
```Javascript
//web.xml
HelloServlet
servlet.HelloServlet
HelloServlet
/hello
HelloServlet02
servlet.HttpServlet02
HelloServlet02
/hello02
3.通过IDEA自动生成Servlt程序
1.通过IDEA新建一个Servlet
2.之后再新生成的java文件中我们自己按需要配置就好了
3.老样子,依旧是在web.xml中配置好
4.写个按钮来检测配置结果
示例代码:
//HelloServlet.java
package servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class HelloServlet03 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("通过IDEA自动/doGet方法");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("通过IDEA自动/doGet方法");
}
}
//web.xml
HelloServlet
servlet.HelloServlet
HelloServlet
/hello
HelloServlet02
servlet.HttpServlet02
HelloServlet02
/hello02
HelloServlet03
servlet.HelloServlet03
HelloServlet03
/hello03