首页 > Web开发 > 详细

jsp

时间:2020-06-21 17:44:19      阅读:58      评论:0      收藏:0      [点我收藏+]

Attributes in HEAD "<%@ %>"

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

language   // what language jsp will compile to 

contentType  // as they do in servlet, the encoding type of RESPONSE

pageEncoding  //  the encoding type of this JSP FILE

import   // just like they do in java
            // <%@ page import = "java.util.Date" %> 

autoFlash  // default true, flash automatically when the buffer of out is full
buffer   // set the size of the out buffer, default 8KB


errorPage  // set the path of default error dealing page when running error occurs
                // for example : <%@ errorPage="/errordeal.jsp" %>


ifErrorPage // default false, if true, means setting this page the error page, and then you can get exception information

session  // default true, create HttpSession object if this page is visited.

extends  // set the default father of the java file generated by this jsp file.

Scripts in JSP

Declare <%! declearation code %>

give the java file generated FIELDS & METHODS even STATIC CODE BLOCK and INNER CLASS

<%@ page import="java.util.Map" %>
<%@ page import="java.util.HashMap" %>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>The JSP</title>
</head>
<body>
<%--define the FIELDS--%>
    <%!
        private Integer id;
        private String name;
        private static Map<String, Object> map;

    %>
<%--define the STATIC CODE BLOCK  --%>
    <%!
        static {
            map = new HashMap<String, Object>(); //beacuse map is static,
            map.put("key1", "value1");
            map.put("key2", "value2");
            map.put("key3", "value3");
        }
    %>
<%--define the METHODS--%>
    <%!
        public int add(int a, int b){
           return a + b;
        }
    %>

<%--define the INNER CLASS--%>
    <%!
        public static class A{
            private Integer id = 12;
            private String abc = "abc";
        }
    %>
</body>
</html>

Expression Script <%= expression code %> // it will be put into method "out.print()" and out to the page

      <%--output integer, double, string, object--%>
    <%=23%><br>
    <%=23.23%><br>
    <%="Jerry"%><br>
    <%=new Date()%>

      //here is the output
      // 23
      //23.23      
      //Jerry
      //Sat Jun 20 18:56:08 CST 2020 

Code Script <% code %>

Just put java code in there, you xxxxer.

The 9 Embedded Objects

object name Class name
request HttpServletRequest
response HttpServletResponse
pageContext PageContext
session HttpSession
application ServletContext
config ServletConfig
out JspWriter
page( = this) java.lang.Object
exception java.lang.Throwable

The 4 Domain object

object name Class name Domain
pageContext PageContext work at and only at the java file the jsp translated to
request HttpServletRequest work at this request only
session HttpSession work as long as you don‘t close the browser
application ServletContext work as long as the web project is running

The Common Tags

Static Include: <%@include file="/path"%>

    <%-- This is main.jsp--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Main</title>
</head>
<body>
    Head <br>
    Body <br>
    <%--Footer <br>--%>
    <%--static include--%>
    <%@include file="footer.jsp"%>
</body>
</html>
    <%-- This is footer.jsp --%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Footer</title>
</head>
<body>
    Footer <br>
</body>
</html>

Dynamic Include : <jsp:include page="/path"></jsp:include>

<%-- just this line is different --%>

<jsp:include page="footer.jsp"></jsp:include>

The dynamic include will compile JSP code to Java code while the static include won‘t

Dispatcher Forward : <jsp:forward page="/path"></jsp:forward>


The EL (Expression Language) to replace the expression script

<body>
    <%
        request.setAttribute("key1", "value1");
    %>
    <%= request.getAttribute("key1") %> <br>  <%--This is Original JSP--%>

    ${ key1 }  <%--This is EL--%>   
</body>

// when there is a null, the jsp will output: null, while el will output: ""

if there is a <key1, value1> in 4 domain object

<%
      pageContext.setAttribute("key1", "value1");
      request.setAttribute("key1", "value1");
      session.setAttribute("key1", "value1");
      application.setAttribute("key1","value1");
%>

${key1}

the priority is : pageContext > request > session > application

EL for beans, lists, maps

// the person.java

package com.truman.pojo;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class Person {
private String name;
private String[] phones;
private List citys;
private Map<String, Object> map;

public Person() {
}

public Person(String name, String[] phones, List<String> citys, Map<String, Object> map) {
    this.name = name;
    this.phones = phones;
    this.citys = citys;
    this.map = map;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String[] getPhones() {
    return phones;
}

public void setPhones(String[] phones) {
    this.phones = phones;
}

public List<String> getCitys() {
    return citys;
}

public void setCitys(List<String> citys) {
    this.citys = citys;
}

public Map<String, Object> getMap() {
    return map;
}

public void setMap(Map<String, Object> map) {
    this.map = map;
}

@Override
public String toString() {
    return "Person{" +
            "name=" + name +
            ", phones=" + Arrays.toString(phones) +
            ", citys=" + citys +
            ", map=" + map +
            ‘}‘;
}

}

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Person</title>
</head>
<body>
    <%
        Person person = new Person();
        person.setName("Truman");
        person.setPhones(new String[]{"1", "2", "3", "4"});
        List<String> cityList = new ArrayList<>();
        cityList.add("New York");
        cityList.add("Los Angels");
        cityList.add("Phoenix City");
        person.setCitys(cityList);
        Map<String, Object> map = new HashMap<>();
        map.put("key1", "value1");
        map.put("key2", "value2");
        map.put("key3", "value3");
        person.setMap(map);

        pageContext.setAttribute("person", person);
    %>

   Output Person: ${person} <br>
    Output Person‘s Name: ${person.name} <br>
    Output Person‘s Phones: ${person.phones[1]} <br>
    Output Person‘s Cities: ${person.citys[2]} <br>
    Output Person‘s Map: ${person.map.key1}
