JSP Learning Notes

Source: Internet
Author: User

I. Introduction to JSP

    • JSP---Java Server Pages
    • The features and benefits of having a servlet (itself being a servlet)
    • Embed JSP code directly in HTML
    • The JSP program is converted by JSP engine into a servlet code, which is then compiled into a class file loaded into the execution
    • Only when the client requests the JSP for the first time will it need to convert, compile
    • Advantages:
      • Excellent performance
        • Better than cgi,php,asp
      • Platform agnostic
        • OS independent, Web server agnostic
      • Scalability
        • Tag extension mechanism to simplify page development

Second, JSP basic syntax

JSP traditional syntax
    • Declaration statement
    • Scriptlet Small Program Segment
    • Expression expressions
    • Comment notes
    • Directives directive
    • Action Actions Command
    • Built-in objects

Jstl

Jsf

1,jsp-declaration

Basic syntax: <%! %> Description: The variables and methods declared here will be kept as a unique copy until the JSP program stops executing
body><%! intCount=0; The %>//member variable, which is equivalent to a global variable, because the JSP is first converted to a servlet,servlet only new instance. Method can be defined    <% intCount2=0; %>//Local variables, cannot define methods    <h>Count:<%= ++Count%><BR>Count2:<%= ++Count2%>    </h>  </Body>

2,scriptlet

Basic syntax: <% program code area%> can be put into any Java program code
<!--HTML annotations, client source can be seen--<%--JSP comments--%> <%//Note 1 Java annotations  /*NOTE 2*/String BgColor=request.getparameter ("BgColor"); BooleanHascolor; if(bgcolor!=NULL) {Hascolor=true; }  Else{Hascolor=false; BgColor= "White"; }  %> <body bgcolor=<%= BGCOLOR%>> <%if(Hascolor) {out.println ("BgColor:" +BgColor); }        Else{out.println ("Background is white"); }     %> </body>

3, expression

Basic syntax: <%=. ...%> = The following must be a string variable or an expression that can be converted to a string is not required; End only one line example: <%= "Hello World"%> <%=i+1%> <%=request.getparameter ("name")%>

4,derictive

    • Directive (compile instruction) is equivalent to a command during compilation
    • Format:
      • <% @Directive Property = "Property value"%>
    • Common directive:
      • Page
      • Include
      • Taglib
A,derictive-page indicates the basic format of communication with JSP Container:
<% @page language= "script language" | extends= "ClassName" |  Import= "Importlist" |Buffer= "NONE|KB Size" | --None: No buffering, default 8k session=true|false"| --whether the session can be used, by default true AutoFlush=true|false” --whether the buffer is automatically cleared, by default true IsThreadSafe=true|false"| --default False (never set to true) info= "InfoText" | --any character errorpage = "Errorpageurl" | iserrorpage= "true| false"| contentType= "Contenttyepinfo" | pageencoding="gb2312" %>

