Examples of JSP built-in objects

Source: Internet
Author: User
Tags date format header variables string square root variable unique id
js| Objects | Built-in Objects | detailed

JSP nine kinds of built-in objects: request, reponse, out, session, Application, config, PageContext, page, exception.

  A. Request object: The object encapsulates the information submitted by the user, and it is possible to obtain the encapsulated information by invoking the object's corresponding method, that is, the object can be used to obtain user submissions.

  a 1.Request object can use the GetParameter (string s) method to obtain information submitted by the form through text. such as:

Request.getparameter ("Boy")

Example: request1.jsp:

<%@ page contenttype= "text/html;charset=gb2312"%>

<HTML>

<body Bgcolor=green><font size=1>

<form action= "tree.jsp" Method=post name=form>

<input type= "text" name= "Boy" >

<input type= "Submit" value= "Enter" name= "Submit" >

</FORM>

</FONT>

</BODY>

</HTML>

TREE.JSP:

<%@ page contenttype= "text/html;charset=gb2312"%>

<HTML>

<body Bgcolor=green><font size=1>

<P> Get information for text box submissions:

<%string textcontent=request.getparameter ("Boy");

%>

<BR>

<%=textContent%>

<P> get the name of the button:

<%string Buttonname=request.getparameter ("submit");

%>

<BR>

<%=buttonName%>

</FONT>

</BODY>

</HTML>

Use the Request object to get information to be careful, to avoid the use of empty objects, otherwise there will be nullpointerexception exception, so we can do the following processing.

request3.jsp

<%@ page contenttype= "text/html;charset=gb2312"%>

<HTML>

<body Bgcolor=cyan><font size=5>

<form action= "" Method=post name=form>

<input type= "text" name= "Girl" >

<input type= "Submit" value= "Enter" name= "Submit" >

</FORM>

<%string textcontent=request.getparameter ("Girl");

Double number=0,r=0;

if (textcontent==null)

{textcontent= "";

}

try{number=double.parsedouble (textcontent);

if (number>=0)

{r=math.sqrt (number);

Out.print ("<BR>" +string.valueof (number) + "square root:");

Out.print ("<BR>" +string.valueof (r));

}

Else

{Out.print ("<BR>" + "Please enter a positive number");

}

}

catch (NumberFormatException e)

{Out.print ("<BR>" + "Please enter numeric characters");

}

%>

</FONT>

</BODY>

</HTML>

  2. Processing Chinese character information: when the request object obtains the character which the customer submits, will appear the disorderly horse problem, must carry on the special processing. First, the acquired string is encoded with iso-8859-1, and the encoding is stored in a byte array, which is then converted to a character-channeling object immediately.

such as: String textcontent=request.getparameter ("Boy");

Byte b[]=textcontent.getbytes ("Iso-8859-1");

Textcontent=new String (b);

Example: tree2.jsp

<%@ page contenttype= "text/html;charset=gb2312"%>

<MHML>

<BODY>

<P> Get information for text box submissions:

<%string textcontent=request.getparameter ("Boy");

Byte b[]=textcontent.getbytes ("Iso-8859-1");

Textcontent=new String (b);

%>

<BR>

<%=textContent%>

<P> get the name of the button:

<%string Buttonname=request.getparameter ("submit");

Byte c[]=buttonname.getbytes ("Iso-8859-1");

Buttonname=new String (c);

%>

<BR>

<%=buttonName%>

</BODY>

</HTML>

3. Examples of common methods:

Getprotocol (), Getservletpath (), Getcontentlength (), GetMethod (), getremoteaddr (), Getremotehost (), GetServerName (), Getparametername ()

Cases:

<%@ page contenttype= "text/html;charset=gb2312"%>

<%@ page import= "java.util.*"%>

<MHML>

<body bgcolor=cyan>

<font size=5>

The agreements used by <BR> customers are:

<% String Protocol=request.getprotocol ();

OUT.PRINTLN (protocol);

%>

<BR> get a page that accepts customer submissions:

<% String Path=request.getservletpath ();

OUT.PRINTLN (path);

%>

