没有配置好 IntelliJ IDEA 14.03 + Tomcat 的同学先看这篇文章:
IntelliJ IDEA 14.x 与 Tomcat 集成,创建并运行Java Web项目
首先按照上文所讲正确配置 IntelliJ IDEA 14.03 + Tomcat,配置好以后新建的项目结构如图所示:
(没有运行过的class文件夹是空的,运行过后class文件夹里面才会有.class文件)
自动建立的web.xml文件如图:
在<web-app>标签中插入<servlet>标签、<servlet-mapping>标签,如图:
代码:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <servlet> <servlet-name>Servlet</servlet-name> <servlet-class>Servlet.MyServlet</servlet-class> //<servlet-class>中的内容是固定的,必须是"Servlet所在包的名称.Servlet类的名称" </servlet> <servlet-mapping> <servlet-name>Servlet</servlet-name> <url-pattern>/Servlet/MyServlet</url-pattern> </servlet-mapping> </web-app>
新建的四个标签中servlet-class标签的内容是固定的,不能随意修改
servlet-name标签中的内容自定,但两个servlet-name标签中的内容必须相同
url-pattern标签中的内容自定,如例子中url-pattern为 /Servlet/MyServlet ,tomcat端口(默认)为8080,
则启动项目后,在浏览器中输入http://localhost:8080/Servlet/MyServlet,即可访问到servlet所定义的页面
注:
1.
url-pattern可定义多个,可以使不同的url指向同一页面:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <servlet> <servlet-name>Servlet</servlet-name> <servlet-class>Servlet.MyServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Servlet</servlet-name> <url-pattern>/Servlet/MyServlet</url-pattern> <url-pattern>/A</url-pattern> </servlet-mapping> </web-app>
则在浏览器地址栏输入http://localhost:8080/A 可以跳转到相同的页面
2.
一个最简单的servlet类(未定义编码方式):
package Servlet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; /** * Created by Administrator on 2015/3/22. */ @WebServlet(name = "MyServlet") public class MyServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out=response.getWriter(); //准备输出 out.println("<html>"); out.println("<head><title>JAVA WEB</title></head>"); out.println("<body>"); out.println("<h1>Hello World</h1>"); out.println("</body>"); out.println("</html>"); out.close();//关闭输出 } }