Servlet学习日记(一)——什么是Servlet及手动编写一个简单的servlet

1.什么是Servlet?
Servlet是在服务器上运行的小程序,一个Servlet就是一个java类,这个java类使用了Java Servlet应用程序设计接口(API)及相关类和方法。除了Java Servlet API,Servlet还可以使用用以扩展和添加到API的Java类软件包。客户端(浏览器)可以通过“请求—响应”来访问驻留在服务器的Servlet小程序。
2.手工编写一个一个简单的servlet
手工编写servlet有三个步骤:

  1. 创建一个java类并且继承HttpServlet
  2. 重写doGet()或者doPost()方法
  3. 在web.xml里注册servlet

核心代码:
index.jsp
在jsp页面里添加一个a标签

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>

  <body>
    <a href="servlet/MyServlet">doGet</a>
  </body>
</html>

servlet代码:

public class MyServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        System.out.println("doGet");
        PrintWriter out = response.getWriter();
        out.println("<h1>hello doGet</h1>");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>MyWeb</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>


  <servlet>
        <servlet-name>MyServlet</servlet-name>
        <servlet-class>servlet.MyServlet</servlet-class>
  </servlet>
  <servlet-mapping>
        <servlet-name>MyServlet</servlet-name>  
        <url-pattern>/servlet/MyServlet</url-pattern>
  </servlet-mapping>
</web-app>

启动服务器,通过a标签的链接,对应到web.xml文件里的servlet-mapping中的url-pattern,然后找到对应servlet的名字,再通过名字找到了处理该请求的servlet类。
最后附上效果图:
这里写图片描述

这里写图片描述

猜你喜欢

转载自blog.csdn.net/luqiren/article/details/73477732