1,jsp nine large built-in objects
Requesting object request
Output Object out
Response Object Response
Application Object Application
Sessions Object session
Page Context Object PageContext
Pages Object page
Configuration Object Config
Exception Object exception
2,request Object
Stringgetparameter (String name) Gets the submission data based on the form component name
String[]getparametervalues (String name) gets the request data for a form component corresponding to multiple values--requires non-null validation
Voidsetcharacterencoding (String CharSet) specifies the encoding for each request
Requestdispatchergetrequestdispatcher (String path) returns a RequestDispatcher object with the Forward () method used to forward the request
Request Method Forwarding:
Request.getrequestdispatcher ("usercreate.jsp"). Forward (request, response);
3,response Object
Method: SetAttribute (String name, Object o);
Object getattribute (String name);---> if (userName! = NULL | |!username.equals (""))
Note: the GetAttribute () method returns a null value if there is no corresponding parameter name, so a non-null judgment will occur, otherwise null pointer exceptions
And the Object type is returned, so the data type conversion is done
Response redirection
Response.sendredirect ("usercreate.jsp");
4, the difference between forwarding and redirection
Forward
? RequestDispatcher Object
? Forward () method
1, request.getrequestdispatcher ("url"). Forward (request, response)
2, <jsp:forward page= "url"/>
? redirect
? Relocate a user request to a new URL
Response.sendredirect ("url")
*): Redirect execution: The Web server sends an HTTP response to the browser, and the browser receives this response before sending a new HTTP request to the server
The server looks for resources and sends them to the browser based on this request. It can redirect to any URL and cannot share data within the request scope
2): Redirect is a function on the client, by requesting a new address to implement the page jump
3): Redirect is to re-request the address through the browser, in the address bar can display the post-turn address
: Forwarding Process: The Web server calls internal methods to complete the request processing and forwarding actions within the container, and sends the target resource to the browser, which can only be used in the same web app, sharing data within the request range
5): Forwarding is performed on the server side, through the forward () method to pass the submission information between multiple pages
6): Forwarding is the transfer of control within the server, the address bar of the client browser does not show the address after the turn
5,session Object
Method:
SetAttribute (String key, Object O);
GetAttribute (String key);==> for non-null validation if (userName! = NULL | |!username.equals (""))
GetId ();
Invalidate (); Set Session object to expire
Setmaxinactioveinterval (int interval)
RemoveAttribute (String key)
To remove a session:
1): Program Active Removal:
Session.invalidate ();
Session.removeattribute ("UserName");
2): Active Server cleanup:
Session.setmaxinactioveinterval (int interval); In units of seconds
Configure the Tomcat Web. xml file
<session-config><session-timeout>10</session-timeout></session-config>
-In minutes
6,cookie Object
1) Create a cookie
Cookie cookie = new Cookie ("User", Urlencoder.encode (UserName, "UTF-8"));
2) Write Cookie
Response.addcookie (cookie);
3) Read the cookie (response receive page)
cookie[] cookies = request.getcookies ();
String user = "";
if (cookie = null) {
for (int i=0; i<cookies.length; i++) {
if ("User". Equals (Cookies[i].getname ())) {
user = Urldecoder.decode (cookies[i].getvalue (), "UTF-8");
}
}
}
===> recommends an array to be judged if (cookies! = null)
<% @page import= "Java.net.URLEncoder"%>
<% @page import= "Java.net.URLDecoder"%>
Common methods:
SetValue (String value);
GetName ();
GetValue ();
Getmaxage ();
Setmaxage (int expiry); Set the cookie validity period in seconds
Comparison between 7,cookie and session
1): Session is to save user information on server side, cookie is to save user information on client
2): The object is saved in the session, and the cookie is the string
3): The Session object expires with the end of the conversation, the cookie can be stored in the client for a long time
4): Cookies are typically used to store unimportant user information, and important information is saved using the session
8,application Object
Method:
SetAttribute (String key, Object O);
GetAttribute (String key)
Get
Example: Number of visitors to the statistics website
Request.setcharacterencoding ("UTF-8");
Integer hitcount = (integer) application.getattribute ("Hitcount");
if (Hitcount ==null | | hitcount ==0) {
Application.setattribute ("Hitcount", New Integer (1));
} else {
Application.setattribute ("Hitcount", Count.intvalue () +1);
}
Out.print ("page has been accessed" hitcount. Intvalue () + "times" + "<br/>");
Or:
if (Hitscount ==null | | hitscount = = 0) {
Hitscount = 1;
}else{
Hitscount + = 1;
}
Application.setattribute ("HitCounter", Hitscount);
---> Final Unified setup
Add:
Reset counter
Using the above method, after the Web server restarts, the counter will be reset to 0, that is, the previously retained data will disappear, you can use the following methods to solve the problem:
A data table that is used to count page accesses is defined in the database, the field is Hitcount, the Hitcount default value is 0, and the statistics are written to the data table.
On each visit we read the Hitcount field in the table.
Let Hitcount increment by 1 per visit.
Displays the new Hitcount value on the page as the amount of access to the page.
If you need to count the number of visits per page, you can use the logic above to add code to all pages.
9, Object Scope comparison
Page: Only valid on the current page, once you leave the current page, objects created within that scope will not be accessible
Requests within the same request scope can access objects created within the scope, and once the request is invalidated, the created object is also invalidated
The session can access objects within the scope before it is invalidated or destroyed
Application data can be stored from the application before the entire Web application service is stopped
10, automatic page refresh
Using the Setintheader () method of the Response object
public void Setintheader (String header, int headervalue)--This method notifies the browser to refresh after a given time, in seconds.
Set to refresh every 5 seconds
Response.setintheader ("Refresh", 5);
Cases:
Get current time
Calendar calendar = new GregorianCalendar ();
String am_pm;
int hour = Calendar.get (Calendar.hour);
int minute = Calendar.get (Calendar.minute);
int second = Calendar.get (Calendar.second);
if (Calendar.get (calendar.am_pm) = = 0) {
AM_PM = "AM";
}else{
am_pm = "PM";
}
String CT = hour+ ":" + Minute + ":" + second + "+ am_pm;
Out.println ("Current time:" + CT + "\ n");
11. Pass the Checkbox data to the JSP program
Request.setcharacterencoding ("UTF-8");
Request.setcharacterencoding ("UTF-8");
string[] Paramnames = request.getparametervalues ("web"); --The web is the Name property value of the Checkbox
if (paramnames! = null) {
for (String para:paramnames) {
OUT.PRINTLN (para);
}
}
Redirect into session Pass
String[] Info = request.getparametervalues ("info");--> info is the Name property value of the Checkbox
list<string> list = new arraylist<string> ();
if (info! = null) {------> Note Be sure to do non-null validation
for (String Str:info) {
List.add (str);
}
}
Session.setattribute ("list", list);
-Loop Read
<c:foreach var= "str" items= "${list}" varstatus= "status" >
<b>${str}</b>
</c:forEach>
-Enhanced
<c:foreach var= "str" items= "${list}" varstatus= "status" >
${STR}
<c:set var= "End" scope= "session" Value= "${list.get (List.size ()-1)}"/>---> Set the last element, noting that the last index is list.size ()-1
<c:if test= "${!end.equals (str)}" >,</c:if>----> if not the last element, add ', '
</c:forEach>
JavaBean unique features compared to other Java classes:
Provides a default parameterless constructor.
The serializable interface needs to be serialized and implemented.
There may be a series of read-write properties.
There may be a series of "getter" or "setter" methods.
----> Settings jump to the specified page
<%
String URLPath = (string) request.getattribute ("url");
Response.setheader ("Refresh", "3,url=" +urlpath); %>
12,jsp Action Instructions
1): include directive
JSPs can include other files through the include directive. The included file can be a JSP file, an HTML file, or a text file. The contained file is as if it were part of the JSP file and will be compiled at the same time.
<%@ include file= "file relative URL address"%>
Note: When a JSP file is converted into a servlet, the file is introduced
2):P age directive
The page directive provides the container with instructions for using the current page. A JSP page can contain multiple page directives.
<%@ page attribute= "value"%>
Example: <%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%>
3): Taglib instruction
<%@ taglib uri= "uri" prefix= "Prefixoftag"%>
Example: <%@ taglib uri= "Http://java.sun.com/jsp/jstl/core" prefix= "C"%>
13,jsp Action Elements
1):<jsp:include>
<jsp:include page= "relative URL Address" flush= "true"/>
Flush Boolean property that defines whether to flush the buffer before the resource is included.
-->include directive, which introduces a file when a JSP file is converted to a servlet
Jsp:include action is different, the time to insert a file is when the page is requested.
2):<jsp:usebean>--><jsp:usebean id= "name" class= "Package.class"/>
<jsp:setProperty>
<jsp:getProperty>
Cases:
<jsp:usebean id= "user" class= "com.entity.User" scope= "request"/> ==>id As Object name, class full path, scope scope
<jsp:setproperty property= "userId" name= "User" value= "1"/> ==>property as the property name, name is the object name, value is the property value of the object
<jsp:setproperty property= "UserName" name= "user" value= "Zhang San"/>
<jsp:getproperty property= "userId" name= "user"/><br/>//1
<jsp:getproperty property= "UserName" name= "user"/>//Zhang San
3):<jsp:forward> Action elements
Jsp:forward action to transfer requests to another page forwarding
<jsp:forward page= "relative URL address"/>
The-->page property contains a relative URL. The value of the page can be either directly or dynamically computed at the time of the request, either as a JSP page or as a Java Servlet.
4):<jsp:plugin> Action elements
5):<jsp:element>, <jsp:attribute>, <jsp:body> action elements
6):<jsp:text> Action elements
<jsp:text> Template Data </jsp:text>
Cases:
<jsp:text> <jsp:forward page= "date.jsp"/></jsp:text>
Display: <jsp:forward page= "date.jsp"/>
Note: JSP page is greater than less than > <
===>
GetParameter () returns a string type
GetAttribute () returns the type of object
JSP Learning Notes