JSP learning notes (principle, syntax, built-in objects, tags)

Keywords: Java JavaEE JSP

1. What is JSP?

JSP, the full name of Java Server Pages, is a dynamic web page development technology. It uses JSP tags to insert Java code into HTML web pages. Labels usually start with <% and end with% >.

JSP is a Java servlet, which is mainly used to realize the user interface part of Java web application. Web developers write JSPS by combining HTML code, XHTML code, XML elements and embedded JSP operations and commands.

JSP obtains user input data, accesses database and other data sources through web page forms, and then dynamically creates web pages.

JSP tag has many functions, such as accessing database, recording user selection information, accessing JavaBeans components, etc. it can also transfer control information and sharing information in different web pages-- Rookie tutorial

2. Working principle

Working principle of jsp: ① client request; ② Translate *. JSP into *. java; ③ Compile as *. class; ④ Execute the generated servlet; ⑤ The feedback result is displayed to the client. If there is any change in the second access, execute the above process. If there is no change, execute it directly.

JSP works inside the server. If the compiler used is IDEA, those using Tomcat in IDEA will produce a work directory in Tomcat of IDEA. Generally, it is located in this location: C:\Users\xxx\AppData\Local\JetBrains\IntelliJIdea2020.3\tomcat\c9d6b57f-024c-4d39-8143-9e611ae074b4\work\Catalina\localhost\ROOT\org\apache\jsp

Here we find that JSP pages are transformed into java programs, and the essence of JSP is a servlet! The source code inside can be read by yourself. I won't repeat it here.

3.JSP basic syntax

3.1 three directives

<%@ page ... %>Define page dependent properties, such as scripting language, error page, cache requirements, etc.
<%@ include ... %>Contains additional files.
<%@ taglib ... %>The definition of the imported label library can be a user-defined label.
<%--page--%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"  contentType="text/html; charset=UTF-8" isErrorPage="true"%>

<%--include--%>
<%@ include file="foot.html" %>
<%@ include file="foot.jsp" %>
    
<%--taglib prefix: Specify the label prefix. This thing can be named at will uri: Specifies the name of the third-party label library uri(Unique identification)--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

3.2 declaration

JSP declaration: it will be compiled into the java class generated by JSP! Others will be generated to_ jspService method.

<%--jsp Declaration: will be compiled to jsp Generated java Class in! The others above will be generated to_jspService Method--%>
<%!
  static {
    System.out.println("loading Servlet!");
  }
  private int globalVar = 0;
  public void add(){
    System.out.println("Entered the method add!");
  }
%>

3.3 expression

<%--JSP expression
 Function: used to output the program to the client
<%=Variable or expression%>
--%>
<%=new java.util.Date()%>

3.4 scripts

<%--java Script fragment--%>
<%
  int sum = 0;
  for (int i = 0; i <= 100; i++) {
    sum = sum+i;
  }
  out.print("<h1>sum="+sum+"</h1>");
%>

3.5 notes

<!-- This is the html comment -- > 
<% -- this is a JSP comment. The difference between the two annotations: JSP annotations will not be displayed on the client, and HTML will! --% >

Display of results in 3.3 and 3.4:

  4. Nine built-in objects

requestAn instance of the HttpServletRequest class
responseAn instance of the HttpServletResponse class
outAn instance of the PrintWriter class used to output results to a web page
sessionAn instance of the HttpSession class
applicationThe instance of ServletContext class, which is related to the application context
configAn instance of the ServletConfig class
pageContextThe instance of PageContext class provides access to all objects and namespaces of JSP pages
pageSimilar to the this keyword in a Java class
exceptionexception   Class, representing the corresponding exception object in the JSP page where the error occurred

It can store data for pageContext, request, session and application. Note the differences in their scopes.

give an example:

