As I learn more and more things, I can’t guarantee to master so much knowledge very well. Therefore, I hope I can learn to write blog in the process of learning, and record the problems and skills I meet in the process of learning.
To get to the point, servlets are one of the things that web developers can’t get away from. My understanding of servlets is that the browser accesses Java code on the server via a URL.
Task: Configure a simple Servlet and access it through a browser.
Eclipse:
- Create a New Java project, TestProject
- Add JAR package support for servlets
The jar package for the servlet is available in the Tomcat lib directory, called servlet-api.jar
- Write Servlet: HelloFirstServlet (send text to the browser: Hello World!)
public class HelloFirstServlet extends HttpServlet{ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub super.doGet(req, resp); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<h1>Hello World!</h1>"); out.println("</body>"); out.println("</html>"); out.close(); } }Copy the code
- Deploy the project to Tomcat
Go to tomcat’s application directory (Webapps)
1. Create a new folder myServlet
2. Create the WEB-INF directory in the folder
3. Create a classes directory in the WEB-INF directory to store the resource classes used in the project
4. Then find the compiled helloFirstservlet. class file in Eclipse, in your working directory, and copy it to the Classes folder.
5. Locate the web. XML file in the Webapps folder, place it in the WEB-INF directory, and open the edit file.
I’ll give you the object code directly below :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_3_1.xsd" version = "3.1" metadata-complete="true"> <servlet> <servlet-name>hello</servlet-name> <servlet-class>HelloFirstServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> </web-app>Copy the code
Then start tomcat, and enter: http://localhost:8080/myservlet/hello
Success: Hello World!