JavaWeb: the first servlet program developed under IntelliJ idea integrated development environment
Step 1: create a project
New Project: first create an empty project (Empty Projcet) named javaweb.
Step 2: create a new module
File --> new --> Module...
What is newly created here is a common Java se Module, which will be automatically placed under the Java Web project. Name: servlet01.
Step 3: turn the Module into a Java EE Module
Turn the module into a webapp module. Comply with webapp specification. Module conforming to Servlet specification.
- Right click on the Module: Add Framework Support
- In the pop-up window, select Web Application (webapp support is selected)
- After selecting the webapp support, IDEA will automatically generate a webpp directory structure that conforms to the Servlet specification.
Key points: in the IDEA tool, there is a web directory in the directory generated according to the Web Application template, which represents the root of webapp
Step 4: (not required): there is an index.jsp file in the resources generated according to the Web Application. Here I choose to delete this index.jsp file.
Step 5: write a Servlet (StudentServlet)
class StudentServlet implements Servlet
There is no Servlet.class file, CATALINA_HOME/lib/servlet-api.jar and jsp-api.jar are added to the classpath (the classpath here refers to the classpath of IDEA)
File -- > Project structrue -- > modules -- > + Plus -- > Add jars
Implement five methods in the jakarta.servlet.Servlet interface.
Step 6: write business code in the service method in the Servlet (connect to the database)
Implement StudentServlet class:
package com.lhr.javaweb.servlet; import jakarta.servlet.Servlet; import jakarta.servlet.ServletException; import jakarta.servlet.ServletRequest; import jakarta.servlet.ServletResponse; import jakarta.servlet.ServletConfig; import java.io.IOException; import java.io.PrintWriter; import java.sql.*; public class StudentServlet implements Servlet{ public void init(ServletConfig config) throws ServletException{ } public void service(ServletRequest request,ServletResponse response) throws ServletException , IOException{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); // Write JDBC code, connect to the database and query all student information. Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try{ // Register driver (com.mysql.jdbc.Driver, this is out of date.) // In the new version, it is recommended to use the com.mysql.cj.jdbc.Driver driver. Class.forName("com.mysql.cj.jdbc.Driver"); // Get connection String url = "jdbc:mysql://localhost:3306/student"; String user = "root"; String password = "luhaoran2001"; conn = DriverManager.getConnection(url,user,password); // Gets the precompiled database operation object String sql = "select no,name from t_student"; ps = conn.prepareStatement(sql); // Execute SQL rs = ps.executeQuery(); // Process query result set while(rs.next()){ String no = rs.getString("no"); String name = rs.getString("name"); //System.out.println(no + "," + name); out.print(no + "," + name + "<br>"); } }catch(Exception e){ e.printStackTrace(); }finally{ // Release resources if(rs != null){ try{ rs.close(); }catch(Exception e){ e.printStackTrace(); } } if(ps != null){ try{ ps.close(); }catch(Exception e){ e.printStackTrace(); } } if(conn != null){ try{ conn.close(); }catch(Exception e){ e.printStackTrace(); } } } } public void destroy(){ } public String getServletInfo(){ return ""; } public ServletConfig getServletConfig(){ return null; } }
Here you can add the related configuration of mysql database:
Establish student database and t_student table, insert four pieces of data.
To view the contents of a table:
Step 7: create a new subdirectory: lib under the WEB-INF directory, and put the driver jar package connected to the database into the Lib directory.
Complete the registration of the StudentServlet class in the web.xml file. (the request path corresponds to the Servlet)
<?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>studentServlet</servlet-name> <servlet-class>com.bjpowernode.javaweb.servlet.StudentServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>studentServlet</servlet-name> <url-pattern>/servlet/student</url-pattern> </servlet-mapping> </web-app>
Step 9: give an HTML page and write a hyperlink in the HTML page. The user clicks the hyperlink and sends a request. Tomcat executes the background StudentServlet.
The student.html file cannot be placed inside the WEB-INF directory, but outside the WEB-INF directory.
Contents of student.html file:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>student page</title> </head> <body> <!--The project name here is /xmm ,Unable to get dynamically. Write to death first--> <a href="/xmm/servlet/student">student list</a> </body> </html>
Step 10: let the IDEA tool associate the Tomcat server. In the process of association, webapp is deployed to Tomcat server.
- In the upper right corner of the IDEA tool, there is an Add Configuration on the right of the small green hammer
- The plus sign in the upper left corner, click Tomcat server -- > local
- Set the parameters of the Server in the pop-up interface (basically do not move)
- There is a Deployment in the current window (click this to deploy webapp). Continue to click the plus sign to deploy.
- Modify the Application context to: / xmm
Step 11: start Tomcat server
There is a green arrow or a green bug in the upper right corner. Click the green bug to start the Tomcat server in the debug mode.
be careful:
At this time, an error is reported during the operation, which is the problem of Apache Tomcat's permission in the mac. The solution is to find the directory of Tomcat (under the terminal):
# sudo chmod -R755 apache-tomcat-10.0.12
The startup interface is as follows:
Step 12: open the browser and enter in the browser address bar: http://localhost:8080/xmm/student.html
The demonstration results are as follows:
Congratulations on completing your first servlet program.