<%
    pageContext.setAttribute("book1","Romance of the Three Kingdoms");//The saved data is only valid in one page
    request.setAttribute("book2","Water Margin");//The saved data is only valid in one request, and the request forwarding will carry this data
    session.setAttribute("book3","The Dream of Red Mansion");//The saved data is valid only in one session, from opening the browser to closing the browser
    application.setAttribute("book4","Journey to the West");//The saved data is only valid in the server, from opening the server to closing the server
%>

<%--The code of the script fragment will be generated to the.JSP.java
 The code here must be guaranteed java Grammatical correctness
--%>
<%
    //Retrieve from pageContext by searching
    //From bottom to top (SCOPE): Page - > request - > session - > Application
    String book1 = (String) pageContext.findAttribute("book1");
    String book2 = (String) pageContext.findAttribute("book2");
    String book3 = (String) pageContext.findAttribute("book3");
    String book4 = (String) pageContext.findAttribute("book4");
    String book5 = (String) pageContext.findAttribute("book5");//non-existent
%>

<%--use EL Expression output ${}--%>
<h1>The values taken are:</h1>
<h3>${book1}</h3>
<h3>${book2}</h3>
<h3>${book3}</h3>
<h3>${book4}</h3>

<%--<%=book5%>If it does not exist, take it out as null   ${book5}If it doesn't exist, there's nothing. So use EL expression--%>
<h3><%=book5%></h3>
<h3>${book5}</h3>

Result display:

  Because their scopes are different, if we create a new. jsp page and take out the above data, we find that only book3 and book4 can be taken out.

5.JSP tag and JSTL tag library

5.1 JSP Tags

More important: jsp:include, jsp:forward, jsp:param

Example: jsp:include is in jsptaf2.jsp.

<%--jsp label  jsp:include Splicing pages, the essence is still three--%>
<jsp:include page="common/header.jsp"/>
<h1>Web page subject</h1>
<jsp:include page="common/footer.jsp"/>

<%--http://localhost:8080/jsptag.jsp?name=haha&age=20--%>
<jsp:forward page="/jsptag2.jsp">
    <jsp:param name="name" value="haha"></jsp:param>
    <jsp:param name="age" value="20"></jsp:param>
</jsp:forward>

Result display:

  5.2 JSTL tag library

The use of JSTL tag library is to make up for the shortage of HTML tags; It can customize many tags for us to use. The function of tags is the same as that of Java code!

Core tag (master part), format tag, SQL tag, XML tag

  Usage steps of JSTL tag library: ① import the corresponding taglib; ② Use one of these methods. You also need to introduce JSTL packages into Tomcat, otherwise an error will be reported: JSTL parsing error.

c:if

<h4>if test</h4>
<hr>
<form action="coreif.jsp" method="get">
    <%--EL Expression to get the data in the form  ${param.Parameter name}--%>
    <input type="text" name="username" value="${param.username}">
    <input type="submit" value="Sign in">
</form>
<%--Judgment: if the submitted is an administrator, the login is successful--%>
<c:if test="${param.username=='admin'}" var="isAdmin">
    <c:out value="Welcome to the administrator!"/>
</c:if>

<%--c:if That's what we wrote java code--%>
<%--<%
if(request.getParameter("username").equals("admin")){
    out.print("Login succeeded");
}
%>--%>
<c:out value="${isAdmin}"/>

Result display:

 c:forEach

<%
    ArrayList<String> people = new ArrayList<>();
    people.add(0,"Zhang San");
    people.add(1,"Li Si");
    people.add(2,"Wang Wu");
    people.add(3,"Zhao Liu");
    people.add(4,"Tian Liu");
    request.setAttribute("list",people);
%>


<%--
var , Variables traversed each time
items, Object to traverse
begin,   Where to start
end,     Where to go?
step,   step
--%>
<c:forEach var="people" items="${list}">
    <c:out value="${people}"/> <br>
</c:forEach>

<hr>

<c:forEach var="people" items="${list}" begin="1" end="3" step="1" >
    <c:out value="${people}"/> <br>
</c:forEach>

Result display:

  reference resources: Meet the crazy God

Posted by strega on Sat, 23 Oct 2021 00:56:56 -0700