Servlet

servlet体系结构 一、servlet体系结构图 二、servlet/jsp的网络拓扑图 三、Servlet的开发流程(以Tomcat为例,纯手工建立) 1、在%TOMCAT_HOME%\webapps下WEB-INF的文件夹建立classes、lib目录,classes目录存放编译后的文件,lib目录存放要用到的外部库文件,另外创建一个很重要的文件:web.xml。we 阅读详情

1. Basic Servlet Structure

Here's the outline of a basic servlet that handles GET requests. GET requests, for those unfamiliar with HTTP, are requests made by browsers when the user types in a URL on the address line, follows a link from a Web page, or makes an HTML form that does not specify a METHOD. Servlets can also very easily handle POST requests, which are generated when someone creates an HTML form that specifies METHOD="POST". We'll discuss that in later sections.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SomeServlet extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
      
    // Use "request" to read incoming HTTP headers (e.g. cookies)
    // and HTML form data (e.g. data the user entered and submitted)
    
    // Use "response" to specify the HTTP response line and headers
    // (e.g. specifying the content type, setting cookies).
    
    PrintWriter out = response.getWriter();
    // Use "out" to send content to browser
  }
}
(Download template source code -- click with the right mouse on the link or hold down SHIFT while clicking on the link.)

To be a servlet, a class should extend HttpServlet and override doGet or doPost (or both), depending on whether the data is being sent by GET or by POST. These methods take two arguments: an HttpServletRequest and an HttpServletResponse. The HttpServletRequest has methods that let you find out about incoming information such as FORM data, HTTP request headers, and the like. The HttpServletResponse has methods that lets you specify the HTTP response line (200, 404, etc.), response headers (Content-Type, Set-Cookie, etc.), and, most importantly, lets you obtain a PrintWriter used to send output back to the client. For simple servlets, most of the effort is spent in println statements that generate the desired page. Note that doGet and doPost throw two exceptions, so you are required to include them in the declaration. Also note that you have to import classes in java.io (for PrintWriter, etc.), javax.servlet (for HttpServlet, etc.), and javax.servlet.http (for HttpServletRequest and HttpServletResponse). Finally, note that doGet and doPost are called by the service method, and sometimes you may want to override service directly, e.g. for a servlet that handles both GET and POST request.

2. A Simple Servlet Generating Plain Text

Here is a simple servlet that just generates plain text. The following section will show the more usual case where HTML is generated.

2.1 HelloWorld.java

You can also download the source or try it on-line.
package hall;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    out.println("Hello World");
  }
}

2.2 Compiling and Installing the Servlet

Note that the specific details for installing servlets vary from Web server to Web server. Please refer to your Web server documentation for definitive directions. The on-line examples are running on Java Web Server (JWS) 2.0, where servlets are expected to be in a directory called servlets in the JWS installation hierarchy. However, I placed this servlet in a separate package ( hall) to avoid conflicts with other servlets on this server; you'll want to do the same if you are using a Web server that is used by other people and doesn't have a good infrastructure for "virtual servers" to prevent these conflicts automatically. Thus, HelloWorld.java actually goes in a subdirectory called hall in the servlets directory. Note that setup on most other servers is similar, and the servlet and JSP examples in the tutorial have also been tested using BEA WebLogic and IBM WebSphere 3.0. WebSphere has an excellent mechanism for virtual servers, and it is not necessary to use packages solely to prevent name conflicts with other users.

If you've never used packages before, there are two main ways to compile classes that are in packages.

One way is to set your CLASSPATH to point to the directory above the one actually containing your servlets. You can them compile normally from within the directory. For example, if your base directory is C:/JavaWebServer/servlets and your package name (and thus subdirectory name) is hall, and you were on Windows, you'd do:
  DOS> set CLASSPATH=C:/JavaWebServer/servlets;%CLASSPATH%
  DOS> cd C:/JavaWebServer/servlets/hall
  DOS> javac YourServlet.java