<BR> accept the length of customer submission information:

<% int length=request.getcontentlength ();

Out.println (length);

%>

<BR> How the customer submits the information:

<% String Method=request.getmethod ();

Out.println (method);

%>

<BR> get the value of the User-agent in the HTTP header file::

<% String header1=request.getheader ("user-agent");

Out.println (Header1);

%>

<BR> get the value of the accept in the HTTP header file:

<% String Header2=request.getheader ("accept");

Out.println (Header2);

%>

<BR> get the value of host in the HTTP header file:

<% String header3=request.getheader ("Host");

Out.println (HEADER3);

%>

<BR> get the value of the accept-encoding in the HTTP header file:

<% String header4=request.getheader ("accept-encoding");

Out.println (HEADER4);

%>

<BR> get the customer's IP address:

<% String ip=request.getremoteaddr ();

Out.println (IP);

%>

<BR> get the name of the client:

<% String clientname=request.getremotehost ();

Out.println (ClientName);

%>

<BR> get the name of the server:

<% String servername=request.getservername ();

Out.println (ServerName);

%>

<BR> get the port number of the server:

<% int Serverport=request.getserverport ();

Out.println (ServerPort);

%>

<BR> get the name of all parameters submitted by the client:

<% enumeration Enum=request.getparameternames ();

while (Enum.hasmoreelements ())

{string s= (String) enum.nextelement ();

Out.println (s);

}

%>

<BR> get an enumeration of header names:

<% enumeration Enum_headed=request.getheadernames ();

while (Enum_headed.hasmoreelements ())

{string s= (String) enum_headed.nextelement ();

Out.println (s);

}

%>

<BR> gets an enumeration of all values for the specified header name in the header file:

<% enumeration Enum_headedvalues=request.getheaders ("Cookie");

while (Enum_headedvalues.hasmoreelements ())

{string s= (String) enum_headedvalues.nextelement ();

Out.println (s);

}

%>

<BR>

</Font>

</BODY>

</HTML>

4. Get data submitted by HTML form

Radio Box Radio

Cases:

RADIO.JSP:

<HTML>

<%@ page contenttype= "text/html;charset=gb2312"%>

<body Bgcolor=cyan><font size=1 >

<P> poet Li Bai is one of the dynasties in Chinese history:

<form action= "answer.jsp" Method=post name=form>

<input type= "Radio" name= "R" value= "a" > Song Dynasty

<input type= "Radio" name= "R" value= "B" > Tang Dynasty

<input type= "Radio" name= "R" value= "C" > Ming Dynasty

<input type= "Radio" name= "R" value= "D" checked= "OK" > Yuan Dynasty

<BR>

The author of the Dream of the <P> novel is:

<BR>

<input type= "Radio" name= "P" value= "a" > Cao Xueqin

<input type= "Radio" name= "P" value= "B" > Guanzhong

<input type= "Radio" name= "P" value= "C" > Li Bai

<input type= "Radio" name= "P" value= "D" > Sima Qian

<BR>

<input type= "Submit" value= "submitted Answer" Name= "Submission" >

</FORM>

</FONT>

</BODY>

</HTML>

ANSWER.JSP:

<HTML>

<%@ page contenttype= "text/html;charset=gb2312"%>

<body Bgcolor=cyan><font size=1 >

<% int n=0;

String s1=request.getparameter ("R");

String s2=request.getparameter ("P");

if (s1==null)

{s1= "";}

if (s2==null)

{s2= "";}

if (S1.equals ("B"))

{n++;}

if (S2.equals ("a"))

{n++;}

%>

<P> you got <%=n%> points

</FONT>

</BODY>

</HTML>

List box <select><Option>

Cases:

SELECT.JSP:

<HTML>

<%@ page contenttype= "text/html;charset=gb2312"%>

<body Bgcolor=cyan><font size=1 >

<P> Choose the calculation and the way

<form action= "sum.jsp" Method=post name=form>

<select name= "Sum" size=2>

<option Selected value= "1" > computes 1 to n continuous and

<option value= "2" > calculates the sum of squares of 1 to N

