Http protocol, Tomcat, servlet

HTTP protocol
Http, Hypertext Transfer Protocol is the most widespread network protocol on the Internet, and all www files must comply with this standard.
Http protocol consists of http request and http response
http request:
1. Request line
Request methods POST, GET, PUT, DELETE, etc.
Requested resource/DemoEE/form.html
Protocol version http/1.1
2. Request header
cookie cookie information cached by the browser
User-Agent client browser and operating system related information
Connection keeps the connection state Keep-Alive In the connection, close has been closed.
Host The requested server hostname
Content-Length The length of the request
If Content-Type is a Post request, this header will be used. The default value is application/x-www-form-urlencodeed, which means that the requested content is url-encoded.
Accept The browser can MIME type, a description of the file type. Such as: text/html, text/css, text/javascript, iamge/*
Accept-Encoding Data compression formats supported by browsers such as GZIP compression
Accept-Language The languages ​​supported by the browser
3. Request body
Post request method: The request experience is determined by the requested parameters such as username=1&password=2
Get request method: The request parameters will not appear in the request weight, but will be spliced ​​after the url xxx.jsp?username=1&password=2
 
Http response:
1. Response line
Http status code 200 (successful request), 302 (request redirection), 304 (requested resource has not changed, access local cache), 404 (requested resource does not exist), 500 (server internal error)
2. Response header
When Location 302, specify the path of the response.
Content-Type Type of response body MiMe type
Set-Cookie server writes a cookie to the browser
Compression format used by the Content-Encoding server
Content-length response body length
Refresh Refresh periodically. Which url to call in a few seconds
Server server name
Last-Modified file last modification time
3. Response body
The server returns the page body to the browser, the browser loads the body into memory, and then renders and parses it for display.
 
B/S Browser/Server browser side
C/S Client/Server Client
Static resources: html pages, data will not change.
Dynamic resources: pages that write programs, such as asp, php.
 
Tomcat
Tomcat Apache open source free small and medium web application server
Click tar.gz to download windows to download 64-bit windows zip
 
Tomcat's directory structure
bin script directory
conf configuration directory
lib depends on the jar library directory
logs log directory
temp temporary file directory
webapps web application publishing directory
work tomcat working directory for jsp processing
 
bin script directory
Windows executes the .bat version and mac executes the .sh version
Startup script: startup.sh
Stop script: shuntdown.sh
 
conf configuration file directory
Core configuration file: server.xml
User rights configuration file: tomcat-users.xml
The default configuration file for all web projects: web.xml
 
open terminal
1. cd into the root directory
2. Execute sh bin/startup.sh to start the server
3. Browser input localhost:8080
 
Put a website in webapps and enter the URL/folder name to access
localhost:8080/myProject
 
Common reasons for startup failure:
1. Port conflict
server.xml
Find the Connector element and modify the port attribute to change the port number
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
2. The java_home environment variable is not configured
 
servlet
Servlet is a small java program running on the server side, which is a set of specifications (interfaces) provided by sun company to process client requests and response operations.
 
Servlet life cycle
1. init(ServletCOnfig config) is executed when the servlet is initialized
2.service(ServletRequest request,ServletResponse response) will be executed every time
3.destroy() is executed when the servlet is destroyed
 
1. Idea configuration
1. Create a new web application project Idea and select Java Enterprise -> web application
2. The new version does not have a web-inf folder. The solution is to enter project structure -> facets-> click the small plus sign and add web.xml
3. Create two new folders in the web/WEB-INF directory, classes are used to store the bytecode files (.class) of the servlet, and lib is used to store the packages referenced by the project.
4. Enter Project Structure, enter the Modules (IDEA project) tab, and change the two output paths of Paths to the classes created in step 2.
5. Then click Dependencies, select the + sign on the right, create a new JARS path, and select the lib folder created in step 2 -> Jar Directory
6. Go to the Artifacts tab and set the output directory to the new project folder under webapps of the Tomcat installation location
7.Run->Edit Configurations configure Tomcat, set tomcat port and other information.
8. Set the default startup path http://localhost:9999/servlet/ or enter it manually
 
2. Create a class and implement the Servlet interface rewrite method
public class QuickStartServlet implements Servlet {
@Override
public void init(ServletConfig servletConfig) throws ServletException {
System.out.print("init running..");
}
 
@Override
public ServletConfig getServletConfig() {
System.out.print("getServletConfig running..");
return null;
}
 
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.print("service running..");
}
 
@Override
public String getServletInfo() {
System.out.print("getServletInfo running..");
 
return null;
}
 
@Override
public void destroy() {
System.out.print("destroy running..");
}
}
3. Configure the web.xml file
<?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">
<!-- corresponding class -->
<servlet>
<servlet-name>QuickStartServlet</servlet-name>
<servlet-class>com.david.servlet.QuickStartServlet</servlet-class>
</servlet>
<!-- access path-->
<servlet-mapping>
<servlet-name>QuickStartServlet</servlet-name>
<url-pattern>/QuickStartServlet</url-pattern>
</servlet-mapping>
</web-app>
 
Browser input http://localhost:9999/servlet/ QuickStartServlet access
 
ServletContext context object
<servlet>
<servlet-name>QuickStartServlet</servlet-name>
<servlet-class>com.david.servlet.QuickStartServlet</servlet-class>
<init-param>
<param-name>name</param-name>
<param-value>david</param-value>
</init-param>
</servlet>
Added init-param node to use Context context object to obtain node information
public void init(ServletConfig config) throws ServletException {
String servletName = config.getServletName();
System.out.println(servletName);
String initParameter = config.getInitParameter("name");
System.out.println(initParameter);
}
 
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
Default home page list
 
httpServlet
httpServlet implements the servlet interface and implements servlet methods.
The service method implemented in the parent class inherited by httpServlet determines whether it is a get request or a post request and then executes the doGet or doPost method
 
public class QUickStartServletExtends extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
response.getWriter().write("doget..." + username + "pass:" + password);
}
 
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.getWriter().write("dopost...");
}
}
 
HttpServletResponse
response.setStatus(302); //Set the status code
 
//add response header
response.addHeader("name","zhangsan");
response.addIntHeader("age",18);
response.addDateHeader("date",System.currentTimeMillis());
 
//modify existing response headers
response.setHeader("name","lisi");
response.setIntHeader("",0);
response.setDateHeader("",0L);
 
Redirect:
response.setStatus(302);
response.setHeader("Location","/servlet/QuickStartServlet");
方法:response.sendRedirect("/servlet/QuickStartServlet");
 
set response body
//set encoding
response.setCharacterEncoding("gb2312");
PrintWriter writer = response.getWriter();
writer.write("<h1>试试printwriter</h1>");
 
byte output stream
ServletOutputStream st = response.getOutputStream();
 
HttpServletRequest
When creating a servlet, the service method or doGet and doPost methods will be rewritten. These methods have two parameters, one is the request request and the other is the response response.
The request type in the service method is ServletRequest, and the request type of the doGet and doPost methods is HttpServletRequest, which is a sub-interface of ServletRequest.
1. Get the request line through request
String method = request.getMethod();
String uri = request.getRequestURI();
StringBuffer url = request.getRequestURL();
String contextPath = request.getContextPath();
 
//get request parameters
String param = request.getQueryString();
 
PrintWriter writer = response.getWriter();
writer.println("method:" + method);
writer.println("uri:" + uri);
writer.println("url:" + url);
writer.println("contextPath:" + contextPath);
writer.println("param:" + param);
 
method:GET uri:/servlet/QUickStartServletExtends url:http://localhost:9999/servlet/QUickStartServletExtends contextPath:/servlet param:name=david&pass=123
 
2. Get the request header through the request
String header = request.getHeader("User-Agent");
System.out.println(header);
Enumeration<String> headerNames= request.getHeaderNames();
while(headerNames.hasMoreElements()){
String headerName = headerNames.nextElement();
writer.println(headerName);
 
String headerValue = request.getHeader(headerName);
writer.println(headerValue);
}
 
3. Get the request body through request
 
// get the specified parameters
String name = request.getParameter("name");
String pass = request.getParameter("pass");
writer.println(name);
writer.println(pass);
 
// get multiple values
String[] parms = request.getParameterValues("checkbox");
for(String s : parms){
writer.println(s);
}
 
// get all request parameter names
Enumeration<String> paramsNames = request.getParameterNames();
while(paramsNames.hasMoreElements()){
writer.println(paramsNames.nextElement());
}
 
//Get a collection of all parameter key-value pairs
Map<String,String[]> maps = request.getParameterMap();
for(Map.Entry<String,String[]> entry : maps.entrySet()){
writer.println(entry.getKey());
for(String s : entry.getValue()){
writer.println(s);
}
writer.println("-------");
}
 
The difference between address forwarding and 302 redirection is that the address does not change
RequestDispatcher dis = request.getRequestDispatcher("/path");
dis.forward(request,response);
 
 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325536861&siteId=291194637