The first part, setting the CLASSPATH, you probably want to do permanently, rather than each time you start a new DOS window. On Windows 95/98 you'd typically put the "set CLASSPATH=..." statement in your autoexec.bat file somewhere after the line that set the CLASSPATH to point to servlet.jar and jsp.jar. On Windows NT, you'd go to the Start menu, select Settings, select Control Panel, select System, select Environment, then enter the variable and value. Note also that if your package were of the form name1.name2.name3 rather than simply name1 as here, you'd still have the CLASSPATH point to the top-level directory of your package hierarchy (the one containing name1).

A second way to compile classes that are in packages is to go to the directory above the one containing your servlets, and then do "javac directory/YourServlet.java" (Windows; note the backslash) or "javac directory/YourServlet.java" (Unix; note the forward slash). For example, suppose again that your base directory is C:/JavaWebServer/servlets and your package name (and thus subdirectory name) is hall, and you were on Windows. In that case, you'd do the following:
  DOS> cd C:/JavaWebServer/servlets
  DOS> javac hall/YourServlet.java
Note that, on Windows, most JDK 1.1 versions of javac require a backslash, not a forward slash, after the directory name. This is fixed in JDK 1.2, but since many Web servers are configured to use JDK 1.1, many servlet authors stick with JDK 1.1 for portability.

Finally, another advanced option is to keep the source code in a location distinct from the .class files, and use javac's "-d" option to install them in the location the Web server expects.

2.3 Running the Servlet

With the Java Web Server, servlets are placed in the servlets directory within the main JWS installation directory, and are invoked via http://host/servlet/ServletName. Note that the directory is servlets, plural, while the URL refers to servlet, singular. Since this example was placed in the hall package, it would be invoked via http://host/servlet/hall.HelloWorld. Other Web servers may have slightly different conventions on where to install servlets and how to invoke them. Most servers also let you define aliases for servlets, so that a servlet can be invoked via http://host/any-path/any-file.html. The process for doing this is completely server-specific; check your server's documentation for details.

HelloWorld Servlet Output

3. A Servlet that Generates HTML

Most servlets generate HTML, not plain text as in the previous example. To do that, you need two additional steps: tell the browser that you're sending back HTML, and modify the println statements to build a legal Web page. The first step is done by setting the Content-Type response header. In general, headers can be set via the setHeader method of HttpServletResponse, but setting the content type is such a common task that there is also a special setContentType method just for this purpose. Note that you need to set response headers before actually returning any of the content via the PrintWriter. Here's an example:

3.1 HelloWWW.java

You can also download the source or try it on-line.
package hall;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWWW extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<!DOCTYPE HTML PUBLIC /"-//W3C//DTD HTML 4.0 " +
                                        "Transitional//EN/">/n" +
                "<HTML>/n" +
                "<HEAD><TITLE>Hello WWW</TITLE></HEAD>/n" +
                "<BODY>/n" +
                "<H1>Hello WWW</H1>/n" +
                "</BODY></HTML>");
  }
}

3.2 HelloWWW Result

HelloWWW Servlet Output

4. Simple HTML-Building Utilities

It is a bit cumbersome to generate HTML with println statements. The real solution is to use Java Server Pages (JSP), which is discussed later in this tutorial. However, for standard servlets, there are two parts of the Web page ( DOCTYPE and HEAD) that are unlikely to change and thus could benefit from being incorporated into a simple utility file.

The DOCTYPE line is technically required by the HTML spec, and although most major browsers ignore it, it is very useful when sending pages to formal HTML validators. These validators compare the HTML syntax of pages against the formal HTML specification, and use the DOCTYPE line to determine which version of HTML to check against. Their use is very highly recommended both for static HTML pages and for pages generated via servlets, so the use of DOCTYPE is well worth the effort, especially if it can be easily incorporated into a servlet utilities class.

In many Web pages, the HEAD line contains nothing but the TITLE, although advanced developers may want to include META tags and style sheets. But for the simple case, I'll create a method that takes a title as input and returns the DOCTYPE, HEAD, and TITLE entries as output. Here's the code:

4.1 ServletUtilities.java (Download source code)

package hall;

public class ServletUtilities {
  public static final String DOCTYPE =
    "<!DOCTYPE HTML PUBLIC /"-//W3C//DTD HTML 4.0 Transitional//EN/">";

