1.4 basic syntax for JSP
1.1 JSP annotations
<%--Comment Content--%>
1.2 JSP Declaration
<%! Declaring part%> declaring variables and methods
For example:
1 <%! 2 3 int count; 4 5 Public String info () 6 7 { 8 9 Return "Hello"; Ten One }%>
Declared variables and methods become member variables and methods of the Servlet class, which can be decorated with access modifiers such as public, private, or static adornments.
1.3 Output JSP expression
<%= expression%>
Example: <%=info ()%>
1.4 JSP Script
<% Java Code%>
The JSP script is converted to the executable code of the _jspservice method in the servlet, which means that the JSP script part can declare the variable, but this is a local variable and is not decorated with an access modifier.
2.3 Compiler directives for JSP
The JSP compiler directive is a message informing the JSP engine that it does not generate output directly.
Syntax format for compiling directives: <%@ compiler directive Name Property name = "Property Value" ....%>
2.1 page directive
Page directive Properties:
Language: Default to Java
Extends: Specifies the parent class inherited by the Java class that the JSP page compiles from or the implemented interface
Import: for importing packages. The default imported package has java.lang.*,javax.servlet.*,javax.servlet.jsp.*,javax.servlet.http.*.
Session: Set whether the page requires a session
Buffer: Specifies the size of the output buffer
Info: Set up information for this JSP program
ErrorPage: Specify error page
Iserrorpage: Set this JSP page as an error handler
ContentType: Set page format and encoding
Pageencoding: Specifies the coded character set of the generated Web page
2.2 Include directives
<%@ include file= "script.jsp"%>
3.7 Action commands for JSP
3.1 Jsp:forward
The forward instruction is used to forward the page response to another page or servlet, which can be added with additional parameters, which can be obtained using the GetParameter () method of the HttpServletRequest class on the target page.
Command syntax:
1 <jsp:forward page= "{relativeurl | <%=expression%}"/>2 <jsp:param name= "" Value= ""/>3 </jsp:forward>
For example:
1 <jsp:forward page= "result.jsp" >2 <jsp:param name= "age" value= "+"/ >3 </jsp:forward>
1 2 <%=request.getparameter ("Age")%>
3.2 Jsp:include
Used to include a page, it does not import the compilation instructions of the included page, only the body content of the page is inserted into the page.
Syntax format:
1 <jsp:include page= "{relativeurl | <%=expression%}" flush= "true" >2 <jsp:param name= "" value= ""/>3 </jsp:include>
3.3 Jsp:usebean Jsp:setproperty Jsp:getproperty
The Usebean directive is used to initialize a Java instance in a JSP page. SetProperty sets the JavaBean property value, getproperty the output JavaBean property value.
Syntax format:
1 <jsp:usebean class= "scope=" page | request | session | application "/> // ID is the instance name of JavaBean 2 <jsp:setproperty name= "" property= "" value= ""/> //name is JavaBean instance name 3 <jsp:getproperty name= "" property= ""/>
3.4 Jsp:plugin
Primarily used to download server-side JavaBean or applets to client execution
3.5 Jsp:param
Used to set parameters, cannot be used alone, and should be used with include, forward, or plugin.
4.9 built-in objects in a JSP
An instance of the
- Application:javax.servlet.ServletContext that represents the application itself to which the JSP belongs. Common methods are instances of the getattribute (), Setattribu (), and Getinitparameter ()
- config:javax.servlet.ServletConfig, which represent the configuration information for the JSP. Common methods are Getinitparameter () and Getinitparameternames ()
- exception : an instance of java.lang.Throwable that can be used only if the Iserrorpage property of the compile instruction page is true. Common methods are instances of GetMessage () and Printstacktrace ()
- Out:javax.servlet.jsp.JspWriter, which represent the output stream of a JSP page
- page: Represents the page itself , which is the this in the servlet, where the page can be used to use this
- An instance of PageContext:javax.servlet.jsp.PageContext that represents a JSP page context that allows access to shared data on the page. Common methods are Getservletcontext () and Getservletconfig (), such as
- An instance of Request:javax.servlet.http.HttpServletRequest that gets the client request parameter that must be used by the object. Common methods are GetParameter (), Getparametervalues (), SetAttribute (), and getattribute
- response : an instance of Javax.servlet.http.HttpServletResponse that represents the response of the server to the client. Common methods are Getoutputstream (), Sendredirect (), and so on
- session : an instance of Javax.servlet.http.HttpSession, representing a sequential session, when the client browser establishes a connection with the site, the session begins, and the client closes the browser when the session ends
JSP built-in objects are initialized in the _jspservice method, so these built-in objects can be used only in JSP scripts, JSP output expressions, and not in JSP declarations.
4.1 Application Object
Application objects typically have two effects:
1) share data across multiple JSPs and servlets throughout the Web application
2) Access the configuration parameters of the Web App
4.1.1 multiple JSPs, Servlets share parameters
1 // get-application.jsp
2 <%! 3 int i; 4 %>5 <%6 application.setattribute (' Counter ', string.valueof (+ +I )) ; 7 %>
1 // put-application.jsp
2 <%=application.getattribute (' counter ');%>
1 //Servlet
2@WebServlet (name= "Get-application ", urlpatterns= ("Get-application "))3 Public classGetapplication extends HttpServlet {4 Public voidService (HttpServletRequest request, httpservletresponse response) throws IOException {5Response.setcontexttype ("text/html;character=gb2312 ");6PrintWriter out=Response.getwriter ();7 out. println ("");8 out. println ("Test Application");9 out. println ("</title>");TenServletContext sc =Getservletconfig.getservletcontext (); One out. println ("The current counter value in the application is:"); A out. println (Sc.getattribute ("Counter")); - out. println ("</body>"); - } the}
4.1.2 get web App configuration parameters
1 // getwebparam.jsp 2 <%3 String driver = application.getinitparameter ("Driver"); 4 String url = application.getinitparameter ("url"); 5 String user = application.getinitparameter ("user"); 6 String Password = application.getinitparameter ("password"); 7 %>
4.2 Config Object
1 // config.jsp 2 3 The value of the name configuration parameter is: <%=config.getinitparameter ("name")%>
1 //Web. XML2 3<servlet>4<servlet-name>config</servlet-name>5<jsp-file>/config.jsp</jsp-file>6<init-param>7<param-name>name</param-name>8<param-value>juedi</param-value>9</init-param>Ten<servlet-mapping> One<servlet-name>config</servlet-name> A<url-pattern>/config</url-pattern> -</servlet-mapping>
4.3 Exception object
In the exception handling mechanism of JSP, an exception handling page can handle the exception of multiple JSP page script parts. The exception handling page is specified by the ErrorPage property of the page directive.
1 // 2 3 <%@ Page errorpage= "error.jsp"%>4 <%5 int a = 6; 6 int C = A/0; 7 %>
1 // error.jsp 2 3 <%@ page iserrorpage= "true"%>4 <body>5 Exception type is: <%= Exception.getclass ()%><br/>6 exception information is: <%=exception.getmessage ()%>7 </ Body>
4.4 Out Object
All the places that are used out can be replaced with output expressions. The essence of the <%=......%> expression is Out.write ().
4.5 PageContext Object
This object is mainly used to access shared data between JSPs, can access page, request, session, application range of variables, can be used Pagecontext.getattribute (name, scope) To get the property value for any scope.
1 // pagecontexttest.jsp 2 3 <%4 pagecontext.setattribute ("page", "Hello"); 5 pagecontext.setattribute (' name ', ' Juedi ', pagecontext.session_scope); 6 pagecontext.setattribute (' Pass ', ' Pass ', pagecontext.application_scope); 7 %>
PageContext can also get other objects:
ServletRequest Getrequest ()
Servletresponse GetResponse ()
ServletConfig Getservletconfig ()
ServletContext Getservletcontext ()
HttpSession getsession ()
4.6 Request Object
4.6.1 GET request Header/Request parameters
The request header is automatically added by the browser and the request parameters are specified by the customer.
method to get the request header:
String GetHeader (): Gets the value of the specified request header
Java.util.enumeration<string> getheadernames (): Gets the name of all request headers
Java.util.enumeration<string> getheaders (): Gets multiple values for the specified request header
int Getintheader (): Gets the value of the specified request header and converts to an integer
method to get Request parameters:
String getparameter (): Gets the value of the parameter of the specified name
Map Getparametermap (): Get the Map object consisting of parameter names and values
Enumeration Getparameternames (): Gets the enumeration object that all request parameter names comprise
String[] Getparametervalues (): Gets the value of the parameter of the specified name
1 //request.jsp2 3<%4Enumeration<string> Headernames =request.getheadernames ();5 while(Headernames.hasmoreelements ())6 {7String Headername =headernames.nextelement ();8OUT.PRINTLN (Headername +--+ request.getheader (headername) + "<br/>");9 }TenString name =request.getparameter ("name"); One%> A
4.6.2 Properties for Operation request Scope
1 // draw.jsp 2 3 <body>4 <form method= "POST" action= "first.jsp" >5 take money: <input Type= "text" name= "balance"/>6 <input type= ' submit ' value= ' Submit '/>7 </ Form>8 </body>9
1 //first.jsp2 3<%4String Bal =request.getparameter ("balance");5 DoubleQian =double.parsedouble (BAL);6 if(Qian < 500)7Out.println (' Give you ' +Qian);8 Else9 {Tenlist<string> info =NewArraylist<string>(); OneInfo.add ("1111"); AInfo.add ("2222"); - Request.setattribute ("info", info); - } the%> -<jsp:forward page= ' second.jsp '/> -
1 //second.jsp2 3<%4String Bal =request.getparameter (' balance ');5 DoubleQian =double.parsedouble (BAL);6list<string> info = (list<string>) request.getattribute (' info ');7 for(String tmp:info)8OUT.PRINTLN (tmp + "<br/>");9Out.println ("Give You" +Qian);Ten%>
When forward a user request, the parameters of the request parameters and requests range are not lost, that is, after forward or the original request, the request is not sent to the server again.
4.6.3 performing forward or include
The HttpServletRequest class provides a getrequestdispatcher (String path) method, where path is the path that you want to forward or include, and the method returns a Requestdispacher.
Getrequestdispatcher ("a.jsp"). Include (request, response)
4.7 Response Object
4.7.1 response generating non-character responses
An Out object can also generate a response, but out is an instance of JspWriter, and JspWriter is a subclass of writer, and writer is a character stream that cannot produce non-character content.
JSP Learning Notes