<option value= "3" > Compute 1 to n cubic and

</Select>

<P> Select the value of N:<br>

<select name= "n" >

<option value= "Ten" >n=10

<option value= ">n=20"

<option value= ">n=30"

<option value= ">n=40"

<option value= ">n=50"

<option value= ">n=100"

</Select>

<BR><BR>

<input type= "Submit" value= "submitted your choice" Name= "Submit" >

</FORM>

</FONT>

</BODY>

</HTML>

SUM.JSP:

<HTML>

<%@ page contenttype= "text/html;charset=gb2312"%>

<body Bgcolor=cyan><font size=1 >

<% long sum=0;

String s1=request.getparameter ("sum");

String S2=request.getparameter ("n");

if (s1==null)

{s1= "";}

if (s2==null)

{s2= "0";}

if (S1.equals ("1"))

{int n=integer.parseint (s2);

for (int i=1;i<=n;i++)

{sum=sum+i;

}

}

else if (S1.equals ("2"))

{int n=integer.parseint (s2);

for (int i=1;i<=n;i++)

{sum=sum+i*i;

}

}

else if (S1.equals ("3"))

{int n=integer.parseint (s2);

for (int i=1;i<=n;i++)

{sum=sum+i*i*i;

}

}

%>

<P> your sum result is <%=sum%>

</FONT>

</BODY>

</HTML>

  Two. Response objects: Dynamic response to customer requests, sending data to the client.

 1. Dynamic Response Contentype Properties

When a user accesses a JSP page, if the page sets the page's ContentType property to be text/html, the JSP engine responds to this property value. If you want to dynamically change this property value to respond to the customer, you need to use the setContentType (String s) method of the response object to change the ContentType property value.

Format: Response.setcontenttype (String s)

Parameter s are preferable to text/html, Application/x-msexcel, Application/msword, etc.

For example: response1.jsp

<%@ page contenttype= "text/html;charset=gb2312"%>

<HTML>

<body Bgcolor=cyan><font size=1 >

<P> I'm learning the response object

<br>setcontenttype method

<P> Save the current page as a Word document?

<form action= "" method= "get" name=form>

<input type= "Submit" value= "yes" name= "submit" >

</FORM>

<% String Str=request.getparameter ("submit");

if (str==null)

{str= "";

}

if (str.equals ("yes"))

{Response.setcontenttype ("application/msword;charset=gb2312");

}

%>

</FONT>

</BODY>

</HTML>

 2. Response Redirect: In some cases, when responding to a customer, you need to reboot the customer to another page, and you can use the response Sendredirect (URL) method to achieve customer redirection.

For example: response2.jsp:

<body>

<%

String address = Request.getparameter ("where");

if (address!=null) {

if (Address.equals ("Chinawebber"))

Response.sendredirect ("http://www.ChinaWebber.com");

else if (address.equals ("Yahoo"))

Response.sendredirect ("http://www.yahoo.com");

else if (address.equals ("Sun"))

Response.sendredirect ("http://www.sun.com");

}

%>

<b>please select:</b><br>

<form action= "goto.jsp" method= "Get" >

<select name= "where" >

<option value= "Chinawebber" Selected>go to Chinawebber

<option value= "Sun" > Go to Sun

<option value= "Microsoft" > go to Microsoft

</select>

<input type= "Submit" value= "Go" >

</form>

 Three Session Object

  1. What is session: The session object is a JSP built-in object that is automatically created when the first JSP page is loaded, and is completed for conversation management.

From a customer to open the browser and connect to the server to start, to the customer close the browser to leave the server end, is called a session. When a client accesses a server, it may be repeatedly connected between several pages of the server, repeatedly refreshing a page, the server should somehow know that this is the same customer, this requires the session object.

  2. ID of the Session object: When a customer first accesses a JSP page on a server, the JSP engine produces a sessions object and assigns a string ID number, which the JSP engine sends to the client at the same time, stored in a cookie, This creates a one by one correspondence between the session object and the customer. When a customer accesses another page that connects to the server, it is no longer assigned to the customer's new session object until the client closes the browser, and the client's sessions object is canceled on the server side, and the client's conversation relationship disappears. When the client reopened the browser and then connected to the server, the server creates a new session object for the client.

 3. Common methods for session objects:

