曦远 (DealiAxy)一份私人的文字刊物

StarBlog
返回文章列表折页手记阅读全文
Java

JavaWeb Development --- Creating a Servlet Program with IDEA

Preface Due to recent project needs, I switched from PHP and Python, which I was previously familiar with, to JavaWeb, so I made these notes. The resource images all come from online sources; I summarized and organized them based on my own actual operations. Required Tools JDK Tomcat IDEA Creating the Project Set the project name: After creation, the project structure is as follows: The images above were copied from the internet. It seems that the IDEA 2017.3.2 I use doesn't have this Create web.xml option. I don't know why—could it be that IDEA the more

曦远 (DealiAxy)约 21 分钟
目录25 个章节

Preface

Due to recent project needs, I switched from PHP and Python, which I was previously familiar with, to JavaWeb, so I made these notes. The resource images all come from online sources; I summarized and organized them based on my own actual operations.

Required Tools

  • JDK
  • Tomcat
  • IDEA

Creating the Project

Set the project name:

After creation, the project structure is as follows:

The images above were copied from the internet. It seems that the IDEA 2017.3.2 I use doesn't have this Create web.xml option. I don't know why—could it be that the more IDEA is updated, the more its features regress? As shown below:

So here I have to configure IDEA myself to add web.xml. Steps: Open Project Structure, select the nested web under facets or select web under Modules. In the deployment Descriptors panel, click the + sign to select web.xml and the version number. Then in the dialog that pops up, modify the default xml directory by adding web, and that will do.

Then confirm, and you'll have the web.xml file. As shown:

Web Project Settings

Creating the classes and lib Directories

Right-click under the WEB-INF directory, New --> Directory, and create the two directories classes and lib

The classes directory is used to store compiled class files, and lib is used to store dependent jar packages

Configuring the classes Directory

File --> Project Structure..., enter the Project Structure window, click Modules --> select the project “JavaWeb” --> switch to the Paths tab --> check “Use module compile output path”, and change both “Output path” and “Test output path” to the previously created classes directory

That is, the class files compiled later will be generated in the classes directory by default

Configuring the lib Directory

Still in this Project Structure window. Click Modules --> select the project “JavaWeb” --> switch to the Dependencies tab --> click the “+” on the right, select “JARs or directories...”, and select the created lib directory.

Select Jar Directory

Configuring the Packaging Method Artifacts

Click the Artifacts tab. IDEA will automatically create a packaging method named “JavaWeb:war exploded” for this project, meaning it is packaged as a war package in an exploded (file-expanded) form. The output path is the out folder under the current project; keep the default. Also check “Build on make”, which means it packages and deploys at compile time, and check “Show content of elements”, which means it displays a detailed content list.

Tomcat Configuration

Creating a Tomcat Container

Run -> Edit Configurations, enter the “Run Configurations” window, click "+"-> Tomcat Server -> Local, to create a new Tomcat container.

Configuring the Server Name and Path

Enter a new service name in "Name", click “Configure...” after “Application server”, the Tomcat Server window pops up, select the locally installed Tomcat directory -> OK

Run Configuration

In the “Server” tab of the “Run Configurations” window, uncheck “After launch”, set “HTTP port” and “JMX port”, click Apply -> OK. At this point, Tomcat configuration is complete.

JavaWeb Testing

Run Configuration

Run -> Edit Configurations, enter the “Run Configurations” window, select the previously configured Tomcat, click the “Deployment” tab, click “+” -> “Artifact”-> select the Artifact of the created web project... Modify “Application context”-> Apply -> OK Note: The Application context here specifies the root directory of this project. It is the path you use to access the server. For example, if you set JavaWeb here, then the address to access the server is http://localhost:8080/JavaWeb.

Editing the Jsp File

Add the content to display between the body tags in the index.jsp file, then click the green triangle for “Run”

Open a browser and enter: localhost:8080/JavaWeb

At this point, creating and setting up a javaweb project in IntelliJ IDEA is fully complete. Next is writing and running a Servlet in it.

Servlet Implementation

Next I'll record the complete process of how to write a Servlet program until the Servlet program is up and running.

I feel IDEA is still a bit not that smart. Even though Tomcat is clearly configured, it still doesn't automatically import the Servlet packages for me, causing the following error when creating a Servlet in IDEA and using classes such as javax.servlet.http.HttpServlet:

