It is enough to understand JavaWeb,

Source: Internet
Author: User

It is enough to understand JavaWeb,

Java Web cannot be used. This article will show you how Java Web is.

In JavaWeb, the interaction between the client (such as the browser page, which can be seen by the user) and the server (the backend server must have a program to process the information sent from the client) is mainly used.Servlet Container. That is, the front-end application HTML (JSP, etc.) of the web page, and the server response uses Servlet (Java program ).

For example, the following is a Servlet Demo, which inherits HttpServlet and overwrites the doGet and doPost methods. DoPost has two input parameters. req is the request information sent by the client (such as the user name and password), and resp is the response information that the Servlet will send back to the client. In this example, a piece of HTML code is sent back to the client interface, and the customer can see the relevant display information.

 

Important objects of Servlet:

HttpServletResponse Class a) after the client requests the server, the server encapsulates the returned information in the class HttpServletResponse for response. The corresponding status code I .100-199 is carried in the response. The server successfully receives the request, but the client is required to submit the next request to complete the entire process. Ii.200-299: the server has successfully received the request and completed all the processing. Iii.300-399: the client has handed over the requested resources to another Location and provided a new address to the client (specified by the Location field of the corresponding HTTP message header ). Iv.400-499: the client request has an error. (Set using the setError method) v.500-599: an error occurs on the server. Vi. Use setStatus to set various status Response codes. Vii. HttpServletResponse provides a sendRedirect method to set the response code 302 to redirect the client to the URL. B) add and set the Response Headers addHeader and setHeader.

HttpServletRequest Class a) when the client requests a Servlet, the Servlet engine creates an HttpServletRequest object for the Servlet to store the client's request information, when the service method is called, The HttpServletRequest object is passed as a parameter to the service method. B) The HttpServletRequest interface defines several methods to obtain the messages of each part of the request line, such as I. getMethod, and obtain the request methods (such as GET and POST) in the request line ). Ii. getRequestURL: return the resource part. Iii. getQueryString, return parameter section. Iv. C) The HttpServletRequest interface also defines methods for obtaining information related to network connections between clients and servers. I. getRemoteAttr, which returns the IP address used by the client to send the request. Ii. getRemotePort: return the port number of the network interface used by the client. Iii. getLocalAddr: the IP address used by the network interface on the Web server to receive requests. Iv. There are also the client name, server port, server name, and so on. D) the interface also defines request headers for obtaining request messages.

Cookiea) Cookie is a technology used to store information on the client. When a browser accesses a Web resource, the Web server sends a Set of information to the browser through the Set-Cookie field in the HTTP message header. B) the browser determines whether to save these cookies Based on the Cookie data in the Set-Cookie field. When the browser accesses this Web Resource next time, it will automatically read the stored cookies and add them to the Cookie field of the HTTP request message header, the Web server processes the Cookie fields accordingly. C) The Web server can send multiple cookies to a Web browser, but the size of each Cookie is generally limited to 4 kb. D) java. servlet. http. Cookie class to encapsulate a Cookie message. e) Use the addCookie method of HttpServletResponse to send a Cookie to the browser. F) use the getCookies method of HttpServletRequest to read the Cookie information passed by the browser h) the Cookie can only store characters supported by the ISO-8859-1 encoding, if you want to save more complex data in the Cookie, it is encoded in Base64 format.
Sessiona) Cookies are suitable for storing small data volumes and simple data structures. B) store a large amount of data on the server and use SessionID to track the data. This is Session technology. C) use the HttpSession class in the Servlet to describe the Session. An HttpSession object is a Session. D) Use the getSession method of HttpSservletRequest to obtain the HttpSession object. E) The HttpSession contains various methods to operate the Session information, such as: I. getId: returns the current SessionID. ii. setMaxInactiveInterval, getMaxInactiveInterval: Sets and obtains the maximum idle time of the session. When an HttpSession object is not accessed after the maximum time is exceeded, the HttpSession object becomes invalid and the entire session process ends. Iii. getServletContext: returns the ServletContext object of the Web application to which the current session belongs. Iv. F) The objects stored in the ServletRequest object can only be accessed by the requested Servlet. G) objects stored in HttpSession can be accessed by all servlets in the current session. h) objects stored in ServletContext can be accessed and shared by all servlets. (I) one request can belong to only one Session, but one Session can have multiple requests. J) the process of searching for an HttpSession object through SessionID is also called Session tracking. K) When you access the URL for the first time, the SessionID is put into the Set-Cookie field of the message header as a temporary Cookie when the response message header is generated. Therefore, you can track the Session through cookies. L) Tracking Sessioni by rewriting the URL. If the client browser does not support cookies or the Cookie function is disabled, the Cookie cannot be used to save and pass the SessionID. Ii. Use the URL parameter to pass the SessionID if the Cookie cannot work. Iii. To send SessionID through a URL, you must rewrite the URL. 1. encodeURL method: rewrite all URLs embedded in the Servlet. 2. encodeRedirectURL: rewrite the URL used by the sendRedirect method.

 

 

