1. 程式人生 > 實用技巧 >使用eclipse寫第一個Java_web的hello_world專案

使用eclipse寫第一個Java_web的hello_world專案

1、先建立一個Java_web專案

如果你沒有下載過Tomcat伺服器,不會配置,建議看一下我得這一篇部落格:https://www.cnblogs.com/kongbursi-2292702937/p/11746773.html

我得專案名稱為day02

上面資訊填完之後點next,別點finish

再點next

之後finish就可以,建立完之後如下:

之後建立一個Java類hello_world.java,繼承於GenericServlet

檔案內容如下:

import java.io.IOException;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class hello_world extends GenericServlet { @Override public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { // TODO Auto-generated method stub
res.getOutputStream().write("hello_world".getBytes()); } }

之後配置web.xml檔案,以使得外界可以訪問到這個檔案

這裡給出檔案內容:不需要全部一樣,只要web.xml檔案紅色框內一樣就可以

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation
="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>day02</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>hello_world</servlet-name> <!-- 就是一個名字,沒實際意義 --> <servlet-class>day02.hello_world</servlet-class> <!-- 給出Java檔案位置 --> </servlet> <servlet-mapping> <servlet-name>hello_world</servlet-name> <url-pattern>/hello_world</url-pattern> <!-- 你要對映的地址 --> </servlet-mapping> </web-app>

之後建立一個Tomcat伺服器

點了之後預設就運行了。可以右鍵點選停止或啟動:

啟動Tomcat伺服器之後,開啟網頁訪問127.0.0.1:8080/day02/hello_world

day02就是:

hello_world就是:

完結!!