Servlet 是一个 Java程序,是在服务器上运行以处理客户端请求并作出响应的程序
开发第一个Servlet:
我们需要创建一个 web项目,在src目录下创建servlet包,用于保存servlet类,类中继承javax.servlet.http.HttpServlet 类。
Servlet的生命周期有三个阶段:初始化阶段 init() --> 运行阶段 Service() --> 消亡阶段 destroy()
如图所示:
进行简单的了解后我们可以在网页上传递数据到后台:
新建一个LoginServlet类写入数据:
package servlet1;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String name = req.getParameter("name");
String pwd = req.getParameter("pwd");
System.out.println("姓名: "+name+" 密码:"+pwd);
System.out.println("get...");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String name = req.getParameter("name");
String pwd = req.getParameter("pwd");
System.out.println("姓名: "+name+" 密码:"+pwd);
System.out.println("post...");
}
}
打开WebRoot–>WEB-INF–>web.xml 文件,添加内容 做链接:
在index.jsp 中写好表单在网页中展示:
部署运行:
在浏览器中加载:
接收到数据:
还有一种接收操作方法是在地址栏中写入数据:
接收到数据:
Servlet页面交互(二):