What is HTML?

HTML is a hypertext tag language, and the common static Web page you see is HTML. Give a Demo a general understanding of its structure:

1 <! DOCTYPE html> 2 

Appendix: Common HTML tags:

 

1) Basic HTML structure, such as <HTML>, <HEAD>, and <BODY>. 2) Set tags for paragraph formats, such as <p>, <br>, <div>, and <span>. 3) hyperlink label <a href...>. 4) image labels , table labels <table>, <tr>, <td>, and <th>. 5) frame labels <frame> and <frameset>. 6) form labels <input> and <select>. 7.

 

 

 

 

Some webpages are very beautiful. Who has decorated the HTML window and who has decorated the HTML dream?

For HTML, decoration is required on the appearance, orientation, and other la S. CSS is used. The color and size of a piece of text, the position of a button, the background pattern, and even the animation effect are all credits of CSS. For example:

 

, Announcements, top posts, other texts, blog parks, home pages, various titles, content, etc., all HTML. The font color of "hambi" is gray, and the font color of "top-up" is blue, and "6 months" and "45" are underlined, the background introduces beautiful pictures, which can be achieved through CSS. I can view the status of the browser Debugger:

On the left is the interface effect, in the middle is HTML, and on the right is the CSS style.

1) CSS is short for Cascading Style Sheet (stacked Style form). It is used to define the Style (color, Font, size, position, and so on) for webpage elements ). 2) CSS formats include selector and style rules. 3) define the style in the style attribute of the HTML element. 4) define the style code in HTML. 5) define styles in external files.

 

What is an HTML tool?

Then the client needs to perform convenient operations on HTML. I want to easily access various HTML nodes and provide services for us. I want to obtain the relevant attributes of the browser, in order to better optimize the client experience, I want to write a series of methods to operate and control HTML, then we need to use JavaScript. For example:

Use getElementById () to retrieve HTML elements. For example, navigator. appVersion can be used to obtain the browser version information.

1) var defines variables. 2) Original Type: Undefined, Null, Boolean, Number, String, etc. 3) type conversion: toString (), parseInt, etc. 4) function Definition and function call, with the keyword "function. 5) class and object. Methods of custom classes, such as factory, constructor, and prototype. 6) pre-defined classes, such as Object, Array, String, and Number.

 

Who assists JavaScript in guiding the country?

DOM (Document Object Model) encapsulates all HTML elements and components into objects, and JavaScript can directly manipulate these objects to manipulate Html. In the preceding example, navigator. appVersion encapsulates browser information into an object, and appVersion is an attribute.

1) The main function of DOM is to obtain various elements (div, form, etc.) in the HTML language. Using the object method, you can easily obtain information about these elements, or dynamically add new elements to the element. 2) Three Methods for getting HTML elements. A) getElementById. B) getElementsByName. C) getElementsByTagName.

 

