使用IDEA进行Servlet对象的创建与运行
1.创建一个 JAVA项目:
新建->项目->JAVA模块…
2.输入项目名(以ServletDemo为例)
3.配置Tomcat:
①
②点击“+”->Tomcat Servlet->Local
③
修改Name,查看Tomcat的URL地址:
④点击“deploment”->”+”->“Artifact…”->“确定”
4.点击“文件”->“项目结构”->“模块”->“源码”->点击“Web”->右键“WEB-INF”
5.“新建文件夹” 如下:
6.点击“路径”->选择“使用模块编译输出路径”->把输出路径和测试输出路径全部选到刚才创建的classes的地方
7.点击“依赖”->点击“+”->选择第一个“JARs or directories…”->找到刚才建的lib 的位置->“确定”:
8.选择“Jar Directory”->“确定”:
9.点击“确定”:
10.新建一个Servlet:
在src下面建一个包(例如com.servlet)->右键新建一个类(MyFirstServlet)
示例代码:
package com.servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class MyFirstServlet extends HttpServlet {
private static final long serialVersionUID=1L;
public void init(ServletConfig config)throws ServletException{
super.init(config);
}
public void service(HttpServletRequest request, HttpServletResponse response)throws IOException{
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
out.println("<html><body>");
out.println("第一个Servlet类");
out.println("</body></html>");
}
}
11.配置WEB-INT下的web.xml:
输入代码:
<?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_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>MyFirstServlet</servlet-name>
<servlet-class>com.servlet.MyFirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyFirstServlet</servlet-name>
<url-pattern>/MyFirstServlet</url-pattern>
</servlet-mapping>
</web-app>
12.启动Tomcat,就可以在浏览器中输入Tomcat的URL+”MyFirstServlet”来运行Servlet了!!!
(URL查看方法:点击Tomcat)