The Servlet of actual combat
Generally in the actual project development, is the use of inheritance HttpServlet class method to achieve the Servlet program.
Implementation steps:
- Create a Web project to import Servlet dependencies
- Write a class to implement the HttpServlet class
- Override the doGet or doPost methods based on business needs
- Configure the Servlet access address in web.xml.
1. Create a Web project and import Servlet dependencies
How do I add Web components to a project?
Project right click ->Add Framework Support…
–> Select the Web application
The Servlet rely on
< the dependency > < groupId > javax.mail. Servlet < / groupId > < artifactId > javax.mail. The servlet API - < / artifactId > < version > 3.1.0 < / version > </dependency> <! -- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api --> <dependency> < < the groupId > javax.mail. Servlet. JSP/groupId > < artifactId > javax.mail. Servlet. JSP - API < / artifactId > < version > 2.3.3 < / version > </dependency>Copy the code
Write a class that inherits HttpServlet
3. Override the doGet or doPost method as required
public class MyServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1. String method = req.getParameter("method"); If (method.equals("add")) {req.getSession().setAttribute(" MSG "," executed the add method "); } if (method.equals("delete")) {req.getSession().setAttribute(" MSG "," execute delete method "); Req. GetRequestDispatcher ("/ web-INF/JSP /test.jsp").forward(req,resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); }}Copy the code
4. Configure the Servlet access address in web. XML
<? The 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 > hello < / servlet - name > <! --> <servlet-class> com.bewind.myservlet </servlet-class> </servlet-class> </ servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <! -- Welcome page --> <! --<welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list>--> </web-app>Copy the code
Configuring the Server
See the Tomcat of actual combat
Normal execution
The above code no request so visit http://localhost:8080/ServletCombat_war_exploded/hello
complains