B,directive--include the instructions during compilation

    • Include the specified JSP program or HTML file in the
    • Format:
      • <% @include file= "fileurl%>
    • JSP engine will be in the JSP program conversion period of the file property set files are included in, and then start to perform the conversion and compilation work. (Copy the file's code to that location, and then convert and compile, creating only one Java and Class)
    • Limit:
      • Cannot pass parameters to FileURL
      • Can't abc.jsp?user=aaa

5,action

Actions (action commands) are common during run-time commands:
    • Jsp:usebean
      • Jsp:setproperty
      • Jsp:getproperty
    • Jsp:include
    • Jsp:forward
      • Jsp:param
    • Jsp:plugin
      • Embed applets

A,jsp:include/jsp:param

    • Used to dynamically include JSP programs or HTML files, etc.
    • Unless this command is executed, it will not be compiled by JSP engine such as Tomcat.
    • Format:
      • <jsp:include page= "Urlspec" flush= "true"/>
      • <jsp:include page= "Urlspec" flush= "true" >
        • <jsp:param name= "paramname" value= "Paramvalue"/>
      • </jsp:include>
    • Jsp:param parameters and corresponding values used to set the include file
    • And the difference between the compile directive include
      • The Include compiler directive embeds the program content specified by the file property at the time of conversion of the JSP program, and then compiles and executes, while the include directive is not compiled at the time of the conversion, only if the client request period is executed until it is loaded by dynamic compilation
      • Include cannot take parameters, and <jsp:include> can

B,jsp:forward/jsp:param

Used to route the contents of a JSP to the JSP program specified by the page or to the servlet processing (URL) format: <jsp:forward page= "Urlspec" flush= "true"/><jsp:forward Page= "Urlspec" >

<jsp:param name= "paramname" value= "Paramvalue"/>

</jsp:forward>

<jsp:param> is used to specify parameters and their corresponding values for example: test.jspforward.jsp/forforward.jsp
<jsp:forward page= "forforward.jsp"/>
forward1.jsp/forforward1.jsp (with parameters)
<jsp:forward page= "forforward1.jsp" >    <jsp:param name= "name" value= "M"/>    <jsp:param name= " Oldname "Value= ' <%=request.getparameter (" name ")%> '/>    <jsp:param name= ' roles ' value= ' manager '/> </jsp:forward>

Forward pages and forward pages use the same request that corresponds to the difference between response.sendredirect<jsp:forward> and Response.sendredirect.
    • <jsp:forward>
Statements that use the same requestforward will not continue to be sent to the client Fast server internal conversion, you can pass parameters
    • Response.sendredirect
is a different requestsend after the statement will continue to execute, unless the return slow need to the client's round trip, you can go to any page can pass parameters, directly written behind the URL C,jsp:usebean
    • with Jsp:usebean, you can use the basic elements of a well-defined bean
    • bean in a JSP:
      • You must have a constructor with no arguments. The null constructor is called when the JSP element creates the bean
      • bean class should not have any public instance variables, that is, direct access to instance variables is not allowed, the first letter of the variable name must be lowercase
    • Basic usage:
      •  <jsp:usebean id= "CB" class= "Bean. Counterbean "type=" TypeName "scope=" page|request|session|application ">  </jsp: 
          Usebean>   
      • test.jsp/counterbean.java do not use naked classes (specification requirements) should be placed inside the package
Import // Response.sendredirect (".. /servlet/showrs "); %>New Counterbean (); %><font color= "Red" size= "5" >    class= "Bean. Counterbean ">              New Counterbean () --%></jsp:usebean><jsp:setproperty name=" CB "property= "Count" value= "/>     <%--equivalent to Cb.setcount (Integer.parseint (") ")--%><jsp:getproperty name=" CB " property= "Count"/>                <%--equivalent to Out.print (Cb.getcount ())--%>        

    • Jsp:usebean the meaning of each parameter:
ID: object Instance name Scope:bean scope of action, default to page, valid Class:bean class name (full name) Type:bean instance type for the entire JSP page, can be this class, or its parent class, or implemented interface, default to this class
    • The meaning of the scope parameters:
Page: covers only pages using JavaBean, equivalent to local variables Pagebean.jsp/counterbean.java) Request: The valid range is limited to requests using JavaBean (requestbean.jsp/ Requestbean2.jsp/counterbean.java) session: The valid range is valid throughout the user's connection (the entire session stage) (sessionbean.jsp/session2.jsp/ Counterbean.java) Application: The effective range covers the entire application. Which is valid for the entire site (Application.jsp/application2.jsp/counterbean.java)
    • Format of Jsp:setproperty:
<jsp:setproperty name= "Beanname"

Property= "PropertyName" |property= "*"

Value= "Property value" |param= "ParamName"/>

Equivalent to the Beanname.setpropertyname (value) method call (Setxxx () method)
    • Format of Jsp:getproperty:
<jsp:getproperty name= "Beanname" property= "PropertyName"/> Equivalent to Beanname.getpropertyname () method call (GetXxx () method)
    • Establish association between form parameters and bean properties
By specifying the name of the form element by param, the corresponding bean property name is specified by Perperty, which establishes the association of the two variables (Saleentry.jsp/saleentry.java, passing parameters by URL)
<jsp:setproperty     name= "entry"    property = "NumItems"       param= " NumItems "/>   //equivalent to <jsp:setproperty name=" entry "NumItems =<%=reuest.getparameter(" numitems")%>/> 

Use * To set the association between all properties and input parameters (Sayhellobean.html/sayhellobean.jsp/hellobean.java)
    • When establishing the correspondence between bean properties and form parameters, the server automatically converts the corresponding parameters into data that matches the property type.
    • Initial explanation of the coding problem
      • <%=new String (Hello.getname (). GetBytes ("Iso8859_1"), "GBK")%>
      • Request.setcharacterencoding ("gb2312");

