创建一个maven项目
1.File --> new --> Poject新建项目
2.选中Maven,选中Create from archetype 如图选择webapp,点击next创建项目
3.创建一个类继承HttpServlet,重写doGet()和doPost()方法
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter writer = resp.getWriter();
writer.print("HelloServlet");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
4.配置web.xml文件,编写Servlet映射
为什么需要映射,因为我们需要通过浏览器访问,而浏览器需要连接web服务器,所以我们需要在web服务器中注册我们写的servlet,还需要给他一个浏览器能够访问的路径。
5.配置Tomcat,如下图所示
如果点击加号中没有Artifact,解决方法如下:File -->Project Structure -->Artifacts -->点击加号 --> Web Application Exploded --> From Modules中选择项目即可。
如果存在Artifact,添加并设置Application context
6.最后的测试