Learning Notes (iii) Genericservlet HttpServlet forwarding and redirecting JSPs and hidden object domain objects

Source: Internet
Author: User
Tags html comment

7. MVC design pattern.

6. Properties-related methods:

1). method

void SetAttribute (String name, Object o): Setting properties
Object getattribute (String name): Gets the specified property

Enumeration Getattributenames (): Gets all the names of the properties of the enumeration object
RemoveAttribute (String name): Removes the specified property

2). PageContext, request, session, application objects all have these methods!
These four objects are also called domain objects.

PageContext: The scope of the property is limited to the current JSP page
Request: The scope of the property is limited to the same request.
Session: The scope of the property is limited to one conversation: The browser opens until it is closed as a session (session is not invalidated during this time)
Application: The scope of the property is limited to the current WEB application. is the largest range of properties, as long as the property is set in one place, in a JSP or Servlet everywhere
can be obtained.


5. JSP:

1). Why:

A JSP is a technique written by a simple Servlet that mixes Java code and HTML statements in the same file.
Only the content that is dynamically generated in the Web page is written in Java code, and the static content that is invariant is written in the way of ordinary static HTML page.

2). Java Server Page:java server-side Web page. A page that writes Java code in an HTML page.

2). HelloWorld:

Create a new JSP page and write Java code <%%> within the body node.

<body>

<%
Date date = new Date ();
System.out.print (date);
%>

</body>

3). JSP can be placed in any directory other than Web-inf and its subdirectories in the WEB application.
The access path to the JSP page is exactly the same as the access path of the normal HTML page.

4). How the JSP works: JSP is essentially a Servlet.

Each JSP page is accessed the first time, the JSP engine translates it into a servlet source program, and then compiles the servlet source program into a servlet class file.
The Web container (servlet engine) is then loaded and interpreted in the same way as a normal servlet program to execute the servlet program translated by the JSP page.

5). The implied variable of the JSP page: an object that can be used without a declaration. There are 9 hidden objects in a JSP page.

public void _jspservice (HttpServletRequest request, httpservletresponse response)
Throws Java.io.IOException, Servletexception {

PageContext pagecontext = null;
HttpSession session = NULL;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;

//...

Code written using <%%> at this location. can use request, response, PageContext, session
Application, config, out, page these 8 hidden objects. (You can actually use an implicit object called exception.)

}

An object of ①. Request:httpservletrequest. *
②. Response:httpservletresponse an object (any method of response is rarely called in a JSP page.)

③. PageContext: The context of the page, which is an object of PageContext. You can get the other 8 hidden objects from this object. You can also get the current
Additional information about the page. (Use it when learning a custom label) *
④. Session: A conversation that represents a browser and a server, which is an object of HttpSession. Learn more later. *

⑤. Application: Represents the current WEB app. is a ServletContext object. *
⑥. config: The ServletConfig object (almost unused) of the Servlet corresponding to the current JSP. If you need to access the initialization parameters of the current JSP configuration,
You need to pass the mapped address.

Map JSP:

<servlet>
<servlet-name>hellojsp</servlet-name>
<jsp-file>/hello.jsp</jsp-file>
<init-param>
<param-name>test</param-name>
<param-value>testValue</param-value>
</init-param>
</servlet>

<servlet-mapping>
<servlet-name>hellojsp</servlet-name>
<url-pattern>/hellojsp</url-pattern>
</servlet-mapping>

⑦. Out:jspwriter object. Call Out.println () to print the string directly to the browser. *
⑧. Page: A reference to the Servlet object corresponding to the current JSP, but for type object, only methods of the object class are called (hardly used)

⑨. Exception: can only be used if the iserrorpage= "true" of the page directive is declared. *

<%@ page iserrorpage= "true"%>

PageContext, request, session, application (range from small to large for the scope of the attribute)
Out, Response, config, page
exception

6). JSP template elements: static HTML content in JSP pages

7). JSP expressions (expression) provide a simplified way of outputting the results of a Java variable or expression to the client.
The variables or expressions that it will output are encapsulated directly in <%= and%>.

<%
Date date = new Date ();
Out.print (date);
%>

<%= Date%>

8). JSP script fragment (scriptlet) refers to one or more Java program code nested within <% and%>.
Code in multiple script fragments can access each other

<%
String agestr = Request.getparameter ("Age");
Integer age = Integer.parseint (AGESTR);

if (age >= 18) {
%>
Adult...
<%
}else{
%>
Non-adult ...
<%
}
%>

9). JSP declaration: JSP Declaration encapsulates Java code in <%! And%>, the code inside it will be inserted outside the _jspservice method of Servle T.
(almost never used in JSP pages)

). JSP comment Format: <%--jsp comment--%> <!--HTML Comment--
Difference: JSP annotations can block the execution of Java code.


4. Forwarding and redirection of requests:

1). Essential difference: The forwarding of the request only makes one request, while the redirect makes two requests.

