Home Java javaTutorial A brief introduction to Java Servlet programs

A brief introduction to Java Servlet programs

Jul 19, 2022 pm 01:46 PM
java

本篇文章给大家带来了关于java的相关知识,其中主要整理了Servlet的相关问题,Servlet运行在服务端(tomcat)的java程序。是sun公司的一套规范,就是动态资源,用来接收客户端的请求,处理请求,响应给浏览器的动态资源,下面一起来看一下,希望对大家有帮助。

A brief introduction to Java Servlet programs

推荐学习:《java视频教程

Servlet运行在服务端(tomcat)的java程序。是sun公司的一套规范,就是动态资源。

Servlet作用

用来接收客户端的请求,处理请求,响应给浏览器的动态资源。

但Servlet本质就是java代码,通过java的API动态的向客户端传输数据内容。

Servlet与普通的java程序的区别

1,必须实现Servlet接口

2,必须在servlet容器(tomcat服务器)中运行

3,servlet程序可以接收用户请求的参数以及向浏览器输出数据。

Servlet接口并不是JDK中的接口,所以我们需要导入jar包。javaweb项目是在WEB-INF/lib目录中存放jar包。tomcat是一个库,里面有Servlet的jar包,所以我们可以不用在lib目录中导入了。通过maven也可以依赖。

怎么通过浏览器访问Servlet呢?

可以通过配置web.xml映射路径,使用场景:不是自己写的Servlet,或者jar包中的Servlet,你没法在别人写的代码上加注解,所以就得使用配置web.xml映射路径的方式去使用别人写的servlet.

  <servlet>
         <!--自定义,一般为类名-->
         <servlet-name>servletDemo1</servlet-name>
         <!--一定是package + .类名-->
         <servlet-class>day08_servlet.ServletDemo1</servlet-class>
     </servlet>
     <!--给Servlet提供(映射)一个可供客户端访问的URI-->
     <servlet-mapping>
         <!--和servlet中的name必须相同-->
         <servlet-name>servletDemo1</servlet-name>
         <!-- servlet的映射路径 -->
         <!-- 全路径匹配/servlet 或者/*通配符匹配 或者扩展名匹配*.do-->
         <url-pattern>/servlet</url-pattern>
     </servlet-mapping>
Copy after login

第二种方式@WebServlet注解。自己写的Servlet通过注解@WebServlet方式比较方便

@WebServlet(name = "helloServlet", value = "/hello-servlet")
Copy after login

Servlet生命周期:

1,默认是第一次有请求访问这个servlet的时候创建,创建出来之后会将这个Servlet的对象存储到tomcat容器当中。

2,当服务关闭时,Servlet对象才会销毁

Servlet生命周期方法:

1,init()会在Servlet初始化出来的时候使用,会调用一次

能否配置Servlet在服务器启动的时候就创建呢?

可以在web.xml中配置,例如DefaultServlet(静态资源访问)就是在tomcat的配置文件中配置好了

 如果不用配置文件配置可以使用@WebServlet注解中的loadOnStarup配置。

2,service()会在Servlet接收到请求时候调用

3,destroy()会在servlet对象被销毁之前调用

ServletConfig对象的介绍;用于获取servlet配置时候的初始化参数的


idea新建一个Servlet快捷方式

 HttpServletRequest

 请求转发:只能转发到项目类的路径,并且浏览器端url不跳转,原理是服务器请求转发

request.getRequestDispatcher("/test.jsp").forward(request, response);

如果一个资源在WEB-INF目录下,只能使用请求转发才能访问到

request作为域对象,可以在不同的Servlet之间进行数据共享,但是它只能在同一次请求中进行数据共享。

 HttpServletResponse

 HttpServletResponse详解_平庸的俗人的博客-CSDN博客_httpservletresponse

向客户端写数据

        //用字符流向浏览器输出文本
        PrintWriter writer = response.getWriter();
        //write()方法只能输出字符串,如果输入int,float等类型,则会有问题
        writer.write("嘻嘻");
        //println方法可以输出纯数字,字符串
        writer.println(88);

        //1.获取字节输出流
        ServletOutputStream sos = response.getOutputStream();
        //2.输出数据
        sos.write("hello你好".getBytes("utf-8"));
Copy after login

ServletContext作用

作为域对象存取数据,让Servlet共享,所有的请求都可以进行数据共享

ServletContext servletContext = getServletContext();
servletContext.setAttribute("username","zhangsan");
servletContext.getAttribute("username");
Copy after login

 获得文件的MIME类型(文件下载)

ServletContext servletContext = getServletContext();
servletContext.getMimeType("文件名");
Copy after login

获得全局初始化参数

获得web资源路径,可以将web资源转换为字节输入流

@WebServlet(name = "Test2Servlet", value = "/Test2Servlet")
public class Test2Servlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /**
         * 把文件转成流的几种方式
         */
        //方式一
        FileInputStream fileInputStream = new FileInputStream("E:\\java重新学习\\demo\\src\\main\\webapp\\2222.jpg");

        //方式二,使用类加载器将文件转换成流
        //只能读取到resources目录下面的文件,
        //resources是类路径,编译后的路径classes。
        //Test2Servlet.class.getClassLoader()类加载器默认能找到类路径(classes)
        //如果你要找webapp下路径的文件得../../
        InputStream resourceAsStream = Test2Servlet.class.getClassLoader().getResourceAsStream("2222.jpg");

        //使用ServletContext可以获取webapp里面资源的真实路径
        ServletContext servletContext = getServletContext();
        String realPath = servletContext.getRealPath("2222.jpg");
        //然后通过真实路径
        FileInputStream fileInputStream1 = new FileInputStream(realPath);
        //或者servletContext是webapp路径
        InputStream resourceAsStream1 = servletContext.getResourceAsStream("2222.jpg");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
Copy after login

在web项目中,将文件转换成流,通常使用这两种方式:

1,如果文件在resources中,就使用类加载器

2,如果文件在webapp目录下,就使用ServletContext 

ServletContext介绍及用法_白衬衫丶的博客-CSDN博客_servletcontext

推荐学习:《java视频教程

The above is the detailed content of A brief introduction to Java Servlet programs. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles