Eclipse開發Web專案入門篇
阿新 • • 發佈:2019-01-04
前言:以前一直使用myeclipse 8 開發web,今天特意使用eclipse,所以在這小記一下,一來有需要的可以參考下,二來隨手做個筆記備用
1.開發環境的搭建
1.1.開發工具
JDK:jdk1.6.0_17Web Server:apache-tomcat-6.0.37
IDE:eclipse-jee
1.2.搭建開發環境
由於選擇IDE作為開發的工具,IDE可以手動配置需要的外掛工具,所以搭建開發環境變得簡單而又快捷。(1)安裝JDK
提示:安裝完JDK之後需要配置環境變數。(2)安裝tomcat
提示:如果是解壓縮版直接解壓就ok,如果是安裝版需要根據安裝提示完成安裝。因為是使用IDE做開發,所以就不需要配置tomcat的環境變量了,不過還是建議不要太依賴於IDE了。(3)解壓縮Eclipse
提示:如果沒有安裝JDK就無法完成Eclipse的安裝。好了,到這裡開發環境就準備好了,接下來用一個demo來演示一下如何在Eclipse中開發Web專案。
2.開發Web專案
2.1.新建Web專案
Eclipse-->File-->New-->Dynamic Web Project,如圖1:圖1 如果沒有或者Eclipse-->File-->New-------->Web-->OtherDynamic Web Project,如圖2、3:
圖2 圖3
選擇Target runtime下的New Runtime配置Web Server
Next>
通過Browse選擇tomcat的安裝目錄
Finish>
之後,一路Next直到Finish就oK了
新建的Web專案結構如下
2.2.開發Servlet
在Project Explorer檢視的src上右鍵可以選擇New——>ServletNext>……
選擇重寫service方法,這樣可以自動生成程式碼方便一點
當然也可以全手動的編寫Servlet,不過不要忘記在web.xml中配置Servlet,呵呵^_^
然後Finish就完成了Servlet的建立
HelloServlet.java的原始碼如下
package com.lanyoung.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class HelloServlet
*/
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public HelloServlet() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Hello JSP");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
demo的程式碼就是這樣簡單,呵呵^_^2.3.釋出Web專案
Web專案建立好了,接下來的工作就是在Web Server中釋出Web專案Window——>Show Views——>Servers
在Servers檢視的空白區域右鍵
New——>Server
Finish之後就可以在Servers下啟動tomcat了
啟動tomcat之後會在Console下打印出很多tomcat的啟動資訊
如果沒有異常出現,表示demo釋出成功
即使出現警告資訊也沒有關係
在瀏覽器中訪問http://localhost:8080/HelloWorld/HelloServlet
如果沒有出現異常資訊,並且在Console中輸出
Hello JSP
表示Servlet測試成功 ^_^
只是做了一個特別簡單的demo,說明問題就oK
2.4.開發JSP
在WebContent目錄下新建JSP FileNext>之後就直接Finish
index.jsp的原始碼如下
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Hello JSP</h1>
</body>
</html>
重新部署demo專案就可以看到效果了