I.public String getId (): Gets the Session object number.

ii.public void setattribute (String key,object obj): Adds the object obj specified by the parameter object to the session object and assigns an index keyword to the added object.

Iii.public Object GetAttribute (String key): Gets objects in the session object that contain keywords.

Iv.public Boolean isnew (): Determine if it is a new customer.

For example: session1.jsp

<%@ page contenttype= "text/html;charset=gb2312"%>

<HTML>

<body Bgcolor=cyan><font size=5>

<BODY>

<%string S=session.getid ();

%>

<P> the ID of your session object is:

<BR>

<%=s%>

<BODY>

<HTML>

For example: session2.jsp

<%@ page contenttype= "text/html;charset=gb2312"%>

<HTML>

<BODY>

<%! int number=0;

synchronized void Countpeople ()

{

number++;

}

%>

<%

if (Session.isnew ())

{

Countpeople ();

String str=string.valueof (number);

Session.setattribute ("Count", str);

}

%>

<P> you are <%= (String) session.getattribute ("Count")%> a person to visit this site.

<BODY>

<HTML>

  Four Aplication objects

 1. What is application:

This Application object is generated when the server is started, and the Application object is the same until the server is shut down when the customer browses through the pages of the site visited. But unlike the session, all customers have the same application object, that is, all customers share this built-in application object.

  2. Common methods for application objects:

(1) public void setattribute (String key,object obj): Adds the object obj specified by the parameter object to the Application object and assigns an index keyword to the added object.

(2) Public object GetAttribute (String key): Gets the object that contains the keyword in the Application object.

Example: application.jsp

<HTML>

<HEAD>

Use of <title>application variables </TITLE>

</HEAD>

<BODY>

<CENTER>

<font SIZE = 5 COLOR = blue>application variable use </FONT>

</CENTER>

<HR>

<P></P>

<%

Object obj = null;

String strnum = (string) application.getattribute ("Num");

int Num = 0;

Check whether the NUM variable can be obtained

if (strnum!= null)

Num = Integer.parseint (strnum) + 1; Increase the value achieved by 1

Application.setattribute ("num", string.valueof (num)); Start num Variable Value

%>

The <font color = blue>num</font> Variable value in the Application object is

<font color = red><%= Num%></font><br>

</BODY>

</HTML>

  Five Out objects

An Out object is an output stream that is used to output data to the client. The Out object is used for the output of various data.

Common methods:

(1) out.print (): Output various types of data.

(2) Out.newline (): Output a line feed character.

(3) Out.close (): Close the stream.

Example: out.jsp

<%@ page contenttype= "text/html;charset=gb2312"%>

<%@ page import= "Java.util.Date"%>

<HTML>

<HEAD>

<%

Date now = new Date ();

String hours=string.valueof (Now.gethours ());

String mins=string.valueof (Now.getminutes ());

String secs=string.valueof (Now.getseconds ());

%>

is now