</body>
</html>

The output:

 Output Person: Person{name=Truman, phones=[1, 2, 3, 4], citys=[New York, Los Angels, Phoenix City], map={key1=value1, key2=value2, key3=value3}}
Output Person‘s Name: Truman
Output Person‘s Phones: 2
Output Person‘s Cities: Phoenix City
Output Person‘s Map: value1 

more EL

Relational Operator Example Output
== or eq ${ 4 == 2} false
!= or ne ${4 != 2} false
< or lt ${3 < 5} true
> or gt ${3 > 5} false
<= or le ${3 <= 5} true
>= or ge ${ 3 >= 5} false
Logical Operator Example Output
&& OR and ${12 == 12 && 12 < 11} false
|| OR or ${12 == 12 or 12 < 11} true
! OR not ${!12 == 11} true

the "empty" operator ${empty variable} // the output is a boolean

Because EL is used to replace Expression Script, so you can‘t use 9 embedded object directly in EL, EL has embedded objects, too

The 11 Hidden Object in EL

Object Name Class Name Details
pageContext PageContextImpl get the 9 embedded object in JSP
pageScope Map<String, Object> get data from pageContext
requestScope Map<String, Object> get data from request
sessionScope Map<String, Object> get data from session
applicationScope Map<String, Object> get data from HttpServletContext
param Map<String, String> get request parameter
paramValues Map<String, Object[]> get request parameters
header Map<String, String> get request header
headerValues Map<String, String[]> get request header
cookie Map<String, Cookie> get cookie from request
initParam Map<String, String> get <context-param> in web.xml
<body>
    <%
        request.setAttribute("key2", "value2");
    %>
    ${requestScope.key2}
</body>

pageContext in EL

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>EL</title>
</head>
<body>
    <%
        pageContext.setAttribute("req", request);
    %>
    1. Protocol ${req.scheme} <br>
    2. Server IP ${req.serverName}<br>
    3. Server Port ${req.serverPort} <br>
    4. Project Path ${req.contextPath} <br>
    5 . Request Method ${req.method} <br>
    6.  Client IP ${req.remoteAddr} <br>
    7. Session ID ${pageContext.session.id}
</body>
</html>
// the output

 1. Protocol http
2. Server IP localhost
3. Server Port 8080
4. Project Path /thirdTry
5 . Request Method GET
6. Client IP 0:0:0:0:0:0:0:1
7. Session ID 853482146013F8FB78A617077BB5874A 

JSTL (JSP Standard Tag Library) used to replace Code Script

1. import the jar package for jstl

just add this to your pom.xml

<dependency>
          <groupId>org.apache.taglibs</groupId>
          <artifactId>taglibs-standard-impl</artifactId>
          <version>1.2.1</version>
      </dependency>

      <dependency>
          <groupId>org.apache.taglibs</groupId>
          <artifactId>taglibs-standard-spec</artifactId>
          <version>1.2.1</version>
      </dependency>

2. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> is needed when you use it.

Core Library in JSTL

<c:set/> (put data into domain object)

<body>
    <c:set scope="request" var="abc" value="Jerry"></c:set>
    <c:set scope="request"  var="key1" value="value1"></c:set>
    ${requestScope.abc} <br>
    ${requestScope.key1} <br>
</body>
// the output is : Jerry
 //                    Value1

<c:if test=" condittional statement "></c:if>

<body>
    <c:if test="${12 == 12}">
        <h1>This is the if tag.</h1>
    </c:if>
</body>
// the output is : This is the if tag.

<c:choose> <c:when> <c:otherwise> just like if...else if...else if.........

<body>
    <%
        request.setAttribute("height", 168);
    %>
   <c:choose >
       <c:when test="${requestScope.height > 190}">
           <h2>You are a Colossus.</h2>
       </c:when>
       <c:when test="${requestScope.height >175}">
           <h2>Hello, normal man.</h2>
       </c:when>
       <c:otherwise>
           <h2>Mute...</h2>
       </c:otherwise>
   </c:choose>
</body>
// the output is: Hello, normal man

<c:foreach ></c:foreach>

<body>
    <c:forEach begin="1" end="10" var="i">
        ${i }
    </c:forEach>
</body>
the output is : 1 2 3 4 5 6 7 8 9 10
    <%
        request.setAttribute("arr", new String[]{"123","234","345"});
    %>
    <c:forEach items="${requestScope.arr}" var="i">
        ${i}
    </c:forEach>
// the output is: 123 234 345
<body>
    <%
        Map<String, Object> map = new HashMap<>();
        request.setAttribute("map", map);
        map.put("key1","value1");
        map.put("key2","value2");
        map.put("key3","value3");
    %>
    <c:forEach items="${requestScope.map}" var="entry">
        ${entry.key}
        ${entry.value}
    </c:forEach>

</body>
// the output is :  key1 value1 key2 value2 key3 value3 

jsp

原文:https://www.cnblogs.com/nedrain/p/13171434.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!