  public static String headWithTitle(String title) {
    return(DOCTYPE + "/n" +
           "<HTML>/n" +
           "<HEAD><TITLE>" + title + "</TITLE></HEAD>/n");
  }
  
  // Other utilities will be shown later...
}

4.2 HelloWWW2.java (Download source code)

Here's a rewrite of the HelloWWW class that uses this.
package hall;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWWW2 extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println(ServletUtilities.headWithTitle("Hello WWW") +
                "<BODY>/n" +
                "<H1>Hello WWW</H1>/n" +
                "</BODY></HTML>");
  }
}
Servlet的起源以及Servlet到底是什么 详细介绍了Java Web中的Servlet的概念以及Servlet的发展历程。 1 Java Web概述 Java EE全名为Java Platform Enterprise Edition,即Java平台企业版。JavaEE以JavaSE作为语法基础,可以看作一个大的框架,提供了的一系列使用Java语言进行企业级应用开发的组件和API标准,没有提供具体的实现(也就是接口)。比如常见的Servlet、JDBC、EJB、JNDI、Servlet、JSP等等都是它制定的企业级应用程序开发的规范或者标准. 阅读详情

相关推荐

ServletApp

老师布置的期中作业,需要连接数据库,只需利用dos界面打开数据库就可以登录使用了。

三、第一个Servlet

3.1 Servlet基本结构    下面的代码显示了一个简单Servlet的基本结构。该Servlet处理的是GET请求,所谓的GET请求,如果你不熟悉HTTP,可以把它看成是当用户在浏览器地址栏输入URL、点击Web页面中的链接、提交没有指定METHOD的表单时浏览器所发出的请求。Servlet也可以很方便地处理POST请求。POST请求是提交那些指定了METHOD=“POST”的表单时所发出

Leecy 1025

计算机网络之NAT的解释与实验配置

NAT 静态NAT 动态NAT easy_ip NAT服务器映射

爱学习的JackYang的博客 1929

我的第一个 Servlet

第一个 Servlet 首先在 \apache-tomcat-6.0.14\Tomcat 6.0\webapps 目录下建一个 文件夹(firstServlet),接着在 firstServlet文件夹内,创建一个 WEB-INF文件夹,接着在WEB-INF文件夹内创建一个 classes文件夹,这个文件夹用来放java文件的,具体结构是 这个cn 文件夹是编译后 生成的。 \first...

kanwoerzi 184

医学影像处理实战:如何用Python+SimpleITK搞定DICOM/NIfTI重采样(附完整代码)

本文详细介绍了如何使用Python和SimpleITK库实现医学影像(DICOM/NIfTI格式)的智能重采样技术。通过实战代码演示,帮助读者掌握医学图像处理中的关键步骤,包括环境搭建、数据准备、核心算法实现和质量验证,解决医学AI领域中的影像标准化难题。

linux的博客 985

UE5 SplineMesh与StaticMesh性能对比:生成1000米路径的帧率与内存实测

本文深度对比了UE5中SplineMesh与StaticMesh在生成1000米路径时的性能差异,包括帧率、内存占用及实现复杂度。实测数据显示,SplineMesh在Draw Call优化和动态变形场景中表现更优,而StaticMesh适合需要复杂材质变化的场景。文章还提供了优化技巧和选型指南,帮助开发者根据项目需求做出科学决策。

weixin_33976326的博客 321

dos下如何编译servlet

编译servlet,需要相关的包,但是java自身不带,需要我们自己添加,相关的编译需要的包这个包在tomcat的lib里面有,需要的名字是servlet-api.jar 包放的位置有2种: 1.放在java相关的文件中: 如:我的jdk安装在C下的C:\Program Files\Java中: 则servlet-api.jar放在这个C:\Program Files\Java\jdk1.

zfqzpp的专栏 1315

【汽车故障诊断2】从标准到实战:解码DTC格式背后的诊断逻辑