Third, JSP built-in objects

JSP built-in object out request Response Pagecontextà very few Session application Config used rarely exception Page with very few
    • JSP Programming---out
The out built-in object is a buffered output stream that is used to return information to the client. It's an example of Javax.servlet.jsp.JspWriter. Typical application: Output content to clients common methods: println (): Output various types of data to clients write () NewLine (): Outputs a newline character close (): Off output stream flush (): Data in output buffer Clearbuffer (): Clears data in buffer while outputting data to client clear (): Clears data in buffer, but does not output data to client GetBufferSize (): Return The size of the back buffer
    • JSP Programming--request
Request built-in objects represent requests to invoke JSP pages. Typically, the request object is an instance of the Javax.servlet.http.HttpServletRequest interface typical application: Through Request.getparameter ("ParamName") You can get the parameter values that the form submits to the requested header, information (such as browser version, language and encoding, etc.), the requested method (Get/post), the requested parameter name, the parameter value, the host name of the client, and other common methods: GetMethod () : Returns the method that the client transmits data to the server GetParameter (String paramname): Returns the value of the parameter that the client transmits to the server, which is specified by ParamName getparameternames ()    : Gets the name of all parameters that the client sends to the server, and the result is an enumeration type data (enumeration) Getparametervalues (String name): Gets all values for the specified parameter, specified by name    Getrequesturi (): Obtain the client address of the request string getremoteaddr (): Gets the IP address of the client Getremotehost (): Gets the client machine name getServerName (): Gets the name of the server Getservletname (): script file path requested by client Getserverport (): Gets the server-side port counterpart class: Javax.servlet.http.HttpServletRequest
    • Jsp-response
Indicates that the response returned to the client is an instance of the Javax.servlethttp.HttpServletResponse interface is often used to set HTTP headers, add cookies, set the type and status of the response content, send HTTP redirects, and encode URLs Common method: Addcookie (Cookie cookie): Adds a cookie object that holds a specific message AddHeader (String name,string value) on the client: adds the HTTP header information that will be sent       Sent to client Containsheader (string name): Determines whether the HTTP file header for the specified name exists senderror (int): Sends the wrong message to the client sendredirect (string url): Redirect JSP file Differences with <jsp:forward> Sendredirect Two requests are initiated by the client, and the different request object Jsp:forward is the same request and is forwarded internally within the server Setcon Tenttype (String ContentType): Sets the MIME type and encoding method
    • Jsp-cookie
The non-connectivity of the HTTP protocol requires a mechanism to preserve the state of the C/s between cookies: A text file saved to the client, with a specific customer-related Cookie to save the data in the form of a "name-value" pair get the corresponding name and value by GetName and GetValue
    • Jsp-session & Application
<% @page session= "true"%> (default)--indicates that the session function has been started in the JSP page common method: void SetAttribute (String name,object value) Object getattribute (String name) Boolean isnew () application ServletContext Four, servlet and JSP communication
    • Invoke Servlet from JSP available <jsp:forward>
Request information is automatically passed to the servlet or via Sendredirect
<jsp:forward page= "/servlet/servlettojsp"/>
<%
Response.sendredirect (".. /servlet/showparameters?a=b ");
%>

    • Invoke JSP from servlet using
The forward (req, res) method of the RequestDispatcher interface request information needs to be passed explicitly (in the Req, res parameters) or by Sendredirect
 Public classservlettojspextendsHttpServlet { Public voiddoget (httpservletrequest req,httpservletresponse resp) {Try {            //set the property and submit it to servletusejsp.jspResp.setcontenttype ("text/html;charset=gb2312"); Req.setattribute ("Servletname", "servlettojsp"); Getservletconfig (). Getservletcontext (). Getrequestdispatcher ("/servlet_jsp/servletusejsp.jsp"). Forward (req, resp);
//. forward (req, resp) sends the servlet request to another page
//. Include (req, resp) contains the contents of another page in response
}Catch(Exception e) {e.printstacktrace (); } }}

For example: fromjsptoservlet.jsp/servlettojsp.java/servletusejsp.jsp forward can use "/" path, refers to the Web app root path, servlet forward JS P must use "/" to start Jspsendredirect to servlet should use relative path, because here "/" refers to the root path of the Web site, servlet sendredirect JSP is also

JSP Learning Notes

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.