前提:已经安装好java SDK和Tomcat,并且可以通过http://localhost:8080访问tomcat的默认页面。
首先打开idea建立新项目,在Java Enterprise中选择Web Application。
输入项目hello_world,完成建立,项目文件列表如下图:
在src文件夹上右键,选择New---Servlet
在新建的Servlet.java中输入以下代码:
其中@WebServlet注解的作用和以前web/WEB-INF/web.xml部署描述符的作用一样,urlPatterns表明映射的地址,"/*"为映射http://localhost:8080下的全部地址。
import java.io.*; import javax.servlet.http.*; import javax.servlet.annotation.*; @WebServlet(name = "Servlet", urlPatterns = "/*") public class Servlet extends javax.servlet.http.HttpServlet { private String message = "Hello World"; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<h1>" + message + "</h1>"); } }点击运行,程序会自动打开http://localhost:8080,显示的界面如下:
在学习Servlet中遇到的几个问题:
1.在Servlet需要用到其他jar库的时候,比如MySql的JDBC,在Project Structure中选择Libraries,点击绿色的"+"号添加了之后,还是无法连接。
解决方法:
在Project Structure中有一项Problems,点开,再点fix,选择第一项"Add ... to the artifact"即可。
2.新建一个html文件作为html表单时,想将数据传给Servlet,但是总是提示找不到文件。
解决方法:要将html表单建立在项目的web目录下,在Servlet启动后,就可以正确提交表单数据了。