本文深入解析汽车诊断故障码(DTC)的格式与逻辑,对比了OBD-II标准(如ISO 15031-6)的5字符格式与UDS协议(ISO 14229-1)下更丰富的3字节格式。文章从国际标准出发,结合实战案例,阐述了DTC如何作为汽车电子系统的“体检报告”,帮助工程师和维修技师精准定位故障,并详细解读了UDS 19服务如何读取和管理DTC状态。

berry的博客 719

手工编写servlet_MS-DOS编译servlet_Servlet修改后自动载入

(1)手工编写servlet (2)MS-DOS编译servlet (3)Servlet修改后自动载入

吴钦飞 1746

从CCD数据上报看wxHOOK的封号风险与规避

本文深入分析了微信CCD数据上报机制对wxHOOK的检测逻辑与封号风险,揭示了调试器路径暴露、非白名单DLL加载和内存校验失败等关键风险点。通过实战案例和规避方案,帮助开发者理解如何安全使用wxHOOK技术,避免封号风险,包括内存镜像欺骗、内核级隐蔽和硬件辅助方案等高级技巧。

weixin_27875131的博客 644

【DeepSeek R1构建本地RAG知识库】数据结构化清洗-工作流自动清洗

在构建本地RAG知识库时,数据结构化清洗是关键但繁琐的步骤。传统方法效率低且易出错,而低代码/无代码平台如Dify提供了更高效的解决方案。Dify通过可视化工作流设计,集成大模型智能处理,支持多格式输入输出,无需编码即可完成复杂的数据清洗任务。文章详细介绍了数据结构化的核心困境、目标、价值及类型,并比较了TXT与Markdown在RAG系统中的适用性。最后,通过Dify平台实战演示了如何在20分钟内完成规则制度文档的结构化清洗,输出标准化数据,展示了自动化工作流在数据处理中的高效性和便捷性。

少说,多做 1225

什么是servlet ,servlet的作用

什么是servlet ,servlet的作用 1、简单来说servlet是运行在服务器上的java程序 servlet由servlet容器管理,servlet容器也叫 servlet引擎,是servlet的运行环境,给发送的请求和响应之上提供网络服务 2、servlet的作用 通俗来讲servlet专门用来接收客户端的请求,专门接收客户端的请求数据,然后调用底层service处理数据并生成结果 浏...

吴大盖的博客 3万+

YOLO + SubspaceAD:一张良品图,检出所有未知缺陷

当YOLO遇上子空间建模,工业质检正迎来从“见多识广”到“举一反三”的质变时刻。

①答疑群聊服务;②YOLO大模型知识问答系统;③计算机视觉论文生成智能体; 525

Servlet及Tomcat的配置

servlet 动态网页 1、访问web服务器上的某个页面,访问的内容会发生变化 2、动态网页和动态HTML页面的区别 3、动态网页的源文件会随网页的变化而变化,而动态HTML页面的源文件不会发生变化 动态网页程序与引擎 1、首先使用某种编程语言编写出相应的动态网页程序 2、然后由一个专门的web服务程序模块(引擎)来解释执行 3、引擎是动态网页程序和浏览器之间的桥梁 4、浏览器、引擎、API、动...

渣渣瑞 2442

Python控制TEMI1000/TEMI1500测试温箱

该温箱是我司从昆山振弘检测设备有限公司采购的TEMI 1000,但是控制器用的是韩国的,关于控温箱这个项目,可参考的资料仅有一份官方的manual,里面包含一些命令格式。只要你有温箱,就应该可以向厂家索取该文档。该温箱的通讯接口只有一个RS232接口,要想实现远程控制,需要有串口转USB的线;类似于下图所以,想依靠python来与之进行通信,还是要通过python 的pyserial库,关于怎么安装pyserial,过于简单,这里不做赘述,可自行百度。

xgh1951的博客 1万+

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

《Java Servlet编程》笔记(Servlet简介)

         在校图书馆偶看到《JAVA SERVLET编程》(OREILLY)如获至宝,遂借之,转而续借,决心把它好好的看一下。于是便有以下的学习笔记。        这本书共有二十章,分别从现在SERVLET的应用的不同方面对SERVLET的编程进行了讲解,是不一本不错的好书。在下边的笔记里,分别对这二十章进行总结。Java Servlet? VS CGI ===========

