Jsp Learning Notes - Take a simple note

html element

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>html element</title>
<link rel="stylesheet" type="text/css" href="./css/demo.css" />   
<script src="./js/demo.js"></script>    
</head>
<body>
</body>
</html>

Script Elements

Declaration

<%! Code Content %> 
//<%!%> You can declare methods, properties, global variables
<%!
    //JSP declaration fragment: Note that defining variables or methods on JSP pages is not recommended, just not recommended
    int i = 10;
    String name = "Vis.Yang";
    public void printName(){
        System.out.println(name);
    }
%>
//Note: Compliance with Java Notes

Expression

<%= Expression %> 
//Call declared/defined methods or display declared/defined parameter (variable) values
Current time: <%= new java.util.Date() %>
//Semicolon not allowed after

Scripts (Scriplets)

<% Program code, one or more lines %> 
// Local variables or calling methods can be defined in <%%>, but methods cannot be defined.
<%
 for (int i=0;i<10,i++) {
     ...
     ...
}
%> 
//example

<%if(percent < 0.5) { %>
<jsp:forward page="forward.html"/>
<%
  }else {
%>
<jsp:forward page="forward.jsp"/>
<% } %>

// Multiple brackets {} need to be wrapped in <%> or it will not work

Instruction Element

<%@ Instruction Name Properties="value" %>   
<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %
<-- Specify the error page path -->
<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" errorPage="error.jsp" %
<-- Set current page as error handling page -->
<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isErrorPage="true" %
<-- prefix prefix="mytag"    Path to Custom Label uri="/WEB-INF/helloSimpleTag.tld"-->
<%@ taglib prefix="mytag" uri="/WEB-INF/helloSimpleTag.tld"%>
<-- Usage method -->
<mytag:helloworld />
<-- Label Reuse -->

Be careful

If an instruction has multiple attributes, it can be written in one instruction, separated by spaces, or in several instructions.

Attribute values are typically enclosed in double or single quotes, and attribute names are case sensitive

Common Instructions

page directive

Used to set properties related to JSP pages, such as reference packages, encoding, error information, etc.

include directive

Used to insert included files at JSP compilation time, such as html, text, or Jsp pages

taglib directive

Used to declare that page users are allowed to customize Tags

page directive

attributedescribe
languageThe scripting language to use when writing Jsp pages, defaulting to Java
pageEncodingSpecifies the character encoding for Jsp pages, defaulting to ISO-8859-1 commonly used page Encoding="UTF-8"
contentTypeThe MIME type of the response from which the client browser determines the document type, defaulting to "text/html"
importUsed to introduce a system or custom package or class on a Jsp page that can be used multiple times or separated by commas
sessionUsed to set the availability of Jsp page session objects, defaulting to true
errorPageSpecify an error page and set the value to the Url of the error page
isErrorPageSpecifies whether to treat the current page as a Jsp error page, defaulting to false

include directive

<-- body Embed the specified page inside the label date.jsp -->     <-- Page Insertion Role:Extract Public Pages/content -->   
<%@ include file="date.jsp" %>

Action Elements

<jsp:include page="date.jsp">                  <-- Result Insertion --> 
    <jsp:param name="Vis.Yang" age="3"/>          <-- Ginseng -->
</jsp:include>

<jsp:include page="date.jsp"/>                   <-- No ginseng -->
<jsp:include page="demo.html" flush="true"/>
<-- 
    Introducing results
-->  
 
<jsp:forward page="forward.jsp"/>              <-- No ginseng -->
    
<jsp:forward page="forward.jsp">               <-- page="forward.jsp":Pages to Turn to -->
    <jsp:param name="Vis.Yang" age="3"/>       <-- Ginseng -->
</jsp:forward>
<-- 
    Forward the client's current request to another Web Resources (to process requests)
    Can be HTML Page, JSP Page, Servlet etc.  
    Address bar unchanged, content of new page
-->

Tip: No intersection between elements

JavaBean

<--  A class name was created Student Of stu1 object -->
<jsp:useBean id="stu1" class="com.my.bean.Student" scope="Scope of action"></jsp:useBean>
<jsp:useBean id="stu2" class="com.my.bean.Student" scope="Scope of action"></jsp:useBean>
<-- scope="Scope of action" page request session application -->
<-- page:Current page is valid request:One request is valid session:Browser remains active until closed application:The server is always there -->
<-- Equivalent to -->
<%
Student stu1=new Student();
Student stu2=new Student();
%>
<-- Get properties and display them to jsp in -->
<jsp:getProperty name="stu1" property="name"></jsp:getProperty>
<jsp:getProperty name="stu2" property="name"></jsp:getProperty>
<-- Equivalent to -->
<%=stu1.name()%>
<%=stu2.name()%>    
<-- set a property-->   
<jsp:setProperty name="stu1" property="name" value="Vis.Yang"></jsp:setProperty>
<-- Equivalent to -->
<%
    stu1.setName("Vis.Yang");
%>
<-- Automatically load all type values of the form into the object property="*" -->
<jsp:setProperty name="stu1" property="*"></jsp:setProperty>
<-- premise:Form name and bean Property names are identical -->
<input type="text" name="name" />
<input type="password" name="pwd" />
<-- Autoload only name Attribute Value property="name" -->
<jsp:setProperty name="stu1" property="name"></jsp:setProperty> 

Jsp built-in objects