<%out.print (String.valueof (Now.gethours ());%>

Hours

<%out.print (String.valueof (Now.getminutes ());%>

Part

<%out.print (String.valueof (Now.getseconds ());%>

Seconds

</FONT>

</BODY>

</HTML>

  Six Cookies

  1. What is a cookie:

A cookie is a piece of text that the Web server saves on a user's hard disk. Cookies allow a Web site to save information on a user's computer and then retrieve it.

For example, a Web site might produce a unique ID for each visitor, and then save it in the form of a cookie file on each user's machine.

If you use IE to access the Web, you will see all the cookies saved on your hard disk. The most common places they store are: C:\Windows\Cookies (C:\Documents and Settings\ your username in Win 2000 \cookies)

Cookies are saved in the format "keyword key= value".

  2. Creates a cookie object that invokes the constructor of the cookie object to create a cookie. The constructor for the cookie object has two string parameters: the cookie name and the cookie value.

Cookie C=new Cookie ("username", "John");

  3. In the JSP, if you want to transfer the encapsulated cookie object to the client, use the response Addcookie () method.

Format: Response.addcookie (c)

  4. Read the cookies saved to the client, use the GetCookies () method of the Request object, and arrange the cookie objects from all clients as an array when executed, and if you want to remove the cookie object that matches your needs, you need to iterate through the keywords for each object in the array.

Cases:

Cookie[] C=request.getcookies ();

if (c!=null)

for (int i=0;i<c.length;i++)

if ("username". Equals (C[i].getname ()))

Out.println (C[i].getvalue ());

  5. Set the cookie object effective Time: Setmaxage ().

C.setmaxage (3600);

  6. Cookie Application

1. The website is able to know exactly how many people have browsed.

Because of the use of proxy servers, caching, and so on, the only way to help the site to accurately count the number of visitors is to create a unique ID for each visitor. Using cookies, a Web site can do the following:

Determine how many people have visited;

Determine how many visitors are new users (that is, the first visit), how many are old users;

Determine how often a user accesses a Web site.

The website uses the database to achieve this goal. When a user first accesses, the Web site creates a new ID in the database and transmits the ID to the user through a cookie. When the user visits again, the website adds 1 to the counter corresponding to the user ID, and gets the number of visits by the user.

Example: cookie.jsp

<%@ page contenttype= "text/html; charset=gb2312 "

Import= "Java.util.Date"%>

<HTML>

<HEAD>

Access to <title>cookie </TITLE>

</HEAD>

<BODY>

<CENTER>

<font SIZE = 5 COLOR = Blue>cookie Access </FONT>

</CENTER>

<HR>

<P></P>

<%

Creating cookie Variables

Cookie intval = new Cookie ("Intval", "100");

Cookie temp = null;

Response.addcookie (intval); Adding cookie variables to cookies

cookie[] cookies = request.getcookies ();

Get cookie Information

int cookielen = Cookies.length;

Gets the length of the cookie variable array

if (cookielen!= 0)//To determine whether the cookie information was successfully obtained

{

for (int i = 0; i < Cookielen; i++)

{

temp = Cookies[i]; Get cookie variables in cookies array

if (Temp.getname (). Equals ("Intval"))

{//Judge whether to obtain the cookie information named Dateval

%>

The value of the <font color = blue>intval</font> variable in the cookie is

<font color = red><%= intval.getvalue ()%></font><br>

<%

}

       

}

}

Else

{

%>

There is no cookie<br>

<%

}

%>

</BODY>

</HTML>

Example: cookiedate.jsp

<%@ page contenttype= "text/html; charset=gb2312 "

Import= "Java.util.Date"%>

<HTML>

<HEAD>

<TITLE> from cookie access date/Time data </TITLE>

</HEAD>

<BODY>

<CENTER>

<font SIZE = 5 COLOR = blue> from cookie access date/Time data </FONT>

</CENTER>

<HR>

<P></P>

<%

Date now = new Date (); Get the current system time

Cookie dateval = new Cookie ("Dateval", String.valueof (Now.gettime ()));

To convert the stored to cookie time/date value to the number of milliseconds

Response.addcookie (Dateval); Adding cookie variables to cookies

Cookie temp = null;

Dateval = null; Resetting cookie variables

cookie[] cookies = request.getcookies ();

Get cookie Information

int cookielen = Cookies.length;

Gets the length of the cookie variable array

if (cookielen!= 0)//To determine whether the cookie information was successfully obtained

{

for (int i = 0; i < Cookielen; i++)

{

temp = Cookies[i]; Get cookie variables in cookies array

        

if (Temp.getname (). Equals ("Dateval"))

{//Judge whether to obtain the cookie information named Dateval

%>

<font color = blue>dateval</font> in cookies

The value of the variable is <font color = red>

<%= New Date (Long.parselong (Temp.getvalue ())%>

</Font><BR>

<%

}

}

}

else//If no cookie data is available then perform the following description

{

%>

Unable to obtain cookie<br>

<%

}

%>

</BODY>

</HTML>







Related Article

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.