Specific:

①. Forwarding of requests: The Address bar is the address where the request was first made.
REDIRECT requested: The Address bar is no longer the initial request address. Address bar is the last address that responds

②. Request forwarding: In the final Servlet, the request object and the requested request in transit are the same object.
Request redirection: In the final Servlet, the request object and the requested request in transit are not the same object.

③. Forwarding of requests: resources that can only be forwarded to the current WEB app
REDIRECT requested: can be redirected to any resource.

④. Forwarding of requests:/represents the root directory of the current WEB app
REDIRECT requested:/represents the root directory of the current WEB site.

3.

-----------------------------------------------------------------------------

Create a Test_users data table in the MySQL database and add 3 fields: ID, user, password. and enter a few records.

Define a login.html that defines two request fields: User, password. Send request to Loginservlet
When creating a loginservlet (which needs to inherit from HttpServlet and override its DoPost method),
The user in which the request was obtained, password.

Use JDBC to query from Test_users for the user, password corresponding record for the page input

SELECT count (id) from test_users WHERE user =? and password =?

If there is, response hello:xxx, if not, the response sorry:xxx xxx for user.

-----------------------------------------------------------------------------

2. HttpServlet:

1). is a Servlet that inherits from Genericservlet. Customized for the HTTP protocol.

2). Servletreuqest and Servletresponse are converted directly to HttpServletRequest and HttpServletResponse in the service () method.
and called the overloaded service (HttpServletRequest, HttpServletResponse)

The request method was obtained at service (HttpServletRequest, HttpServletResponse): Request.getmethod (). Depending on the request method, there is a creation
Doxxx () method (XXX for specific request mode, such as Doget, DoPost)

@Override
public void Service (ServletRequest req, servletresponse Res)
Throws Servletexception, IOException {

HttpServletRequest request;
HttpServletResponse response;

try {
Request = (httpservletrequest) req;
Response = (httpservletresponse) res;
} catch (ClassCastException e) {
throw new Servletexception ("Non-http Request or response");
}
Service (request, response);
}

public void Service (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
1. Gets the request method.
String method = Request.getmethod ();

2. Call the corresponding processing method according to the request mode
if ("GET". Equalsignorecase (method)) {
Doget (request, response);
}else if ("POST". Equalsignorecase (method)) {
DoPost (request, response);
}
}

public void DoPost (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, ioexception{
TODO auto-generated Method Stub

}

public void doget (HttpServletRequest request, httpservletresponse response)
Throws Servletexception, IOException {
TODO auto-generated Method Stub

}

3). In the actual development, the direct inheritance httpservlet, and according to the request method of the replication Doxxx () method can be.

4). Benefits: Direct by the targeted coverage doxxx () method; Using HttpServletRequest and HttpServletResponse directly eliminates the need for strong turns.

1. Genericservlet:

1). is a serlvet. is the implementation class for the Servlet interface and the ServletConfig interface. But an abstract class. Where the service method is an abstract method

2). If the new Servlet program inherits Genericserlvet directly, it will make development more concise.

3). Specific implementation:

①. A member variable of type Serlvetconfig is declared in Genericservlet and initialized in the init (ServletConfig) method.
②. The method of ServletConfig interface is realized by using ServletConfig member variable method
③. An init () method is also defined, which is called in the init (Serlvetconfig) method, and the subclass can directly override Init () in which the Servlet initialization is implemented.
④. It is not recommended to overwrite Init (servletconfig) directly, because if you forget to write Super.init (config); And still using the Serlvetconfig interface method,
A null pointer exception appears.
⑤. New init () {} is not a life-cycle method of Serlvet. and init (ServletConfig) is a life-cycle-related approach.

Public abstract class Genericservlet implements Servlet, ServletConfig {

/** The following methods are methods of the Servlet interface **/
@Override
public void Destroy () {}

@Override
Public ServletConfig Getservletconfig () {
return servletconfig;
}

@Override
Public String Getservletinfo () {
return null;
}

Private ServletConfig ServletConfig;

@Override
public void init (ServletConfig arg0) throws Servletexception {
This.servletconfig = arg0;
Init ();
}

public void Init () throws servletexception{}

@Override
public abstract void Service (ServletRequest arg0, Servletresponse arg1)
Throws Servletexception, IOException;

/** The following methods are methods of the ServletConfig interface **/
@Override
public string Getinitparameter (string arg0) {
Return Servletconfig.getinitparameter (arg0);
}

@Override
Public enumeration Getinitparameternames () {
return Servletconfig.getinitparameternames ();
}

@Override
Public ServletContext Getservletcontext () {
return Servletconfig.getservletcontext ();
}

@Override
Public String Getservletname () {
return Servletconfig.getservletname ();
}

}

Learning Notes (iii) Genericservlet HttpServlet forwarding and redirecting JSPs and hidden object domain objects

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.