Reason: IntelliJ IDEA did not import the servlet-api.jar jar package; it needs to be imported manually.

Import steps are as follows: Select the project, right-click and choose “Open Modules Settings”, select “Libraries”, click “+”, choose “Java”; in the pop-up window, select the directory where Tomcat is located, find the servlet-api.jar jar package under the lib directory, and the import is done.

Writing the Servlet Source File

Create HelloWorld.java under the src directory, write the following code, and compile it: The code is as follows:

import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import java.io.IOException;  
import java.io.PrintWriter;  
  
public class HelloWorld extends HttpServlet {  
private String message;  
  
    @Override  
    public void init() throws ServletException {  
    message = "Hello world, this message is from servlet!";  
    }  
  
    @Override  
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {  
        //设置响应内容类型  
    resp.setContentType("text/html");  
  
        //设置逻辑实现  
    PrintWriter out = resp.getWriter();  
    out.println("<h1>" + message + "</h1>");  
    }  
  
    @Override  
    public void destroy() {  
    super.destroy();  
    }  
} 

After compilation, you will find that the HelloWorld.class file has been generated under the classes directory

Deploying the servlet

Method 1

Add the following content inside the <web-app> tag of the web.xml file under the WEB-INF directory:

<servlet>  
    <servlet-name>HelloWorld</servlet-name>  
    <servlet-class>HelloWorld</servlet-class>  
</servlet>  
  
<servlet-mapping>  
    <servlet-name>HelloWorld</servlet-name>  
    <url-pattern>/HelloWorld</url-pattern>  
</servlet-mapping>  

Method 2

(Anyway, my own test was unsuccessful) Add in front of the class in the HelloWorld file: @WebServlet("/HelloWorld")

Running the Servlet

Click the Run button

If successfully appears in the console, the Tomcat service has started successfully! Open a browser and enter: localhost:8080/JavaWeb/HelloWorld to view the servlet running status.

Afterword

As someone used to writing PHP and Python, there are still various things to get used to after just switching to Java. Fortunately, Java's syntax is quite similar to C#, which I like writing the most, so it's not too hard to get started. It's just that all the various environment configurations are so troublesome = =...

About

To learn more interesting operations, please follow my WeChat official account: DealiAxy Every article is collected on my blog: blog.deali.cn

_EOF_

JavaWeb Development --- Creating a Servlet Program with IDEA

本文作者:
程序设计实验室
版权声明:
本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!

相关文章

深入Jar包:Gradle构建可执行jar包与访问jar包中文件夹与文件

前言 Java的跨平台功能听起来很诱人可口,号称“Write Once,Run Everywhere”,实际上是“Run Once,Debug Everywhere”... 在实际开发过程中还是会遇到各种各样的坑的,刚刚解决了一系列问题,特地写个文章总结一下。 使用Gradle构建Jar包 感谢万能的Gradle,极大提高了Java开发的生产力~ 在Gradle中生成jar包可以使用官方的插件:a

2022-05-27 · Java · 约 1 分钟

JavaWeb开发---Servlet的生命周期实验

前言 Servlet是运行在服务器端的程序,它的运行状态由Servlet容器(简称容器)来维护。 通常,在容器收到客户对Servlet的请求时,容器会判断这个Servlet是否为第一次被访问,如果是第一次被访问,则会创建一个Servlet实例同时调用该实例的init()方法,进行初始化。 每个Servlet只会被创建一个实例,同时也只会被初始化一次。然后将这个实例一直保存在内存中,对所有的请求进行

2022-05-27 · Java · 约 1 分钟

Java开发:JDK安装和环境配置

前言 环境配置是开发中最基础的部分,不过最近有很多新入坑的同学,都在问怎么安装JDK和配置环境,索性写一篇。 这里要注意一下,在Windows平台和Linux平台下做开发是不同的,Windows平台开发Java需要自己手动配置JDK的环境变量,而大多数Linux都是不需要的,安装了OpenJDK就可以了(可能很多发行版都自带了OpenJDK),这点是比较方便的。 下载Java JDK Window

2023-02-08 · Java · 约 1 分钟

讨论

共 0 条

良言一句三冬暖,恶语伤人六月寒。

加载评论中…