Jsp/servlet Web Learning Note dayfour

Source: Internet
Author: User

Servlet overview

Servelt is a Java program that uses Java servlet application interfaces and related classes and methods.

A servlet is a server-side program written in Java that is independent of protocol and platform . The servlet runs in the Java server.

The Java servlet API defines a standard interface between the servlet and the server, which enables the servlet to have a cross-server platform feature .

Typically, Servlets are accessed using a stateless request-response model . It can handle HTTP requests from clients, extract parameters from them, process business logic, and ultimately return data or output HTML. It can also access the database, perform calculations, and communicate with enterprise JavaBean components.

How the servlet works

See the previous JSP operating principle.

The life cycle of the servlet

There is a javax.servlet.Servlet definition.

Load Class---> Initialize (init ())---> Services (Service ())---> Destruction (Destroy ())

Common structure of Servlets
@WebServlet ("/name") Public classServletextendsHttpServlet {Private Static Final LongSerialversionuid = 1L; /**     * @seeHttpservlet#httpservlet ()
* Init ()*/ PublicServlet () {Super(); //TODO auto-generated Constructor stub } /** * @seeHttpservlet#doget (httpservletrequest request, httpservletresponse response)
* Processing GET requests*/ protected voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {//TODO auto-generated Method StubDoPost (request, response); } /** * @seeHttpservlet#dopost (httpservletrequest request, httpservletresponse response)
   * Processing Post requests */ protected voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {//TODO auto-generated Method Stub }}
Servlet gets the parameters in the request

Similar to JSP, the use of the GetParameter () method, commonly used specifically as follows:

 Public String GetParameter (string name);   // gets the parameter value of the specified name  Public // for cases where a parameter name corresponds to multiple values  Public // returns an enumeration object that contains all the parameter names in the request message.  Public// return all parameter names and map of corresponding parameter values

  Data garbled problem:

Post method: Encodes the encoding specified by the HTML page.

The request handling method in the Servelt class requires that the data be encoded by parameter by calling the Setcharacterencoding (String Enc) method of the HttpServletRequest interface.

      You can usually use Response.setcontenttype ("Text/html;charset=utf-8").

Get method: Parameters are stitched to the URL after submission. That the above method has no effect.

Before sending this data, manually encode them according to the encoding specified by the page: Java.net.URLEncoder.encode (String s,string Enc) method. And then send it again.

The request processing method of the Servlet class is then decoded manually: Java.net.URLDecoder.decode (String s,string Enc) method.

           As a best practice, do not use non-ASCII characters such as Chinese in the URL again.

REDIRECT && request Dispatch
Absolute URL The path that begins with "/" refers to the path relative to the Web app's root directory.
Relative URL A path that is not preceded by "/" refers to the path relative to the current path directory.
redirect

Related methods: Sendredirect () provided by the HttpServletRequest interface

Description: Not only can you redirect to other resources in the current application, you can also redirect resources to other applications in the same container, even resources that are redirected to other sites by using an absolute URL .

 Public void throws IOException;   // Location can use absolute URLs and relative URLs

    Note: Redirection changes the current URL to the URL of the directed program, that is, the Get method cannot be passed to the latter by redirection. The initiator and callee use their own request and response instances.

Working principle:

    

Request Dispatch

Related methods: A RequestDispatcher interface is defined in the Servlet API, commonly known as a request dispatcher. It defines the following two methods:

 Public void throws servletexception, IOException;  Public void include (servletrequest request,servletresponse response)    throws servletexception, IOException;

Description: There are two ways to get an RequestDispatcher instance

The Getrequestdispatcher (String URL) URL provided by the calling ServletContext interface must be an absolute path

The Getrequestdispatcher (String URL) URL provided by the call to the ServletRequest interface can be a relative path or a relative path

Requests can only be forwarded to other components in the same web app and cannot be forwarded to resources at other sites.

    Note: After the request forwarding process is accepted, the browser keeps the initial URL address intact. and the initiator and the callee share a request and response instance.

Working principle:

 

In addition: Because a request, response instance is common, the method can take advantage of setattribute (string name, Oject obj) and getattribute (string name) and other methods to pass the object data using the request domain property. Examples are as follows:

Boolean iserror=true; Request.setattribute ("error", IsError); Request.getrequestdispatcher ("servletcom.jsp"). Forward (request, response);
boolean a= (boolean) Request.getattribute ("Error"), and the other end of the jump is directly accessible.
Call of the servlet

1) URL invocation: When you specify a servlet mapping address in a configuration file, you can invoke the servlet directly from the browser, such as:

Http://localhost:8080/helloworld

2) call in JSP file: You can use the <jsp:include> or <jsp:forward> statement to invoke a servlet in a JSP page, such as:

<jsp:include page= "/servlet" flush= "true"/>

In the execution of the page, when this sentence is encountered, it jumps to the servlet that responds, and when the servlet executes, control returns to the original JSP page.

You can also use <jsp:forward> to jump.

Jsp/servlet Web Learning Note dayfour

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.