1 Basic Concepts
1.1 C/S architecture
C/S architecture (client/server mode) is an early software architecture and a very common one. The feature of this architecture is that the business to be handled is reasonably distributed to the client and server. The client is responsible for interaction with users, while the server is responsible for data management.
Advantages are:
- The client interface and functionality can be very rich
- The load on the application server is light
- Fast response
The disadvantage is that:
- Narrow application area, fixed user groups
- Maintenance and upgrade costs are high, and once updated, all clients need to be upgraded
1.2 B/S architecture
B/S architecture (browser/server mode), the rise of the Internet to the software architecture, the characteristics of this structure is the business function to achieve the main business logic on the server side, only few the business logic of the need to deal with the client, the same browser is responsible for the interaction with the user task, and be responsible for the management of the data browser.
Advantages are:
- You don’t need to install a client, just have a browser
- Wide range of application, user groups are not fixed
- Through the permission control to achieve the purpose of multi-client access, interactive
- Low maintenance and upgrade costs, no need to update all clients
The disadvantage is that:
- The application server is overloaded
- The interface and functionality of the browser can be as rich as that of the client
- Unsatisfactory cross-browser and cumbersome to adapt
1.3 JavaWeb
Web is the original meaning of web pages, indicating the resources on the Internet for external access, and the resources on the Internet for external access are mainly divided into:
-
Static resources: The data in a Web page for people to browse is constant
-
Dynamic resources: The data in a Web page for people to browse is generated by the program, and different points of time to visit the page will see different content
JavaWeb refers to the Java language for dynamic Web resource development technology collectively, is to solve the related Web Internet domain technology sum
1.4 the HTTP protocol
HTTP (Hypertext Transfer Protocol) is an application-layer protocol used to regulate the data format for communication between the browser and the server. It mainly involves the format of the browser’s sending request and the server’s response.
The default HTTP port is 80, and the default HTTPS port is 443. The following describes the HTTP request and HTTP response formats.
HTPP request format: A client sends an HTTP request to the server. The request message consists of the request line, request header, blank line, and request body.
Request line Description Request type, resource to be accessed, and time to be used HTTP version. The format of the HTTP version is as follows: Request type Version of the request path Protocol The request header is the key or value following the request line. Host request length A blank line is an empty line in the request header. Even if the following request data is empty, the request body must be empty, and any other data can be addedCopy the code
The instance
GET/sample. JspHTTP / 1.1 Accept: image/GIF image/jpeg, * / * Accept - Language: useful - cn Connection: Keep Alive - Host: localhost The user-agent: Mozila / 4.0 (compatible; MSIE5.01; The Window NT5.0) Accept - Encoding: gzip, deflate the username = jinqiao&password = 1234Copy the code
HTTP response format: After receiving and processing the request from the client, the server returns an HTTP response message, including the response line, response header, blank line, and response body.
The response line describes the HTTP version number, status code, and status message in the following format: Protocol version status code Status information Response header Specifies additional information to be used by the client. Format (Key,value) Blank lines are empty lines in the response header. Blank lines must be empty even if the following response data is emptyCopy the code
The instance
HTTP/1.1 200 OK Server:Apache Tomcat/5.0.12 Date:Mon,6Oct2003 13:23:42 GMT Content-Length:112 Content-Type:text/ HTML Last-Moified:Mon,6 Oct 2003 13:23:42 GMT Content-Length:112 /Users/bijinxiong/Tomcat/binCopy the code
2 Tomcat Server
Tomcat server is a lightweight Web application server. It is widely used in small and medium sized systems and small concurrency situations. It is the first choice for developing and debugging Servlet and JSP programs.
After installing the Tomcat server, take a look at the directory structure:
- Bin Stores binary executable files
- Conf stores various configuration files
- Lib stores jar packages that need to be loaded when Tomcat is running
- Logs Stores log files generated during Tomcat running
- Temp Stores temporary files generated when Tomcat is running
- Webapps stores applications that will be loaded when Tomcat starts
- Work holds compiled files for Tomcat at runtime, such as compiled files for JSP
3 The concept and use of Servlets
Servlet is short for Java Servlet, called small service program or service connector. It is a server-side program written in Java language. Simply speaking, Servlet is a Java class running on the server.
Servlet is used to complete the response processing of client requests under B/S architecture, that is, interactive browsing and generating data, generating dynamic Web content.
Servlet programming steps:
- Set up a Java Web Application project and configure the Tomcta server
- Custom classes implement the Servlet interface or inherit HttpServlet(recommended) and override the Service method
- Configure the custom information to the web.xml file and start the project as follows:
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.bjx.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
Copy the code
The browser can be accessed as follows:
http://localhost:8080/ Project name /url-patternCopy the code
3.1 the Servlet interface
The java.servlet. servlet interface defines the methods that all servlets must implement. Common methods are as follows:
Method statement | Function is introduced |
---|---|
void init(ServletConfig con) | Called by the servlet container to indicate to the servlet that the servlet is being put into the service |
void service(ServletRequest req,ServletResponse res) | Called by the servlet container to allow the servlet to respond to requests |
ServletConfig getServletConfig() | Returns a ServletConfig object that contains the initialization and startup parameters for this servlet |
String getServletInfo() | Returns information about servlets |
void destroy() | Called by the servlet container to indicate to the servlet that the servlet is exiting the service |
3.2 GenericServlet class
The GenericServlet class mainly defines a generic, protocol-independent Servlet that implements the Servlet interface. The common methods are:
Method statement | Function is introduced |
---|---|
abstract void service(ServletRequest req,ServletResponse res) | Invocation by the servlet container allows the servlet to respond to requests |
3.3 the HttpServlet class
The HttpServlet class is abstract and inherits the GenericServlet class. It is used to create HTTP servlets suitable for various websites. Subclasses of this class override at least one method (service method).
Method statement | Function is introduced |
---|---|
void doGet(HttpServletRequest req,HttpServletResponse resp) | Process client GET requests |
void doPost(HttpServletRequest req,HttpServletResponse resp) | Process client POST requests |
void inti() | Initialization is performed |
void service(HttpServletRequest req,HttpServletResponse resp) | Call the doGet or doPost method depending on the request |
void destroy() | Resources are freed when instances are deleted |
3.4 Servlet life cycle
The constructor is called only once, when the Servlet is first requested to create the Servlet instance
The init method is also called only once, immediately after the Servlet instance is created to initialize the Servlet
The service method can be called multiple times, each time a request is made to respond to the request
The deStory method is called only once, before the Web application in which the Servlet instance resides is uninstalled, to release the currently occupied resources
3.5 POST and GET Requests
GET requests will only appear in:
- Enter the URL in your browser and press Enter
- Click the < a> hyperlink
- Click the Submit button to submit the < Form Method =”get”> form
GET requests add request data to the end of the REQUEST URL, only a small amount of data can be submitted, and are not secure
POST requests will only appear in:
- Click the UBmit button to submit the < Form Method =” POST “> form
The characteristics of POST requests are as follows: Request data is added to the HTTP protocol body, and a large amount of data can be submitted with good security
3.6 ServletRequest interface
The ServletRequest interface is primarily used to provide client request information to servlets, from which any request information can be retrieved.
The Servlet container creates a ServletRequest object and passes the object as a parameter to the Servlet’s service method. Common methods for the ServletRequest interface are as follows:
Method statement | Function is introduced |
---|---|
String getParameter(String name) | Returns the value of the request parameter as a string, null if it does not exist |
String getParameterValues(String name) | Returns an array of string objects containing all the values that a given request parameter has |
Enumeration getParameterNames() | Returns an enumeration of string objects containing the names of the parameters contained in this request object |
Map<String,String> getParameterMap() | Returns a key-value pair of the request parameter. One key can correspond to multiple values |
String getRemoteAddr() | Returns the IP address of the last proxy of the client that sent the request |
int getRemotePort() | Returns the port number of the last proxy on the client that sent the request |
3.7 it interface
The HttpServletRequest interface is a word interface of the ServletRequest interface. It is used to provide HTTP request information.
Unlike form data, the HTTP request header is set directly by the browser when an HTTP request is sent
The ServletRequest object provides a set of get methods to retrieve the header data:
Method statement | Function is introduced |
---|---|
String getRequestURI() | Returns the resource path information for this request |
StringBuffer getRequestURL() | Returns the full path information for this request |
String getMethod() | Returns the name of the HTTP method that made the request, such as GET |
String getQueryString() | Returns the parameters attached to the request following the path |
String getServletPath() | Returns the path portion of the servlet that this request invoked |
3.8 ServletResponse interface
The ServletResponse interface is used to define an object to help the Servlet send a response to the client.
The Servlet container creates a ServletResponse object and passes it as a parameter to the Servlet’s service method. Common methods for ServletResponse are as follows:
Method statement | Function is introduced |
---|---|
PrinWriter getWriter() | Returns a PrintWriter object that sends character text to the client |
String getCharacterEncoding() | Gets the encoding of the response content |
void setContentType(String type) | If the response has not been submitted, set the content type to be sent to the client for the response. The content type can include character encoding specifications, such as text/ HTML; charset=UTF-8 |
3.9 the HttpServletResponse interface
The HttpServletResponse interface inherits the ServletResponse interface to provide HTTP-specific functionality when sending a response, often as follows:
Method statement | Function is introduced |
---|---|
void sendRedirect(String location) | Sends a temporary redirect response to the client using the specified redirect location URL |
4 The Servlet receives Chinese garbled characters
Cause: The browser automatically encodes Chinese parameter values when submitting a form. When the Tomcat server receives a browser request, it automatically decodes it. When the encoding and decoding methods are inconsistent, garbled characters will be generated.
Resolve garbled characters received in POST
Accept set before encoding formats: request. SetCharacterEncoding ("utf-8"Note: Request. GetParameter ("name") before settingCopy the code
Resolve GET receive garbled characters
String name=request.getParameter()"name"); // The Chinese string in the GET request was received
String username=new String(name.getBytes("ISO-8859-1"),"utf-8");// Re-encode Chinese characters, default isO-8859-1
Copy the code
5 ServletConfig interface
The ServletConfig interface is used to describe configuration information about the Servlet itself, which is passed to the Servlet configuration object during initialization
Example of configuration mode:
<servlet>
<servlet-name>ConfigServlet</servlet-name>
<servlet-class>com.bjx.ConfigServlet</servlet-class>
<init-param>
<param-name>key</param-name>
<param-value>value</param-value>
</init-param>
</servlet>
Copy the code
Common methods:
Method statement | Function is introduced |
---|---|
String getServletName() | Returns the alias of the Servlet |
String getInitParameter(String name) | Returns a string containing the value of the initialization parameter |
Enumeration getInitParameterNames() | Returns the name of the servlet’s initialization parameter as an enumeration of the string object |
ServletContext getServletContext() | Returns a reference to the ServletContext in which the calling method is executing |
6 the ServletContext interface
The ServletContext interface is primarily used to define a set of methods that a servlet uses to communicate with its servlet container.
The server container creates a unique ServletContext object for each project at startup, which enables communication and information sharing between multiple servlets
The ServletContext object is obtained in the Servlet using the this.getServletContext() method
Configure the ServletContext initialization parameter in web.xml
<context-param>
<param-name>username</param-name>
<param-value>bi</param-value>
</context-param>
<context-param>
<param-name>password</param-name>
<param-value>666666</param-value>
</context-param>
Copy the code
Common methods for the ServletContext interface:
Method statement | Function is introduced |
---|---|
String getInitParameter(String name) | Returns a string containing the value of the initialization parameter |
Enumeration getInitParameterNames() | Returns the name of the servlet’s initialization parameter as an enumeration of the string object |
String getRealPath(String path) | Returns a string containing the actual path for the given virtual path |
String getContextPath() | Returns the main path associated with this context |
InputStream getResourceAsStream(String path) | Returns the resource at the specified path as an InputStream object |
voud setAttribute(String name,Object object) | Binds the specified property name and value to the current object |
Object getAttribute(String name) | Gets the property value based on the name of the property executed |
void removeAttribute(String name) | Deletes the specified attribute name information |