What should I do if I sometimes need to load part of the page information and don't want to refresh the page?

When using Servlet to interact with customers and servers, sometimes the page does not need to refresh the interface when loading the data returned by the server, which uses AJAX technology. Create a request and send request information using ajax, obtain the response results, and then modify the page based on the results. The code using javascript native ajax technology is complicated. Let's take a look at jQuery's usage of ajax :(JQuery is a lightweight framework developed based on javascript. It uses simple commands and Unified Specifications to make javascript more convenient for us.):

 

The url is the link for sending the request (the Servlet program to which the request is sent for processing), and data is the parameter for sending. Success is the Response Message received after the message is sent successfully. How can this problem be solved. More details;

If I want to implement this function: click the "apple" button to send a request. When the background program finds that the request content is "apple", it returns a "apple" image link at the front end, then, the front-end page displays the apple image on the Interface Based on the link. (Here, we click "apple" to display images, which are statically loaded. We do not want to click "apple", duang ~, The page is refreshed, which affects the user experience. At this time, we can easily solve the problem with ajax)

We bind a program to call the ajax code for the "apple" button, and then fill in the url in ajax to process the apple request. Other parameters remain unchanged, "data" writes "apple", and the callback function parameter after success is the returned Apple image link. In this function, we load the link to the page.

[Update HTML content in the form of refreshing (MAGIC and invisible)] 1) AJAX is a combination of JavaScript, CSS, DOM, and XMLHttpRequest. 2) The core object of AJAX is XMLHttpRequest. 3) AJAX function: Send HTTP requests synchronously or asynchronously, and obtain the server response information. 4) use XMLHttpRequest to obtain Web resources. a) Create XMLHttpRequest. B) use the open () method to send HTTP request information. C) use the send () method to send data to the server. D. synchronous and asynchronous retrieval methods.

The interaction tasks between Servlet and HTML are complicated. How can this problem be simplified?

 

Through Jsp technology, you can easily use Servlet for HTML-server interaction. JSP encapsulates Servlet, which is more conducive to development. That is to say, JSP is actually a disguised Servlet, But it softens HTML, CSS, JavaScript, Servlet, and so on and integrates them into a page, all frontend processing is performed in JSP, and the tasks of background programs become simple and clear. The following is a JSP code example:

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6  7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 

We can see that the Java code can be embedded in <%>, while the request in Java code is actually the request object in Servlet, which is the httw.vletrequest object mentioned above. JSP encapsulates Servlet-related objects, so we can easily obtain these objects in JSP. For example, if I want to obtain request parameters, I don't have to use htt?vletrequest in the background to obtain them. I directly use request on the front-end JSP page. getParameter ("... "), or even get it with a concise symbol $.

Main built-in objects of jsp: common functions are also required in JSP programs, such as outputting information to the client, processing request information, responding to messages, obtaining request parameters, and reading configuration file information. These functions are easy to implement in Servlet, such as obtaining request parameters through HttpServletRequest. On the JSP page, these functions are implemented by the built-in JSP objects. Essentially, these built-in objects are equivalent to the corresponding objects in the Servlet.

Built-in object outOutput Data in text format to the client. It is actually a JSPWriter object, which is obtained by the getOut method of the pageContext object.
When an out object is used to output data to the client, the system first places the data in the buffer of the out object until the buffer is filled or the entire JSP page ends, at this time, the buffer content will be written to the buffer provided by the Servlet engine. Finally, the system outputs the data in the Servlet engine to the client. Therefore, data output from an out object to the client usually goes through two buffers (the buffer provided by the JSPWriter object and the buffer provided by the Servlet engine ).Built-in object pageContextPageContext encapsulates the running information of JSP pages. Since the pageContext object can obtain eight other built-in objects, when calling a common JAVA class on a JSP page, you can pass pageContext as a parameter to the corresponding method.Request, response, session ObjectThe getRequest, getResponse, and getSession methods of the PageContext class are returned, which is exactly the same as the Servlet object.Page ObjectThe object instance of the Servlet class corresponding to the current JSP page.Exception objectThis operation is created only when the isErrorPage attribute value of the page command is true.Config objectYou can obtain the configuration information related to the current JSP page in the web. xml file from the config object. The application object is used to obtain information related to the current Web application. Returned by the getServletContext method of the PageContext class. It can be used to obtain global initialization parameters and the absolute path of a Web resource.

 

 

 

