Day 4 of learning java web (November 10, 2021)
1, The implementation can easily start the Tomcat server by tapping the command startup.bat on cmd
It's very troublesome for us to start Tomcat now. We need to find startup.bat in its home directory, and then double-click it. We hope that wherever cmd is opened in the future, Tomcat can be started by entering the command startup.bat.
Now enter:
to configure:
1. Configure the home directory of tomcat in the environment variable of Path:
D:\install\apache-tomcat-10.0.12\apache-tomcat-10.0.12\bin
2,
After this error is found, you need to configure:
Go to the system variable and create a new one: CATALINA_HOME
3. Now it is found that there are garbled Codes:
Locate the configuration file under the conf Directory: logging.properties
Modification: changed to GBK
Enter startup.bat again
2, Summarize the knowledge points of relevant servlets:
Servlet knowledge points:
1. Who writes these specific Servlet classes, then who writes the mapping relationship between the request path and which class to call.
2. Now the interface specification of Servlet has been written by a group of people from sun company.
Tomcat server has also been installed. We java web programmers only need to write specific Servlet classes and corresponding mapping files.
For java web programmers, we only need to do two things:
1. Write a class to implement the Servlet interface
2. Write a configuration file and specify the relationship between the request path and the class name in the configuration file.
be careful:
All the code in Tomcat has been written, so we can't mess up and put the name and location of the configuration file.
The name and location of the configuration file are specified by sun company and are details in the Servlet specification.
Strictly speaking, Servlet is not a simple interface:
The Servlet specification specifies:
1. What kind of directory structure should a qualified web application have
2. How should the configuration file be written when developing a qualified web application
3. Where should the configuration file of a qualified web application be placed.
4. Where should java programs be placed when developing a qualified web application.
These are specified in the Servlet specification.
Tomcat server should follow the Servlet specification, and java web programmers should also follow this specification. Only in this way can the developed webapp be decoupled from Tomcat server.
Sending data from the browser to the server to call the request;
Send data from the server to the browser for a response.
3, Develop a Web application with Servlet program
1. Create a new directory called crm in webapps
2. Create a new directory under crm Directory: WEB-INF
The name of this directory must be this.
3. Create a new directory called classes under the WEB-INF directory. It must be this directory. Stored here is the bytecode file compiled by the java program.
4. Create a new directory called lib under the WEB-INF directory. This directory is not required. However, if you need to introduce third-party jars into your web project, you need to put the jar package under this directory. For example, the driver package required to connect to the database. This is also the Servlet specification
5. Create a new file under the WEB-INF Directory: web.xml
Note that this file must be called web.xml, and the location must be in the WEB-INF directory. In this configuration file, the mapping relationship between the request path and the servlet class is written. It's best to copy this from other webapps. Don't write it yourself.
This is the most basic content in web.xml.
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="https://jakarta.ee/xml/ns/jakartaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd" version="5.0" metadata-complete="true"> </web-app>
6. Write a java applet. This applet cannot be developed at will. This applet must implement the Servlet interface.
Q: the Servlet interface was developed by sun company. Where is it?
The Servlet is not in the JDK, because the Servlet is not a javaSE, but a data javaEE, which belongs to another set of class libraries.
As mentioned earlier, Tomcat is written in pure java language, and it also implements the servlet interface, so there should be a servlet jar package under Tomcat's lib
Q: what is the full class name of this servlet interface?
Unzip the jar:
The tomcat we downloaded is version 10.0. This version of tomcat supports the specification of Java ee9. Its package name is not javax.servlet, but jakarta.servlet
Note: Oracle donated javaEE to Apache, which will not be called javaE, but jakarta
After upgrading Java ee8, it is not called Java ee9, but Jakarta ee9
The full class name of the Servlet interface corresponding to javaEE8 is javax.servlet.Servlet
Now when it comes to Jakarta 9, the full class name becomes jakarta.servlet.Servlet
The current version of Tomcat10 + only knows jakarta.servlet.Servlet. I don't know javax.
If you still use javax.servlet, you need to use Tomcat 9 or below
Important: starting from Jakarta ee9, the full name of the Servlet interface has changed: jakarta.servlet.Servlet
7. You can write java source code anywhere, but the bytecode file compiled by the source code needs to be placed in classes.
code:
package com.rtl.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; public class HelloServlet implements Servlet{ public void init(ServletConfig config) throws ServletException{ } public void service(ServletRequest servletRequest, ServletResponse servletResponse)throws ServletException,IOException{ System.out.println("My First Servlet,Hello Servlet!!!"); } public void destroy(){ } public String getServletInfo(){ return ""; } public ServletConfig getServletConfig(){ return null; } }
Compile this class:
javac -d . HelloServlet.java
When an error is found, it says that the jar package Servlet cannot be found:
terms of settlement:
New system variable
Add environment variables
CLASSPATH=D:\install\apache-tomcat-10.0.12\apache-tomcat-10.0.12\lib\servlet-api.jar
Re open a cmd
Compiled successfully:
This folder will be added under this path:
Because this package is defined when writing source code.
8. Now copy the entire com folder to the classes directory under the WEB-INF directory. Because classes is dedicated to bytecode files.
9. Write the configuration information in the web.xml file. Map the request path to the full class name of the HelloServlet.
The specialty is called register Servlet
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="https://jakarta.ee/xml/ns/jakartaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd" version="5.0" metadata-complete="true"> <servlet> <servlet-name>aaabbbccc</servlet-name> <servlet-class>com.rtl.servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>aaabbbccc</servlet-name> <url-pattern>/ascac/acac/acsa</url-pattern> </servlet-mapping> </web-app>
10. Start typing the URL in the browser's address bar to call our own HelloServlet applet
http://localhost:8080/crm/ascac/acac/acsa
The current situation is: if the browser does not refresh once, this sentence will be printed on cmd and the service() method will be executed.
Note: the request path on the browser cannot be written casually. The request path must be consistent with the URL pattern in the web.xml file. There is no need to write the project name in URL pattern.
The path written in the browser is too long and complex, so you can use hyperlinks.
Note: html files can only be placed outside the WEB-INF directory.
Create a new web page, place a hyperlink in it, and click the whole hyperlink to execute the Servlet applet.
Click the hyperlink Servlet, and service() will be called and printed on the Tomcat console.
Note: you can omit the IP and port in the form of writing hyperlink, but you must have the project name.
In the future, we don't need to write the main method. The tomcat server is responsible for calling the main method. When the tomcat server starts, it executes the main method. We java web programmers only need to write the implementation class of the Servlet interface and register it in the web.xml file.
Now you can only find the bin of Tomcat's home directory. Double click startup.bat to start Tomcat. This is very troublesome. We hope to start Tomcat by entering startup directly under any path of cmd
What is the process for the browser to send a request to the final server to call the Servlet method?
1. The user enters a URL or clicks a hyperlink http://localhost:8080/crm/ascac/acac/acsa
2. Then the Tomcat server receives the request and intercepts the path / crm/ascac/acac/acsa
3. Tomcat found the crm web app
4. Find the Servlet corresponding to the url / ascac/acac/acsa in the web.xml configuration file
com.rtl.servlet.HelloServlet
5. The Tomcat server creates the object of this class through reflection
6. The server calls the service method of this object.
General directory structure of webapp project:
1,apachetomcat
2,webapps
3. Project Name: crm
4,
5,WEB-INF
Previously, our service printed that sentence on the Tomcat console. Now it is ready to be displayed on the browser. How do I get this?
1. Find this index.html, which is the help document for Jakarta 9
2. Find help for ServletResponse:
Use the second parameter ServletResponse in the service() method
PrintWriter out = servletResponse.printWriter();
The resulting output stream out can be responsible for outputting some text from the server to the browser. Moreover, this output stream does not need to be refreshed and closed. These are maintained by Tomcat.
Source code of the whole HelloServlet Code:
package com.rtl.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; public class HelloServlet implements Servlet{ public void init(ServletConfig config) throws ServletException{ } public void service(ServletRequest servletRequest, ServletResponse servletResponse)throws ServletException,IOException{ // System.out.println("My First Servlet,Hello Servlet!!!"); PrintWriter out = servletResponse.getWriter(); out.println("Hello Servlet You are my first servlet"); } public void destroy(){ } public String getServletInfo(){ return ""; } public ServletConfig getServletConfig(){ return null; } }
Due to the modification of the source code, we need to recompile:
Or put the compiled bytecode file into the classes folder.
Start Tomcat server:
Open cmd (Anywhere)
Enter the command: startup.bat
Enter on the browser:
http://localhost:8080/crm/index.html Address access index page
There is a hyperlink in the index page. Clicking the hyperlink will call the service() method in our implementation class HelloServlet.
This is the service() method.
After clicking the hyperlink, the following screen will appear:
This is achieved by printing the data on the browser, not just to the Tomcat console.
Assumption: now that we have realized the output of text in the browser, can we output HTML code?
The answer is yes.
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException,IOException{ // System.out.println("My First Servlet,Hello Servlet!!!"); PrintWriter out = servletResponse.getWriter(); out.println("Hello Servlet You are my first servlet"); out.println("<h1>Hello servlet!!!</h1>"); }
First attempt:
We found that it didn't achieve the effect we wanted.
We also need to be in the service () method
Set the type of response content to text or html through the response of the second parameter
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException,IOException{ servletResponse.setContentType("text/html") // System.out.println("My First Servlet,Hello Servlet!!!"); PrintWriter out = servletResponse.getWriter(); out.println("Hello Servlet You are my first servlet"); out.println("<h1>Hello servlet!!!</h1>"); }
do it again:
compile:
Now you can output the HTML file to the browser.
Note: the code for setting the type of response content needs to be placed in front of getWriter.
The HTML language is transmitted with Chinese:
How to connect to the database in the Servlet?
Write the java code of JDBC directly in the servlet.
Previous preparations:
1. Create database servlet
2. Create table t_student
3. Add four pieces of data to the table
Create a new java class
StudentServlet
package com.rtl.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.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; public class StudentServlet implements Servlet{ public void init(ServletConfig config) throws ServletException{ } public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException,IOException{ servletResponse.setContentType("text/html"); PrintWriter out = servletResponse.getWriter(); Connection conn = null ; PreparedStatement ps =null ; ResultSet rs = null; try{ Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/servlet?useSSL=false"; String user = "root"; String password = "root"; conn = DriverManager.getConnection(url,user,password); String sql = "select no,name from t_student"; ps = conn.prepareStatement(sql); rs = ps.executeQuery(); while (rs.next()){ String no = rs.getString("no"); String name = rs.getString("name"); System.out.println("no="+no+",name="+name); out.print("no="+no+",name="+name+"<br>"); } }catch (Exception e){ e.printStackTrace(); }finally { if(conn!=null){ try { conn.close(); }catch(Exception e){ e.printStackTrace(); } } if(ps!=null){ try { ps.close(); }catch(Exception e){ e.printStackTrace(); } } if(rs!=null){ try { rs.close(); }catch(Exception e){ e.printStackTrace(); } } } } public void destroy(){ } public String getServletInfo(){ return ""; } public ServletConfig getServletConfig(){ return null; } }
Try to print a copy of the found data to the tomcat console and output it on the browser
We have created a new Servlet implementation class. At this time, we need to edit web.xml to map the relationship between the request path and the class.
Add the database connection jar package into the lib directory.
Modify index.html
Note: these two places have changed
It was written as follows:
If the mysql connector of lib package in WEB-INF is changed to version 8.0.27, you can write the new version of class name when loading the driver package:
Add cj
After extracting the jar package:
Recommended for new version:
com.mysql.jdbc.cj.Driver
Summarize several paths:
In the web.xml file
You don't need to write the project name in the URL pattern.
When you write href in a hyperlink, you need to write the project name.
Use the development tools of IDEA to develop Servlet programs:
1. Create an Empty Project
2. Then create a new Module under the empty project
Create a new ordinary module
This is a very common javaSE project.
How to turn this ordinary javaSE project into a javaEE project?
1. Module servlet01 right click:
After selecting this, IDEA will intelligently help me generate a directory structure of webapp that conforms to Servlet specification.
Important note: in the IDEA tool, there is a web directory in the directory generated according to the selected Web Application template, which represents the root of webapp.
What does root mean?
For example, the root of project crm is here:
The root of the project oa is here:
Peer relationship:
4. The automatically generated index.jsp file is deleted.
5. Write StudentServlet.java to implement Servlet
However, we found that there is no jar package of Servlet in JDK.