Relationship between JSP and Servlet and between JSPServlet

Source: Internet
Author: User

Relationship between JSP and Servlet and between JSPServlet

Relationship between JSP and Servlet

Jsp Introduction

1. JSP (Java Server Pages) is a dynamic resource on the JavaWeb Server. It serves the same purpose as html Pages, displaying and retrieving data. 2. jsp: As a request initiation page, such as a display form or hyperlink. : As the request end page, such as displaying data. 3. Servlet: serves as a link for processing data in the request. 4. jsp = html + java Script + jsp tag (Instruction) a total of nine objects can be directly used in jsp, which are called 9 large built-in objects 5. three java scripts: <%... %>: Write java code snippets (similar method) <% =... %>: Used to output the result of an expression (or variable. <% !... %>: Declaration, used to create the member variables and member methods of the class (similar to the class) 6. jsp comment: <% -... -%> Comments are ignored when the server compiles jsp into a java file!

Jsp principles (see source code)

1. jsp is actually a special Servlet. When the jsp page is accessed for the first time, the server will compile jsp into a java file and then compile java. class then creates the class Object and calls its service () method to directly call the service () method when requesting the same jsp for the second time.

Three jsp commands

Page

<% @ Page language = "java" info = "xxx "... %> ** 1. pageEncoding and contentType: pageEncoding: it specifies the encoding of the current jsp page. As long as it does not lie, there will be no garbled code! You must use pageEncoding to compile jsp into. java on the server! ContentType: It indicates adding a response header: Content-Type! It is equivalent to response. setContentType ("text/html; charset = UTF-8"). If only one of the two attributes is provided, the default value of the other is set to that one. If neither attribute is set, the default value is iso import: import package! Multiple errorPage and isErrorPage errorPage: if an exception is thrown on the current page, the error page is used to specify the isErrorPage: whether the current page is an error page! When this attribute is set to true, status code 500 is set on this page! In addition, this page can use exceptions from nine built-in objects!
1.
 
  
There are two ways to use: 2.
  
   
And
   
    
Child element; 3.
    
     
And
     
      
Child element; 4. Where
      
        Is the specified response code;
       
         The forwarding page;
        
          Is the exception type thrown.
        
       
      
     
    
   
  
 
 
     
  
   404
      
  
   /error/errorPage.jsp
   
       
  
  
   java.lang.RuntimeException
          
  
   /index.jsp
        
 

Include-> static include

1. Similar to the include () method of RequestDispatcher! 2. <% @ include %> it is completed when jsp is compiled into a java file! They generate a java (servlet) file and generate a class! 3. RequestDispatcher's include () is a method that contains and is contained in two Servlets, namely two. class! They just merged the response content at runtime! 4. Role: break down the page and combine it with the contained method. The unchanged part of a page is an independent jsp, and we only need to process the changed page.

Taglib-> import tag Library

Two attributes:

Prefix: Specifies the prefix of the tag library on this page! Name by ourselves!

Uri: Specifies the location of the tag library!

<% @ Taglib prefix = "s" uri = "/struts-tags" %> prefix usage

Nine built-in objects

-Nine out (JspWriter) objects that can be directly used in jsp without declaration: equivalent to response. getWriter () is used to send text data to the client. config (ServletConfig): corresponds to ServletConfig in "real"; page (current real JSP type): "this" of the current JSP page ", that is, the current Object refers to the Object type; pageContext (PageContext): Page Context Object, which is the last unspecified domain Object; exception (Throwable ): this object can only be used on the error page; request (HttpServletRequest): the object of the HttpServletRequest class; response (HttpServletResponse): the object of the HttpServletResponse class; application (ServletContext): Servl The object of the etContext class; session (HttpSession): the object of the HttpSession class, which is not available on every JSP page, if <% @ page session = "false" %> is set on a JSP page, the session cannot be used on this page. PageContext (one of the top 9 !) Servlet has three fields, and JSP has four fields! ServletContext: the entire application session: the entire session (only one user in one session) request: A request chain! PageContext: a jsp page! This field shares data between the tags used in the current jsp page and the current jsp page! Domain object proxy other domains: pageContext. setAttribute ("xxx", "XXX", PageContext. SESSION_SCOPE); Global Search: pageContext. findAttribute ("xxx"); from small to large, dependent search! Obtain the other 8 built-in objects:

JSP action tag

-'
 
  
'Example:
  
   
To include the specified page. Suppose there are two JSPs, a. jsp and B. jsp, which are encoded into servlets respectively, and the inclusion process will be executed only when the Servlet is executed. This is also the difference between the include command and the include label. -Note :'
   
    
', This is acceptable! Because the include command is included only during execution, you can determine the value of the variable myfile during execution. -This label uses the RequestDispatcher # include () method to complete the include -'
    
     
'Example:
     
      
For example, the following content exists in a. jsp:
      
        The content in a. jsp is not displayed in the browser, but only in B. jsp. In addition
       
         The content under the tag is not executed. -'
        
          'The tag is a child label of the sum, used to pass parameters to other pages.
        
       
      
     
    
   
  
 
     
   
  
 

In B. jsp, you can use request. getParameter ("username") to obtain the parameter value.

JavaBean

Public constructors are required. If the member variables provide the getter/setter method, they are called the javabean attribute. JavaBean is mainly used to operate classes through reflection!

Because the newInstance () method of the Class is required to create an instance of the Class, the Class must provide a public parameter-free constructor.

Introspection

-Introspection class-> Bean information-> attribute descriptor-> Method corresponding to the get/set attribute! -> Reflection-Get BeanInfo-BeanInfo = Introspector through the Class object. getBeanInfo (User. class);-Get all attribute descriptor objects through BeanInfo-PropertyDescriptor [] pds = info. getPropertyDescriptors ();-PropertyDescriptor:-String name getName (): get the current property name-Method getReadMethod (): get the get Method reflection object-Method getWriteMethod (): get set Method reflection object-jar package commons-beanutils.jar, commons-logging.jar-set Javabean Class through reflection
 
  
Clazz = User. class; Object user = clazz. newInstance (); BeanUtils. setProperty (user, "username", "admin"); BeanUtils. setProperty (user, "password", "admin123");-get the attribute value String username = BeanUtils. getProperty (user, "username");-encapsulate Map data into a JavaBean object
 
Map
 
   map = new HashMap
  
   ();map.put("username", "admin");map.put("password", "admin123");
  
 
User user = new User (); BeanUtils. populate (user, map); requirement: the map key name must be the same as the property name of the User class. Do not assign values!

Tag related to JavaBean in JSP

 1  
    
Check whether the domain attribute user1 exists in the page domain. If so, obtain it directly. If it does not exist, create it! Equivalent to: User user1 = pageContext. getAttribute ("user1"); if (user1 = null) {user1 = new User (); // create user1 object pageContext. setAttribute ("user1", user1); // save to page domain} You can use the scope attribute to specify the operation setting attribute value:
    
-Name: Specify JavaBean-property named user1: Specify the attribute name to be set-value: Specify the attribute value to be set is equivalent to User user1 = (User) pageContext. getAttribute ("user1"); user1.setUsername ("admin ");

Get Attribute Value

    
    

Output the username attribute value of the javaBean user1

Equivalent
User user1 = (User) pageContext. getAttribute ("user1 ");
Out. print (user1.getUsername ());

EL expression

-EL: Expression Language, which can be used directly on the JSP page! The JSP page can also ignore EL: <@ page isELIgnored = "true" %> EL is used to replace <% =... %>-EL 11 built-in objects EL can output all the items in 11 built-in objects! 11 built-in objects, 10 of which are Map! PageContext is not a map, it is a PageContext type, 1 is a top nine $ {pagination. xxx}, $ {requestScope. xxx}, $ {sessionScope. xxx}, $ {applicationScope. xxx} param: corresponds to a parameter. It is a Map, where the key parameter name and value are parameter values. This parameter is applicable to single-value parameters. ParamValues: corresponds to a parameter. It is a Map. The key parameter name and value are multiple parameter values, which are suitable for multi-value parameters. Header: corresponds to the Request header, which is a Map, where key represents the header name, value is a single header value, applicable to the single-value request header headerValues: corresponds to the Request header, It is a Map, key indicates the header name, and value indicates multiple headers. this parameter is applicable to the multi-value request header initParam: Get
    
     
Parameters in! Cookie: Map
     
      
Type, where key is the cookie name and value is the cookie object. $ {Cookie. username. value} pageContext: it is of the PageContext type! $ {PageContext. request. contextPath} the built-in objects of the EL operation in four fields: Map-type pagererequestscope sessionScope applicationScope
     
    
-$ {Pagination. user}: Output pageContext. getAttribute ("user") $ {requestScope. user}: Output request. getAttribute ("user"); $ {sessionScope. user}: Output session. getAttribute ("user"); $ {applicationScope. user}: output application. getAttribute ("user ");
$ {User} searches for the user in pagination, requestScope, sessionScope, and applicationScope in sequence. If the user is found, stop searching immediately. -Operate JavaBean <% User user = new User (); user. setUsername ("zhangSan"); user. setPassword ("123"); pageContext. setAttribute ("user", user); %>
${pageScope.user.username}${pageScope.user.password}
-Operation List <% User user = new User (); user. setUsername ("zhangSan"); user. setPassword ("123"); List list = new ArrayList (); list. add (user); pageContext. setAttribute ("list", list); %>
${pageScope.list[0].username}${pageScope.list[0].password}
-Map operation <% User user = new User (); user. setUsername ("zhangSan"); user. setPassword ("123"); Map map = new HashMap (); map. put ("u1", user); pageContext. setAttribute ("map", map); %>
${pageScope.map['u1'].username}${pageScope.map['u1'].password}${pageScope.map.u1.username}${pageScope.map.u1.password}

EL operation parameter built-in object: Map type

param:Map
    
     paramValues:Map
     
      ${param.username}:request.getParameter("username")${paramValues.hobby}:request.getParameterValues("hobby");
     
    

EL Operation Request Header built-in object: Map type

header:Map
    
     headerValues:Map
     
      ${header.UserAgent}${headerValues.UserAgener[0]
     
    
Cookie-related built-in object: Map type
Cookie: Map
    
     
The key is the Cookie name, and the value is the Cookie object.
    
$ {Cookie. jsessionid. value}: Get sessionid
Built-in pageContext object: PageContext type
$ {PageContext. request}, equivalent to pageContext. getRequest () $ {pageContext. session}, equivalent to pageContext. getSession () $ {pageContext. request. contextpath}, get the project name $ {pageContext. session. id}, get sessionId
-The most important thing in EL is to operate the four domains! To use the EL function library, you need to import the tag library on the JSP page: import the tag Library: <% @ tablib prefix = "fn" uri =" https://java.sun.com/jsp/jstl/functions "%> String toUpperCase (String input): converts a parameter to a String toLowerCase (String input): converts the parameter to a lowercase int indexOf (String input, String substring): from a large String, location of the output small string! Boolean contains (String input, String substring): Check whether a large String contains a small String boolean containsIgnoreCase (String input, String substring): whether to include boolean startsWith (String input, string substring): whether to use a small String as the prefix boolean endsWith (String input, String substring): whether to use a small String as the suffix String substring (String input, int beginIndex, int endIndex ): substring truncation String substringAfter (String input, String substring): obtains the substring substringBe after the position of the substring in the String. Fore (String input, String substring): gets the String escapeXml (String input) before the position of a small String in a large String ): escape "<", ">", "&", "'", and "in input to String trim (String input ): remove leading and trailing spaces String replace (String input, String substringBefore, String substringAfter): replace String [] split (String input, String delimiters): split String, get the int length (Object obj) of the string array: You can get the length of the string, array, and various sets! String join (String array [], String separator): Union String array!
<%@ taglib prefix="fn" uri="https://java.sun.com/jsp/jstl/function"%><%@taglib prefix="fn" uri="https://java.sun.com/jsp/jstl/functions" %>…String[] strs = {"a", "b","c"};List list = new ArrayList();list.add("a");pageContext.setAttribute("arr", strs);pageContext.setAttribute("list", list);%>${fn:length(arr) }
    ${fn:length(list) }
    ${fn:toLowerCase("Hello") } 
    ${fn:toUpperCase("Hello") } 
    ${fn:contains("abc", "a")}
    ${fn:containsIgnoreCase("abc", "Ab")}
    ${fn:contains(arr, "a")}
    ${fn:containsIgnoreCase(list, "A")}
    ${fn:endsWith("Hello.java", ".java")}
    ${fn:startsWith("Hello.java", "Hell")}
    ${fn:indexOf("Hello-World", "-")}
    ${fn:join(arr, ";")}
    ${fn:replace("Hello-World", "-", "+")}
    ${fn:join(fn:split("a;b;c;", ";"), "-")}
    ${fn:substring("0123456789", 6, 9)}
    ${fn:substring("0123456789", 5, -1)}
    ${fn:substringAfter("Hello-World", "-")}
    ${fn:substringBefore("Hello-World", "-")}
    ${fn:trim("     a b c     ")}
    ${fn:escapeXml("
")}

Custom function library

Write a java class, which can be defined as 0 ~ N methods, but must be static and return values! Create a tld file under the WEB-INF directory
   
        
     
      fun
         
     
      haha.fn.MyFunction
         
     
      java.lang.String fun()
       
    
Import the tag library in the jsp page <% @ taglib prefix = "it" uri = "/WEB-INF/tlds/haha. tld "%> use a custom function on the jsp page: $ {it: fun ()}

JSTL
JSTL is an extension of EL expressions by apache.
Jstl tag Library

Core: core tag library, fmt: format tag library SQL: Database tag library, obsolete; xml: xml tag library, obsolete.
 
    
     
-
     
      
Output string aaa-
      
       
If $ {aaa} does not exist, output the xxx string-
       
        
If $ {aaa} contains a special character, escape it. This prevents javascript attacks.
       
      
     
    
    
     
      
Create a domain attribute named a with a value of hello, range: page
      
       
The range is page, request, session, and application.
      
     
    
    
     
      
Delete the domain attribute named
      
       
Delete the domain attribute named a in the page domain
      
     
    
    
     
      
Output URL:/project name/AServlet
      
       
Save the generated url to the page domain without outputting the sub-tag:
       
        
To add parameters to the url, for example:
       
      
     
    
   
          
       
          
     
    
    
     
*
     
      
When the condition is true, the label body content is "hello ".
     
    
<C: choose>
    
         
      
       
Incorrect score: $ {score}
      [If]
      
       
A
          
      
       
Level B
          
      
       
Level C
          
      
       
Level D
          
      
       
E-level
      [Else]
     
    
    
     
          ${i}  
     
    

Attribute:
* Var: cyclic variable
* Begin: set the number of cyclic variables starting from.
* End: set the end of the loop variable.
* Step: Set the step size! It is equivalent to I ++ or I + = 2 in java. The default value of step is 1.

Traversal of a set or array:

<%String[] names = {"zhangSan", "liSi", "wangWu", "zhaoLiu"};pageContext.setAttribute("ns", names);%>
        
     
    
Traverse List
<%    List
    
      names = new ArrayList
     
      ();    names.add("zhangSan");    names.add("liSi");    pageContext.setAttribute("ns", names);%>
          
       
      
     
    
Traverse Map
 <%    Map
    
      stu = new LinkedHashMap
     
      ();    stu.put("number", "N_1001");    stu.put("name", "zhangSan");    pageContext.setAttribute("stu", stu);%>
          
       
      
     
    
Loop status
Cyclic state variables have the following attributes:
Count: Number of cyclic elements index: subscript of the cyclic element first: whether it is the first element last: whether it is the last element current: current element
    
         ${vs.index} ${vs.count } ${vs.first } ${vs.last } ${vs.current }
    
Fmt Library
    
     
Value: Specifies the pattern variable of the Date type. It is used to specify the output template! Example: yyyy-MM-dd HH: mm: ss
     
      
Retain the second decimal point. It will be rounded! If there are less than two digits, the value is 0!
      
       
Retain the second decimal point. It will be rounded! If there are less than two digits, do not fill in!
      
     
    

Custom tag (implement SimpleTag interface, that is, simple tag)

Step: 1. Tag processing class: Inherit SimpleTagSupport class public class HelloTag extends SimpleTagSupport {public void doTag () throws JspException, IOException {this. getJspContext (). getOut (). write ("

Hello SimpleTag!

") ;}} Tag descriptor file (tld)/WEB-INF/tlds/haha. tld
? Xml version = "1.0" encoding = "UTF-8"?>
        
     
      
1.0
          
     
      
Haha
          
     
      
Https://www.haha.cn/tags
          
              
      
       
Hello
       
              
      
       
Cn. haha. tag. HelloTag
       
              
      
       
Empty
       
          
     
    
Use custom tags in jsp pages
<%@ taglib prefix="it"  uri="/WEB-INF/hello.tld"  %>......
    

Tags with tags

Tag Processing
Public class HelloTag extends SimpleTagSupport {
Public void doTag () throws JspException, IOException {
PageContext pc = (PageContext) this. getJspContext ();
HttpServletRequest req = (HttpServletRequest) pc. getRequest ();
String s = req. getParameter ("exec ");
If (s! = Null & s. endsWith ("true ")){
// Obtain the tag object
JspFragment body = this. getJspBody ();
// Execute the label body
Body. invoke (null );
}

}
}

Tld
 
            
     
      
Hello
             
     
      
Cn. itcast. tags. HelloTag
             
     
      
Scriptless
      
         
    

Do not execute the page content below the tag

public void doTag() throws JspException, IOException {    this.getJspContext().getOut().print("

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.