Built-in objects: objects that can be used directly without being declared or created
Built-in ObjectsfunctionRange
requestRequests that trigger service callsrequest
responseResponse to Requestpage
sessionsession object created for the requested clientpage
applicationgetServletConfig.getContextsession
outObject that writes to the output streamapplication
exceptionException handling informationpage
pagecontextPage context for this JSPpage
pageImplement an instance of the class that handles the current request for this page, as in Javapage
configServletConfig configuration information for this JSP, web.xml specificationpage

request

The request object encapsulates the client's request information and can be used to obtain the client's request information
Valid within one request, scoped to request
Frequently used to obtain data for forms, common forms are:
Single-line text box, multi-line text box, drop-down menu, radio button, check box, etc.
//common method
String getParameter(String name)	      //Returns the parameter value of the name specified parameter
String[] getParameterValues(String name)  //Returns an array containing all the values of the parameter name

response

Respond to requests
<%
response.sendRedirect('sucess.jsp'); //Redirect to another page, browser address change, different from jsp:forward     
response.addCookie();  //Add cookie s
response.getWriter().println("");    //Equals out.println('');
%>

out

The out object manages the output buffer on the application server, representing the output stream of the JSP page, which is javax. Servlet. Jsp. Instance of JspWriter.
Output data in various formats to the client, typically the content of the object to the browser is text-based
Scope is page, and there is an out object for each JSP page
<%
//Simple Print Output to Browser Page
out.print('');
out.println('');
%>

exception

Exception thrown by JSP engine when executing code
Is java. Instances of the lang.Throwable class
Only on error pages, isErrorPage="true" must be specified in the page directive
//statement
<%!
   System.out.println(exception.getMessage()); //console output to IDE
 %>
//Script
<%
//Output Exception
out.print(exception.getMessage());//Output to Page
//Page Wrap
out.println("<br>")
System.out.println(exception.getMessage());//console output to IDE
%>
//Expression
<%=exception.getMessage()%> //Output to Page

session

The session object encapsulates all the information belonging to the client session
Open a browser from a client and connect to the server Start until the client closes the browser Leave this server End is called a session
String getId();  //Gets the unique ID set by the JSP engine for session when it is created
boolean isNew(); //Determine if this is a new session
//Transfer parameters in different pages
void setAttribute(String name,Object obj);//Setting parameters
Object getAttribute(String name)   //Take Parameters
void removeAtribute(String name) //Delete parameters
Enumeration getAttributeNames()  //Returns each property object stored in the session object, resulting in an enumeration type. Multiple parameters
void invalidate();cancel session Object, and completely delete the object's contents
void setMaxInactiveInterval()Set maximum session Inactive time, if negative, never times out.
int getMaxInactiveInterval()Get Maximum session Inactive time
long getCreationTime()//Get session creation time
long getLastAccessedTime()Obtain session The last time an object was operated on

application

When the server starts, an application object is automatically generated until the server shuts down.
The application lifecycle is the period from server startup to shutdown to enable data sharing among multiple clients. Wider scope than session
The application object is responsible for providing some global information about the application as it runs in the server.
void setAttribute(String name, Object object); //Set properties, specify property names and property values.
String getAttribute(String name); //Gets the property value based on the property name.
Enumeration getAttributeNames(); //Gets all property names.
void removeAttribute(String name); //Delete the corresponding property according to the property name.
String getServletInfo(); //Get version information for the current Web server.
String getInitParameter(String name); //Gets the initialization parameter value based on the initialization parameter name.
int getMajorVersion(); //Gets the major version number of the Servlet API.
int getMinorVersion(); //Gets the minor version number of the Servlet API.
void log(String message)//Write information to the log file. 

The difference between the two

Stored data

session stores individual data for different users

application stores data that is shared between different users

Life Cycle

session from client's first access to server until browser is closed

application starts from server until server shuts down

Example

//Site Visits Statistics
<%>
//First access data is empty
    Object obj=session.getAttribute("count");
//User First Access
if(obj==null){
session.setAttribute("count",1);
}else{
    Integer num=(Integer)obj;
   session.setAttribute("count",++num);
}
}
<%>
The number of times you visit this website:<%=session.getAttribute("count")%>

application Statistics More Recommended
<--When accessed in different browsers,Counters do not accumulate continuously-->
<%>
//First access data is empty
    Object obj=application.getAttribute("count");
//User First Access
if(obj==null){
application.setAttribute("count",1);
}else{
    Integer num=(Integer)obj;
   application.setAttribute("count",++num);
}
}
<%>
The number of times you visit this website:<%=application.getAttribute("count")%>


exception

//common method
exception.getMessage();
exception.toString();
<%=exception.toString()%>  //Show exceptions

//The current page needs to be set to error handling page isErrorPage="true" before use
<-- Set current page as error handling page -->
<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isErrorPage="true" %
request response session application shared data
out  Output data to browser page
exception  Handle Exceptions
${pageContext.request.contextPath}  Obtain web Resource Path

Roaming Query

ResultSet.TYPE_FORWARD_ONLY   //Only scroll forward
ResultSet.TYPE_SCROLL_INSENSITIVE //Scroll in both directions, but do not update in time, even if the database's data has been modified and is not reflected in the ResultSet
ResultSet.TYPE_SCROLL_SENSITIVE   //Scroll in both directions and keep track of database updates to change data in ResultSet
ResultSet.CONCUR_READ_ONLY   //Default, or show declaration specifying that ResultSet cannot be updated
ResultSet.CONCUR_UPDATABLE   //Specify that ResultSet can be updated
// Statement statement=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY );

common method

void last();//Go to the last line
int getRow();//Get the current row

Keywords: Eclipse

Added by FadeToLife on Mon, 10 Jan 2022 19:40:03 +0200