步骤如下:
1. jdk已经下载,配置好了。这个属于java的基础知识,这里我就不介绍了,不了解的,自己找资料。
2.下载一个tomcat,建议到官网下。解压成文件夹。
3.在window->perferences->service->runtime environment如图:
4.新建一个web项目,特别是选择版本上最好选择2.5,刚开始我选择3.0的版本就无法访问页面。
5.新建一个servlet文件,内容如下:
package com.course1.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class FirstServlet */ public class FirstServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public FirstServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println("<html><body><h1>欢迎 servlet and jsp!</h1>"); out.println("</body></html>"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub this.doGet(request, response); } }
web.xml配置文件如下:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <servlet> <servlet-name>First</servlet-name> <servlet-class>com.course1.servlet.FirstServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>First</servlet-name> <url-pattern>/FirstServlet</url-pattern> </servlet-mapping> </web-app>
6.给项目添加服务器:
在servers中添加服务器,然后选择你自己的项目,在点击右键,选择start选项
7.注意web.xml文件一定要写正确,不然会报错。
在http://localhost:8080/项目名/FirstServlet就可以了。
时间: 2024-10-05 20:18:05