当前位置:网站首页>Beginner JSP

Beginner JSP

2022-07-07 14:22:00 Bieyunchao

One . What is? JSP?

JSP Full name Java Server Pages, Is a dynamic web development technology .

Two .JSP Executive schematic diagram

 Insert picture description here

3、 ... and .JSP Basic grammar

1.JSP Notes

<%-- JSP The comment  --%>
JSP Comment and Html Differences in notes :
	1. grammar :<!-- Html notes  --><%-- JSP notes  --%>
	2. Security :Html When you click the review element on the web page, you can view the annotation content , and JSP You can't see the notes of . therefore JSP notes 
	 be relative to Hrml Notes are relatively safe .

2.JSP expression

<%--JSP expression 
	 grammar :<%=  Variables or expressions %>
	 effect : Used to convert the output of the program , Output to client 
	 compile : Will be compiled to _jspService In the method 
--%>
<%= System.currentTimeMillis()%>

3.JSP Script snippets

<%--JSP Script snippets 
	 grammar :<% java code snippet  %>
	 Will be compiled to _jspService In the method 
--%>
<%
   int sum = 0;
   sum = 1 + 2;
   out.println("sum=" + sum);
%>

4.JSP Statement

<%--JSP Statement 
	 grammar :<%! java code snippet  %>
	 Will be compiled into JSP Generated java Class !
--%>
<%!
    static {
    }
    private String globalStr = "abc";
    public void globalMethod(){
    }
%>

Four .JSP Instructions

  • effect : Used for configuration JSP page , Import resource file
    • Format :
      <%@ Instruction names Property name 1= Property value 1 Property name 2= Property value 2 … %>
    • classification :
    1. page: To configure JSP Page

      • contentType: Equate to response.setContentType()
        *. Set the mime Type and character set
        *. Set up current jsp Page code ( It can only be advanced IDE To take effect , If you use low-level tools , You need to Set up pageEncoding Property to set the character set of the current page )
      • import: Guide pack
      • errorPage: When the current page is abnormal , Will automatically jump to the specified error page
      • isErrorPage: Identifies whether or not the current is also an error page .
        * true: yes , You can use built-in objects exception
        * false: no . The default value is . You can't use built-in objects exception
    2. include : The page contains . Import the resource file of the page
      * <%@include file=“top.jsp”%>

    3. taglib : Import resources
      * <%@ taglib prefix=“c” uri=“http://java.sun.com/jsp/jstl/core” %>
      * prefix: Prefix , Self defined

5、 ... and .9 Large built-in objects

1. Introduction to built-in objects

Built-in objects effect
pageContext The current page shares data , You can also get eight other built-in objects
request Multiple resources accessed at one request ( forward )
response The response object
session Between multiple requests in a session
application Store the data , The scope is from opening to closing the server at a time
configServlet Configuration objects for
out Output object , Data output to page
page Current page (Servlet) The object of this
exception Exception object ( Only in isErrorPage="true" Only when )

2. Four object scopes

You can refer to the following code to understand
 Insert picture description here

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <%
        pageContext.setAttribute("name1", " Yangtze River one ");//  The saved data is only valid in one page 
        request.setAttribute("name2", " Changjiang 2 ");//  The saved data is only valid in one request , Request forwarding will carry this data 
        session.setAttribute("name3", " Changjiang 3 ");//  The saved data is valid only in one session , From the Dalai Lama browser to closing the browser 
        application.setAttribute("name4", " Changjiang 4 ");//  The saved data is only valid in the server , From turning on the server to turning off the server 
    %>

    <%
        //  from pageContext Take out , By looking for ways to 
        //  From the bottom to the top ( Scope ):page-->request-->session-->application
        String name1 = (String) pageContext.findAttribute("name1");
        String name2 = (String) pageContext.findAttribute("name2");
        String name3 = (String) pageContext.findAttribute("name3");
        String name4 = (String) pageContext.findAttribute("name4");
        String name5 = (String) pageContext.findAttribute("name5");
    %>
    <%-- Use EL Expression output  ${} --%>
    <%-- Be careful : If EL The expression does not take effect , Please be there. JSP Add... At the top of the page :<%@page isELIgnored="false" %>--%>
    <h1> The value taken out is :</h1>
    <h3>${name1}</h3>
    <h3>${name2}</h3>
    <h3>${name3}</h3>
    <h3>${name4}</h3>
    <h3>${name5}</h3>
</body>
</html>

6、 ... and .EL expression 、JSP label 、JSTL label

Import dependencies before use jar package

<!--JSTL The dependency of expressions -->
<dependency>
  <groupId>javax.servlet.jsp.jstl</groupId>
  <artifactId>jstl-api</artifactId>
  <version>1.2</version>
</dependency>
<!--standard Tag library -->
<dependency>
  <groupId>taglibs</groupId>
  <artifactId>standard</artifactId>
  <version>1.1.2</version>
</dependency>

1.EL expression

1.  Concept :Expression Language  Expression language 
2.  effect : Replace and simplify jsp On the page java Code writing 
3.  grammar :${ expression }
4.  Be careful :
	* jsp The default support el Of expression . If you want to ignore el expression 
		1.  Set up jsp in page In the instruction :isELIgnored="true"  Ignore the present jsp All on page el expression 
		2. \${ expression } : Ignore the current el expression 
