1、:配置好相应环境和检查tomcat8.5能否运行,详见https://www.cnblogs.com/LJHAHA/p/10461697.html
2、将tomcat8.5下的webapps目录中所有内容备份到另一文件夹(bak)中,再清空webapps目录;
3、进入eclipse,配置好相应环境后,进入Servers,点击下方红色圈处,将tomcat8.5集成到eclipse中;
4.选择新建一个Apache下的Tomcat v8.5 Server--->Finish
5.双击红色圈出的Tomcat v8.5 Server at localhost,进入上方的设计页面,其余的不做更改,需要将Server Locations改选为第二项Use Tomcat installation,同时检查下方路径是否正确,最好将Deploy path改为tomcat8.5下自带的webapps,最后别忘了点击保存;
6.新建一个Dynamic Web Project(名为prj1),在Java Resources->src目录下新建一个包,名为edu.lsnu.first,在该包下新建一个HelloServlet类,编辑以下内容;
1 package edu.lsnu.first; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 6 import javax.servlet.Servlet; 7 import javax.servlet.ServletConfig; 8 import javax.servlet.ServletException; 9 import javax.servlet.ServletRequest; 10 import javax.servlet.ServletResponse; 11 12 public class HelloServlet implements Servlet{ 13 14 public static void main(String[] args) { 15 } 16 17 @Override 18 public void destroy() { 19 } 20 21 @Override 22 public ServletConfig getServletConfig() { 23 return null; 24 } 25 26 @Override 27 public String getServletInfo() { 28 return null; 29 } 30 31 @Override 32 public void init(ServletConfig arg0) throws ServletException { 33 } 34 35 @Override 36 public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { 37 response.setContentType("text/html;charset=utf-8"); 38 PrintWriter out = response.getWriter(); 39 out.print("<h1>欢迎光临</h1>"); 40 out.close(); 41 } 42 43 }
7.接下来,再进入web->MEB_INF目录下,点开web.xml文件,编辑以下内容;
1 <?xml version="1.0" encoding="UTF-8"?> 2 <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"> 3 <display-name>prj1</display-name> 4 <servlet> 5 <servlet-name>HelloServlet</servlet-name> 6 <servlet-class>edu.lsnu.first.HelloServlet</servlet-class> 7 </servlet> 8 9 <servlet-mapping> 10 <servlet-name>HelloServlet</servlet-name> 11 <url-pattern>/hello</url-pattern> 12 </servlet-mapping> 13 14 <welcome-file-list> 15 <welcome-file>index.html</welcome-file> 16 <welcome-file>index.htm</welcome-file> 17 <welcome-file>index.jsp</welcome-file> 18 </welcome-file-list> 19 </web-app>
编译器的最终布局显示如下:
8.点击Tomcat v8.5 Server at localhost,右键选择Add and Remove...,将项目prj1添加到Tomcat中来;
9.启动服务器;
成功后会显示下图情况
10.最后在浏览器中输入http://127.0.0.1:8080/prj1/hello或http://localhost:8080/prj1/hello,回车即可出现网页