When there are many request tasks, JSP cannot meet the requirements. In this case, the MVC (Model, View, Controller) mode appears. It displays who wants to present and who wants to process the request, who will operate databases, encapsulate objects, and so on. The classic MVC mode is struts and spring.

For example, for spring:

  • Spring MVC uses a set of MVC annotations to turn POJO into a request processing controller without any interface. Spring MVC also supports REST-style URL requests: annotation-driven and REST-style Spring MVC is one of the most brilliant features of Spring 3.0.
  • The Spring MVC framework is centered around the DispatcherServlet core. DispatcherServlet is the General Director of SpringMVC, which intercepts requests and distributes them to corresponding processors for processing.
  • Like most web mvc, Spring MVC receives all requests through a front-end Servlet and delegates the specific work to other components for processing. DispatcherServlet is the front-end Servlet of Spring MVC.

For struts:

 

  • The Struts framework first needs to rely on the filter StrutsPrepareAndExecuteFilter to intercept client requests of the Web program, and then perform further processing.

 

  • In Struts2, HTTP request parameters are encapsulated by using Action directly. Stuts2 provides an Action interface that contains an execute method. To implement an Action interface, execute is required. Struts2 also provides an ActionSupport class, which is the default implementation of basic interfaces in many Struts2 frameworks. By inheriting the class, the Action class can simplify many development tasks.
  • The most frequently accessed ServletAPI in Java Web programs is HttpServletRequest, HttpSession, and ServletContext. These three classes correspond to the JSP built-in Object request, session, and application respectively. Struts2 provides an ActionContext class that can be used to access the corresponding ServletAPI.
  • A lot of struts work is implemented by the Interceptor. For example, the params interceptor can parse parameters in the HTTP request and encapsulate the parameter values in the Action attribute. Struts's interceptor mechanism uses nested call methods.

 

 

 

 

 

 

Appendix: Working Principles of spring:

 

To understand the working mechanism of Spring MVC framework, you must answer the following three questions:

 

Question 1: How does the DispatcherServlet framework intercept specific HTTP requests and handle them by the Spring MVC framework?

 

A: configure a Servlet in web. xml and use <servlet-mapping> to specify the url to process. As shown below:

 

 

All http requests with the suffix ".html" are intercepted and processed by DispatcherServlet.

 

Question 2: How does the Web-layer Spring container (WebApplicationContext) be associated with the Spring container (ApplicationContext) at the business layer so that the web-layer bean can call the bean at the business layer?

 

A: The following is a web. xml file:

 

 

ContextLoaderListener is a ServletContextListener that uses the configuration file specified by the contextConfigLocation parameter (such as applicationContext. xml in this example) to start the Spring container of the "Business Layer. The DispatcherServlet introduced below starts the spring container of the Web layer. The spring container of the Web layer serves as the sub-container of the business layer container (that is, the Web layer container can reference the bean of the business layer container, but the business layer container cannot reference the bean of the Web layer container .)

 

Question 3: How to initialize various components of Spring MVC and assemble them into DispatcherServlet?

 

A: After the DispatcherServlet is loaded, it will automatically scan the context bean to find the custom component based on the name or type matching mechanism. If no custom component is found, DispatcherServlet will be used. default component used in properties.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.