javaweb--jsp Development 1

Source: Internet
Author: User

1, what is JSP, why use JSP.

After using idea to create a Web project, a index.jsp is generated in the WebApp directory

Run directly, the Web site will automatically open such a Web page:

So we can speculate that this index.jsp is the HTML code that determines the initial page of the project, where Hello-world is set when you deploy Tomcat.

So, in fact, JSP is used to write HTML coding a solution, then why do you need additional such a set of solutions?

This is my previous simple use of the servlet:

PrintWriter writer =Resp.getwriter (); Writer.append ("<! DOCTYPE html>\r\n "). Append ("). Append ("). Append ("<title>hello User application</title>\r\n"). Append ("). Append ("<body>\r\n"). Append ("Hello,"). Append (user). Append ("!<br/><br/>\r\n"). Append ("<form action=\" first\ "method=\" post\ ">"). Append ("Enter Your name:<br/>\r\n"). Append ("<input type=\" text\ "name=\" User\ "/><br/>\r\n"). Append ("<input type=\" submit\ "value=\" submit\ "/>\r\n"). Append ("</form>\r\n"). Append ("</body>\r\n"). Append ("

This is in like response add body, for HTML encoding, can be found here HTML and Java combination is not good, resulting in code is very long and messy, especially quotes need to escape character. So in fact we should put this piece of HTML code independent, so we have such a set of JSP (Javaserverpages) hybrid solution, which combines Java code and HTML tags, JSP includes all the HTML tags, as well as the built-in JSP tags, Custom JSP tags and expression languages.

2. JSP processing at run time

    • In fact, JSP is just a carefully designed servlet,jsp is just a syntax sugar, in the runtime JSP code will be converted by the JSP compiler, it will parse out the characteristics of the JSP code and convert them to Java code, the Java class created by JSO will implement the servlet, Finally, it responds to the request like any other servlet.
    • JSPs have their own life cycles like other servlets, unlike web containers, such as in Tomcat, where the JSP will be converted and compiled immediately before the first request arrives, and a compiled JSP can be used between subsequent requests. Many other containers provide the option to precompile all JSPs when the application is deployed.

3. JSP directive

JSP directives are used to set properties related to the entire JSP page, such as the encoding of the Web page and the scripting language.

    • <%@ page ...%> provides control over how JSPs are transformed, rendered, and transmitted to the client
<language= "java"  contentType= "text/html; charset=utf-8"  %>

Where language will tell the container that JSP is using that scripting language, ContentType and CharSet will set the MIME type and character encoding of the JSP page,

Page directive-related properties:

buffer Specify the size of the out object to use the buffer
autoflush control   buffers for out objects
contentType Specify the current JS P page MIME type and character encoding
errorpage Specifies the error handling page that needs to be turned when a JSP page exception occurs
iserr Orpage Specifies whether the current page can be used as an error-handling page for another JSP page
extends Specify which class the servlet inherits from
import importing Java classes to use
Info Define the description of the JSP page
IsThreadSafe Specifies whether access to a JSP page is thread safe
language defines the scripting language for JSP pages, which by default is JAV A
session Specify whether the JSP page uses a session
iselignored Specify Yes Do not execute El expression
isscriptingenabled Determine whether script elements can be used
    • 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.
<file = "Relative URL address"  %>
    • The JSP API allows users to customize the label, a custom tag library is a collection of custom labels. The taglib directive introduces the definition of a custom label collection, including the library path, the custom label.

<uri= "uri"  prefix= "Prefixoftag"  %  >

 

4. Using Java in JSP

There are three ways to write Java code in a JSP:

<%! %>, which can declare a variable or method, note: The variables declared here are global

<%%> Compared to the method above, the local

<%=%>, used to output expressions to the browser, note: This expression cannot be followed by a semicolon

    • Using implicit variables in JSPs

JSP files provide several implicit variables that you can use in scripts and expressions that do not need to be defined anywhere , and the JSP specification requires the translator and compiler of the JSP to supply these variables with exactly the same name. You can see some snippets of code from a compiled JSP file

1    Public void_jspservice (FinalJavax.servlet.http.HttpServletRequest request,Finaljavax.servlet.http.HttpServletResponse Response)2       throwsjava.io.IOException, javax.servlet.ServletException {3 4     FinalJavax.servlet.jsp.PageContext PageContext;5 javax.servlet.http.HttpSession session;6     Finaljavax.servlet.ServletContext Application;7     Finaljavax.servlet.ServletConfig config;8Javax.servlet.jsp.JspWriter out =NULL;9     FinalJava.lang.Object page = This;TenJavax.servlet.jsp.JspWriter _jspx_out =NULL; OneJavax.servlet.jsp.PageContext _jspx_page_context =NULL; A  -     Try { -Response.setcontenttype ("text/html; Charset=utf-8 "); thePageContext = _jspxfactory.getpagecontext ( This, request, response, -                   NULL,false, 8192,true); -_jspx_page_context =PageContext; -Application =Pagecontext.getservletcontext (); +Config =pagecontext.getservletconfig (); -out =pagecontext.getout (); +_jspx_out =Out ; A}

A total of 8 implicit variables are defined here, respectively:

    • Request, response

  Instances of the HttpServletRequest class and the HttpServletResponse class

    • PageContext

An instance of the PageContext class that provides access to all objects in the JSP page and to namespaces

    • Session

An instance of the HttpSession class, if the session attribute in the page directive is set to false then there is no such variable in the JSP

    • Application,

An instance of the ServletContext class, related to the application context

    • Config

An instance of the ServletConfig class that can use this object to access the configuration of a JSP servlet, such as a servlet initialization parameter

    • Out

An instance of the JspWriter class for outputting the results to a Web page

    • Page

Similar to the This keyword in Java classes, provides several convenient ways to request attributes and reply-to attribute values, access requests and responses, include other files, and forward requests

Finally, there is a exception that does not appear here, this variable needs to be set to True by the Iserrorpage attribute of the page directive, which indicates that the purpose of the JSP is to handle the error before this variable appears.

Create a first.jsp file and add the following code

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "%><%!Private Static FinalString default_user = "Guest";%><%String User= Request.getparameter ("User"); if(User = =NULL) {User=Default_user; }%><! DOCTYPE html>Hello,<%= User%>! <br/><br/> <form action= "first.jsp" method= "POST" >Enter user name:<br/> <input type= "text" name= "user"/><br/> <input type= "Submit" value= "Submit"/> </form> </body>

Compile and run, enter http://localhost:8080/hello-world/first.jsp in the browser to get the following page

The previous servlet is implemented here, but you should not use Java in JSP

5. Comments

There are four ways to implement code annotations in a JSP:

    • XML annotations
  <!-- -

But this type of comment will be sent to the client, the browser will ignore it, but it will appear in the source code of the response any JSP code in the comment will be processed,

<!--This is the annotated content <%! Private Static Final String default_user = "Guest";%>--

The Java code here will be executed.

    • Traditional Java line annotations and Java block annotations, i.e.//... and/*...*/
< %      = request.getparameter ("user"); //      null) {//        = default_user; //    } /        *= req.getparameter ("pwd")    ;   */% > 
    • JSP annotations
<JSP commented out content--%>

6. Using Servlets and JSPs together

    • To configure JSP properties in the deployment descriptor

In the empty Web. xml file (including <display-name> only), add the following:

  <Jsp-config>    <Jsp-property-group>      <Url-pattern>*.jsp</Url-pattern>      <Url-pattern>*.jspf</Url-pattern>      <page-encoding>UTF-8</page-encoding>      <Scripting-invalid>False</Scripting-invalid>      <Include-prelude>/web-inf/jsp/base.jspf</Include-prelude>      <trim-directive-whitespaces>True</trim-directive-whitespaces>      <Default-content-type>Text/html</Default-content-type>    </Jsp-property-group>  </Jsp-config>

The label <jsp-config> can contain any number of </jsp-property-group> tags, which are used to differentiate the properties of different JSP groups. For example, to define a common set of properties for all JSPs in the/web-ing/jsp/admin folder, and to define another set of properties for/web-ing/jsp//help, you need to differentiate the different attribute groups by defining the <url-pattern> tags. One is set to <url-pattern>/web-ing/jsp/admin/*.jsp</url-pattern>, and the other is set to <url-pattern>/web-ing/ Jsp/help/*.jsp</url-pattern>.

  

javaweb--jsp Development 1

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.