null 2145

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

Servlet系列之Servlet3异步

入门案例;

lonelymanontheway的博客 1391

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

Servlet与Servlet、JSP与Servlet的跳转

Servlet与Servlet之间的跳转 Servlet和Servlet之间的跳转,可以通过请求转发来实现,即RequestDispatcher对象的forward方法;也可以使用重定向方法,即HttpServletResponse对象的sendRedirect方法。 ...

lanadelrey13的博客 3413

SERVLET 高效总结

SERVLET 高效总结 一、Servlet简介 Servlet是JavaWeb或者JavaEE基础、学会了servlet, 你就入了Javaweb开发的门。Servlet是sun公司提供的一门用于开发动态web资源的技术。Sun公司提供了一套标准的ServletAPI, Servlet开发有二个步骤(1)书写servlet代码 (2) 部署到应用服务器上(Tomcat等)。同样servlet使用Java语言、具有Java语言的优点,如跨平台。 在文章之前推荐一本工具书--《head first

weixin_42177713的博客 786

java 调用servlet_[Java Servlet]调用 Servlet

要调用 Servlet 或 Web 应用程序,请使用下列任一种方法:由 URL 调用、在 标记中调用、在 标记中调用、在 JSP 文件中调用、在 ASP 文件中调用。1. 由 URL 调用 Servlet这里有两种用 Servlet 的 URL 从浏览器中调用该 Servlet 的方法:(1) 指定 Servlet 名称:当用 WebSphere应用服务器 管理器来将一个 Servlet 实例添...

weixin_30253289的博客 1708

Servlet开发之实现Servlet接口

安装好Tomcat后 在tomcat>lib下面的 这个servlet-apt.jar jar包需要导入到项目中. 第一步、创建java文件并实现Servlet接口: public class Hello implements Servlet{ // 该函数用于初始化该servlet(类似类的构造函数) // 这个函数只会被调用一次 (当用户第一次访问该serv...

weixin_43770982的博客 3480

Servlet 规范笔记—servlet概念及结构

Servlet, 这个词对java程序员并不陌生,我想几乎每个java程序员在学习J2EE知识时,首先学习的就是servlet,这是一种正确的学习方式,在我看来Servlet是J2EE的基础,要熟练的掌握J2EE,必须深刻的了解Servlet的原理,因为你想想,现在只要是web相关的技术或框架,无论是开源的、非开源的,哪个和Servlet没有关系? Spring MVC、Struts、WebW

XTU_xiaoxin的专栏 1万+

什么是Servlet?

大家好,我是IT修真院武汉分院第14期的学员,一枚正直纯洁善良的JAVA程序员。今天给大家分享一下,修真院官网JAVA任务2的知识点——Servlet1.什么是SERVLET?Servlet是用Java编写的服务器端程序, 其主要功能在于交互式地浏览和修改数据,生成动态Web内容. 狭义的Servlet是指Java语言实现的一个接口,广义的Servlet是指任何实现了这个Servlet接口的类,一...

u010420197的博客 3378

Servlet技术简介之 Servlet的配置

总的说来Servlet的配置包括Servlet的名字,Servlet的类(如果是JSP,就指定JSP文件),初始化参数,启动装入的优先级,servlet的映射,运行的安全设置。 下面举例介绍其配置:一个完整的servlet配置如下: Study Servlet Config HelloWorld Config HelloWorld jp.co.

1万+

springboot注册Servlet三大组件【Servlet、Filter、Listener】

注册Servlet三大组件【Servlet、Filter、Listener】 由于SpringBoot默认是以jar包的方式启动嵌入式的Servlet容器来启动SpringBoot的web应用,没有web.xml文件。 注册三大组件用以下方式 ServletRegistrationBean MyServlet extends HttpServlet(){ ... } //注册三大组件 @Be...

qq_41534573的博客 865
上一篇: Introduction to CGI Variables
下一篇: Bitmaps
lemonade
博客等级 码龄26年 8粉丝 33原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值