1. 程式人生 > >搭建第一個javaweb應用

搭建第一個javaweb應用

Tomcat的安裝配置

        下載下來的壓縮包    

        

解壓後的目錄結構

檢驗tomcat是能夠正常執行,進入bin目錄,雙擊startup.bat即可啟動tomcat,啟動後在瀏覽器的位址列輸入http:localhost:8080/,然後回車即可。可以看到類似介面

這說明tomcat在正常工作。接下來就是要講tomcat配置到我們的eclipse開發工具,如果不會請訪問

環境已經搞定了,廢話不說了,現在就開始搭建我們的第一個javaweb應用吧開啟eclipse,依次點選File,New,Dynamic Web Project

填寫你的專案名稱,這裡需要注意下專案的名稱後面不能加空格,然後點選next


得到如下圖,點選next


勾選,點選Finish


下面就是建立好的javaweb專案的目錄結構,如下圖,框住的是我們主要寫程式碼的地方


在src資料夾下建立新的class檔案,右擊src,然後依次選擇,點選Servlet


得到如下圖,點選下一步


繼續下一步


點選完成


我們將得到如下結果


點選生成的檔案,寫程式碼,原始碼如下

package servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class HelloService
 */
@WebServlet("/HelloService")
public class HelloService extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HelloService() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setAttribute("message", "Hello javaWeb");
request.getRequestDispatcher("index.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
然後在WebContent資料夾下建一個index.jsp檔案
<?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>首頁</title>
</head>
<body>
	<div align="center">
		${message }
	</div>


</body>
</html>

執行專案,選中專案,點選Run on Server


伺服器啟動開後,在瀏覽器的位址列輸入http://127.0.0.1/8080/HelloWeb/HelloService,得到如下介面,說明你的第一個簡單的javaWeb就已經完成了!!!


有不明白的地方歡迎給我留言,我一定儘量解答!!!!