是Java Applet的简称。称为小服务程序或服务连接器,用Java编写的服务端程序,主要功能在于交互式地浏览和修改数据,生成动态Web内容。
不能直接在JVM上运行,需要在Servlet容器中运行,本质上是个没有Main方法的Java类。
service方法被调用后,跟进请求类型再转发给相应的方法,例如doGet和doPost。
Servlet - 图1
image.png
可以理解为Servlet是一个接口,定义了Java类的被浏览器访问到(tomcat识别)的规则;
需要自定义一个类,实现Servlet接口,那么此方法可以被tomcat识别。

实现原理

image.png
服务器接收客户端请求后,解析url,获取访问的Servlet的资源路径;
查找web.xml文件,是否有对应的
如果有,找到servlet-class
tomcat将这个字节码加载进内存并创建对象
调用这个对象的service方法

路径问题

可以通过在首部添加如下信息,然后在使用的时候,base_path加指定别名就可以<%=base_path>别名

  1. <%
  2. String base_path = request.getScheme()+":"+"//"+request.getServerName()+":"+request.getServerPort()
  3. +request.getServletContext().getContextPath()+"/";
  4. %>

请求与响应

浏览器对服务器一次访问称为一次请求,请求用HttpServletRequest对象来表示

服务器给浏览器的一次反馈称为一次响应,响应用HttpServletResponse对象来表示;

下面的jsp文件提交表单之后,值会传递到调用的服务中。
LoginServlet.java

  1. package cn.java.servlet;
  2. import java.io.IOException;
  3. import javax.servlet.ServletException;
  4. import javax.servlet.http.HttpServlet;
  5. import javax.servlet.http.HttpServletRequest;
  6. import javax.servlet.http.HttpServletResponse;
  7. public class LoginServlet extends HttpServlet {
  8. @Override
  9. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  10. // TODO Auto-generated method stub
  11. // 这里获取的参数,就是jsp文件对应的参数
  12. String username = request.getParameter("username");
  13. String password = request.getParameter("password");
  14. System.out.println("username is:"+username);
  15. System.out.println("password is:"+password);
  16. }
  17. @Override
  18. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  19. // TODO Auto-generated method stub
  20. doGet(req,resp);
  21. }
  22. }

index.jsp

  1. <%@ page language="java" contentType="text/html; charset=utf-8"
  2. pageEncoding="utf-8"%>
  3. <%
  4. String base_path = request.getScheme()+":"+"//"+request.getServerName()+":"+request.getServerPort()
  5. +request.getServletContext().getContextPath()+"/";
  6. %>
  7. <!DOCTYPE html>
  8. <html>
  9. <head>
  10. <meta charset="utf-8">
  11. <title>Insert title here</title>
  12. </head>
  13. <body>
  14. <form action="<%= base_path %>LoginServlet" method="post">
  15. <table align="center">
  16. <tr>
  17. <td>
  18. 账号:
  19. </td>
  20. <td>
  21. <input type="text" name = "username">
  22. </td>
  23. </tr>
  24. <tr>
  25. <td>
  26. 密码:
  27. </td>
  28. <td>
  29. <input type="password" name = "password">
  30. </td>
  31. </tr>
  32. <tr >
  33. <td >
  34. <input type = "submit" value="登录">
  35. </td>
  36. <td >
  37. <input type = "reset" value="重置">
  38. </td>
  39. </tr>
  40. </table>
  41. </form>
  42. </body>
  43. </html>