5.  Use :
	1.  operation :
		*  Operator :
			1.  Arithmetic operator : + - * /(div) %(mod)
			2.  Comparison operator : > < >= <= == !=
			3.  Logical operators : &&(and) ||(or) !(not)
			4.  Air transport operator : empty
				*  function : Used to determine string 、 aggregate 、 Whether the array object is null Or if the length is 0
				* ${empty list}: Judgment string 、 aggregate 、 Whether the array object is null Or the length is 0
				* ${not empty str}: Represents the judgment string 、 aggregate 、 Whether the array object is not null  also   length >0
	2.  Get value 
		1. el Expressions can only get values from domain objects 
		2.  grammar :
			1. ${ Domain name . Key name }: Get the value of the specified key from the specified field 
				*  Domain name :
					1. pageScope		--> pageContext
					2. requestScope 	--> request
					3. sessionScope 	--> session
					4. applicationScope --> application(ServletContext)
				*  give an example : stay request The domain stores name= Zhang San 
				*  obtain :${requestScope.name}

			2. ${ Key name }: Indicates whether there is a value corresponding to the key from the smallest field in turn , Until we find it .

			3.  Get objects 、List aggregate 、Map The value of the set 
				1.  object :${ Domain name . Key name . Property name }
					*  In essence, it will call the object getter Method 
				2. List aggregate :${ Domain name . Key name [ Indexes ]}
				3. Map aggregate :
					* ${ Domain name . Key name .key name }
					* ${ Domain name . Key name ["key name "]}
	3.  Implicit objects :
				* el There is... In the expression 11 Implicit objects 
				* pageContext:
					*  obtain jsp Eight other built-in objects 
						* ${pageContext.request.contextPath}: Get virtual directory dynamically 

2.JSP label

<%-- Embed other pages into the page --%>
<jsp:include page=""/>

<%-- Forward page --%>
<jsp:forward page="jsptag2.jsp">
    <%-- You can carry parameters 
    localhost:8080/jsptag2.jsp?account=admin&password=root
    --%>
    <jsp:param name="account" value="admin"/>
    <jsp:param name="password" value="root"/>
</jsp:forward>

3.JSTL label

1.  Concept :JavaServer Pages Tag Library  JSP Standard label library 
	*  By Apache Open source free... Provided by the organization jsp label 		< label >

2.  effect : Used to simplify and replace jsp On the page java Code 		

3.  Use steps :
	1.  Import jstl relevant jar package 
	2.  Import label Library :taglib Instructions :  <%@ taglib %>
	3.  Use a label 
	4.  frequently-used JSTL label 
		1. if: amount to java Code if sentence 
			1.  attribute :
	            * test  Must attribute , Accept boolean expression 
	                *  If the expression is true, Is displayed if Label content , If false, The label body content is not displayed 
	                *  In general ,test Property values will be combined with el Use expressions together 
	  		 2.  Be careful :
	   		 	* c:if The label doesn't have else situation , to want to else situation , You can define a c:if label 
<body>
    <%request.setAttribute("count","19");%>
    <c:if test="${count >= 18}"> This year you ${count} Year old , I'm an adult </c:if>
    <c:if test="${count < 18}"> Children , This year ${count} Year old , Or underage </c:if>
</body>
	2. choose: amount to java Code switch sentence 
		1.  Use choose Label statement          			 amount to switch Statement 
        2.  Use when The label makes the judgment          			 amount to case
        3.  Use otherwise The label makes a statement of other situations     	 amount to default
<%
request.setAttribute("number", 4);
%>
<body>
<c:set var="score" value="60"/>
<c:choose>
    <c:when test="${score > 80}"> good </c:when>
    <c:when test="${score >= 60}"> pass </c:when>
    <c:when test="${score < 60}"> fail, </c:when>
</c:choose>
</body>
	3. foreach: amount to java Code for sentence 
		1. Repeat the operation 
        *  attribute :
            begin: Starting value 
            end: End value 
            var: Temporary variable 
            step: step 
            varStatus: Loop state object 
                index: The index of the element in the container , from 0 Start 
                count: cycles , from 1 Start 
    	2. Traversal container 
        *  attribute :
            items: Container object 
            var: Temporary variables for elements in the container 
            varStatus: Loop state object 
                index: The index of the element in the container , from 0 Start 
                count: cycles , from 1 Start 
<body>
<%
    //  Initialize a list aggregate 
    ArrayList<String> list = new ArrayList<>();
    list.add(" Apple ");
    list.add(" Banana ");
    list.add(" strawberry ");
    list.add(" watermelon ");
    //  take list The collection is stored in request domain 
    request.setAttribute("list", list);
%>
<c:forEach items="${list}" var="str" varStatus="s">
    <h2> Subscript to be ${s.index} The value of is ${str}, The first ${s.count} loop </h2>
</c:forEach>
</body>

7、 ... and .JavaBean

1. What is? JavaBean?
JavaBean It's a Java Entity class , Have their own specific way of writing :
	*  There has to be a parameterless construct 
	*  Property must be privatized .
	*  There must be a corresponding getter and setter
 It is usually used to map the fields in the database  ORM
ORM: Object relation mapping 
	 surface -->Java class 
	 Field --> attribute 
	 rows --> object 

JavaBean stay JSP Simple use of :

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <jsp:useBean id="person" class="com.aynu.pojo.People" scope="page"/>
    <jsp:setProperty name="person" property="id" value="1"/>
    <jsp:setProperty name="person" property="name" value="Mike"/>
    <jsp:setProperty name="person" property="age" value="19"/>
    <jsp:setProperty name="person" property="address" value=" Beijing "/>
    id:<jsp:getProperty name="person" property="id"/>
     full name :<jsp:getProperty name="person" property="name"/>
     Age :<jsp:getProperty name="person" property="age"/>
     Address :<jsp:getProperty name="person" property="address"/>
</body>
</html>
原网站

版权声明
本文为[Bieyunchao]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130614592316.html