servlet 基础>创建Maven Web项目>实例
第一步:打开Idea软件
1>写一个类继承HttpServlet
1 package com.werner.app.controller; 2 3 import javax.servlet.ServletException; 4 import javax.servlet.http.HttpServlet; 5 import javax.servlet.http.HttpServletRequest; 6 import javax.servlet.http.HttpServletResponse; 7 import java.io.IOException; 8 import java.io.PrintWriter; 9 10 /** 11 * Servlet开发基本步骤 12 * 1>写一个类继承HttpServlet 13 * 2>重写doGet或者doPost 方法 14 * 3>在web.xml中注册 注册Servlet 15 * 4>发布应用 16 */ 17 public class FirstServlet extends HttpServlet { 18 /** 19 * key=value& 20 * @param req 21 * @param resp 22 * @throws ServletException 23 * @throws IOException 24 */ 25 @Override 26 //1 27 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 28 String page = req.getParameter("page");//10 29 String size = req.getParameter("size");//20 30 //可以调数据库的内容 31 //去数据库查询到数据之后 32 //返回前端 33 String msg = "我想大声告诉你"; 34 resp.setContentType("text/html;charset=utf-8"); 35 PrintWriter writer = resp.getWriter(); 36 writer.write( 37 "<html lang=\"en\">\n" + 38 "<head>\n" + 39 " <meta charset=\"UTF-8\">\n" + 40 " <title>Title</title>\n" + 41 "</head>\n" + 42 "<body>\n" + 43 "<p>"+msg+"</p>\n" + 44 "</body>\n" + 45 "</html>"); 46 } 47 48 49 @Override 50 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 51 super.doPost(req, resp); 52 } 53 54 @Override 55 protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 56 super.doPut(req, resp); 57 } 58 59 @Override 60 protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 61 super.doDelete(req, resp); 62 } 63 }
2>重写doGet或者doPost 方法(见上面代码)
3>在web.xml中注册 注册Servlet
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <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"> <display-name>Archetype Created Web Application</display-name> <servlet> <servlet-name>first</servlet-name> <!--包名+类型--> <servlet-class>com.werner.app.controller.FirstServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>first</servlet-name> <url-pattern>/first</url-pattern> </servlet-mapping> </web-app>
4>发布应用
插录:
基本配置: