Author: java_wxid

1. What is Jsp? JSP is a Java Server page, a Java server page. 2. Why to learn JSP technology because JSP technology can be a good solution in the Servlet program to send back data is HTML content, this problem.

Why is sending back HTML data in a Servlet application a problem?

public class PrintHtml extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType("text/ HTML; charset=UTF-8"); PrintWriter writer = response.getwriter (); writer.write("<! DOCTYPE HTML PUBLIC \ "- / / / / W3C DTD HTML 4.01 Transitional / / EN \" \ "http://www.w3.org/TR/html4/loose.dtd\" > \ r \ n "); writer.write("<html>\r\n"); writer.write(" <head>\r\n"); writer.write(" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n"); writer.write(" <title>Insert title here</title>\r\n"); writer.write(" </head>\r\n"); writer.write(" <body>\r\n"); Writer. write(" This is hello's HTML page \r\n"); writer.write(" </body>\r\n"); writer.write("</html>"); }}Copy the code

As you can see, creating an HTML page is tedious

How to create a JSP dynamic page.



4. How to modify the default coding of JSP pages?



Summary:

HTML is the same as JSP. They’re all in webContent

WebContent

a.html =====>>>> http://ip:port/ project name/A.html

b.jsp =====>>>> http://ip:port/ project name /b.jsp

5. What is the essence of JSP? JSP is essentially a Servlet program.

When we first access a JSP page, the Tomcat server translates the JSP into a Java source file and saves it in the Work directory of the Tomcat server.

Double-click Tomcat V7.0 Server at localhost [Started,Synchronized], the following window is displayed



JSP generated class files and Java source files



If we open the a_jsp.java source file, it’s not hard to see that the generated class inherits from the HttpJspBase class.



Then, by looking at the source code, HttpJspBase inherits the HttpServlet program. So the generated class is also essentially a Servlet program.



JSP translation into Servlet source files, full name rules (understand the general) :

The full name of a.jsp after translation is: a_jsp.java

B. JSP’s full name after translation is: b_jsp.java

The source file name is _jsp.java

A) The page instruction in the JSP header

The < % @ page language = “Java” contentType = “text/HTML. Charset = utf-8 pageEncoding “=” utf-8 “% >

The value of the I.language property can only be Java. Indicates that the JSP translation is followed by the Java source file.

Ii. the contentType returned by the contentType attribute. Response.setcontenttype parameter value.

The iii.pageEncoding property is the character set of the current JSP page

The iv.import attribute imports the required packages and classes into the JSP page.

The v.autoflush property sets whether the out output stream in JSP is automatically flushed. The default is true.

When the buffer for the OUT output stream in the JSP is full, it is refreshed automatically.

The vi. Buffer property sets the buffer size of the OUT output stream in the JSP. The default is 8 KB



Vii. errorPage property sets the page to which the JSP automatically jumps when an error occurs while running.

The viii.isErrorPage property sets whether the current JSP is an error page. The default is false, indicating that the exception object is not started. Set to true to enable Exception Exception objects

The ix. Session property sets whether a Session session object is created when accessing a JSP. The default is true.

X. xa tends properties extends inherited properties are reserved for server vendors. (Barely moving)

B) Three types of scripts in JSP i. declaration script (rarely used) Declaration script format: <%! Declaration code %>

Declaration scripts can declare code defined inside a class.

1. We can define global variables. Define a static code block. Define a method. Define an inner class

Test code:

<body> <! -- 1. We can define global variables. -- > < %! int i = 0; private static Map<String,Object> map = new HashMap<String,Object>(); % > <! Define static code block --> <%! static { map.put("key1", "value1"); map.put("key2", "value2"); map.put("key3", "value3"); } % > <! -- 3. Define method --> <%! Public void ABC (){system.out.println (); ); } % > <! -- 4. Define inner class --> <%! private static class A { private String name; } %> </body>Copy the code



Ii. Expression scripts

Expression script format: <%= expression %>

Expression scripts can output data in JSP pages. The expression script is always translated into the _jspService method and the expression script is always out.print and the expression script cannot end with a semicolon because the expression script is always translated into the _jspService method, So objects in the _jspService method can be used directly in expression scripts.

1. Output integers

2. Output floating point type

3. Output a string

4. Output objects



Iii. Code scripts

The code script format is: <% code script %>

Code scripts can write any code that can be written in a method.

The code and scripts are translated in the _jspService method

1. Code script —-if statement

2. Code script —-for loop statement

3. All the code in the _jspService method in the translated Java file can be written



C) Three types of annotations in JSP

I.h HTML comments –

<! — HTML comment –>

The translation is followed by out.write output to the client.

Ii. Java comments // single-line comments /* multi-line comments */ Java comments will be translated into the source code intact

Iii. JSP comments <%– this is JSP comments –%> JSP comments are ignored when translated

7. JSP nine built-in objects



JSP four domain objects

pageContext ====>>>> request ====>>>>> session =====>>>>> application

Domain object data operation scope

PageContext The current JSP page

Request Indicates the same request

Session The same session (open the browser, access the server after the session is opened, as long as the browser is closed. Conversations are all in)

Application a Web project

The data operation ranges of the four domains are as follows: pageContext====>>> Request ====>>> Session =====>>>> Application

All four fields can be used to store data. How to choose and use them? The four fields are selected in ascending order.

Context1. JSP page

<body> <h1> context1.jsp page </h1> <% pagecontext. setAttribute("key", "pageContextData"); request.setAttribute("key", "requestData"); session.setAttribute("key", "sessionData"); application.setAttribute("key", "applicaionData"); PageContext: <%= pagecontext.getAttribute ("key") %><br/> Request: <%=request.getAttribute("key") %><br/> Session: <%=session.getAttribute("key") %> <%=application.getAttribute("key") %><br/> <% // request.getRequestDispatcher("/Context2.jsp").forward(request, response); %> </body>Copy the code

Context2. JSP page

<body> <h1> context2.jsp </h1> pageContext field: <%= pagecontext.getAttribute ("key") %><br/> Request field: <%=request.getAttribute("key") %><br/> Session field: <%=session.getAttribute("key") %><br/> Application field: <%=application.getAttribute("key") %><br/> </body>Copy the code

9. The difference between out output in JSP and response.getWriter output



Now we know that both out and Response can output data to the page.

By observing the source code after JSP translation, we found that it is all output using out. Therefore, we will uniformly use out for output operations in the future.

Out.write Can output a string

Out. print can output arbitrary data

Simple: Use out.print for output

A) JSP static contains

<%-- <% @include file="" %> is static inclusion. The leading slash in the static include address indicates that the http://ip:port/ project name/maps to the code's WebContent directory is statically included, which is essentially just the contents of the included JSP page. Copy to the included location intact. Static inclusion does not translate the included JSP files. --%> <%@ include file="/include/footer.jsp" %>Copy the code

B) JSP tags – dynamic inclusion

<%-- < JSP :include page=""></ JSP :include> </ JSP :include> The included JSP pages are also translated into servlets. Dynamic includes, will be translated into the following statement: JspRuntimeLibrary. Include (request, response, ". / include/footer JSP, "out, false); This is equivalent to passing the Request, Response, and out objects to the Servlet translated by footer.jsp for execution. Dynamic inclusion, You can also pass arguments --%> < JSP :include page="/include/footer.jsp"> < JSP :param value="wzg168" name="username"/> < JSP :param value="123456" name="password"/> </jsp:include>Copy the code

Underlying principles of dynamic inclusion:

C) JSP tag-forward

<jsp:forward page=”/Context2.jsp”></jsp:forward>

Request forwarding function,

With the request. GetRequestDispatcher (“/Context2 JSP “). The forward (request, response); The code functions exactly the same

11. The difference between static and dynamic inclusion

With the continuous upgrade of the whole javaEE technology, then JSP this technology, in the whole javaEE system positioning changes slowly.

Over time, JSP positioning became simply to output HTML page data. So in general. Both use static include.

Exercise 1: Output a 10*10 table in JSP

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <! PUBLIC DOCTYPE HTML "- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd" > < HTML > < head > < meta  http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <style type="text/css"> table{ width: 500px; border: 1px solid red; border-collapse: collapse; } th , td{ border: 1px solid red; } </style> </head> <body> <table> <% for (int i = 1; i <= 10; i++) { %> <tr> <% for (int j = 1; j <= 10; j++) { %> <td><%=i + "," + j %></td> <% } %> </tr> <% } %> </table> </body> </html>Copy the code

Exercise 2: Output the multiplication table in JSP

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <! PUBLIC DOCTYPE HTML "- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd" > < HTML > < head > < meta  http-equiv="Content-Type" content="text/html; Charset =UTF-8"> <title>Insert title here</title> </head> <body> <center> <h1> </h1> <table width="600"> <% for(int  i = 1; i < 10; i++){ %> <tr> <% for(int j = 1; j <= i ; j++){ %> <td><%=j + "x" + i + "=" + (j*i) %></td> <% } %> </tr> <% } %> </table> </center> </body> </html>Copy the code

Exercise 3: JSP output a table, which has 20 students information.

Example flow for requesting forwarding:



Student class

public class Student {

	private Integer id;
	private String name;
	private String phone;
	private String email;

	public Student(Integer id, String name, String phone, String email) {
		super();
		this.id = id;
		this.name = name;
		this.phone = phone;
		this.email = email;
	}

	public Student() {
		super();
	}
Copy the code

SearchStduent program

public class SearchStudent extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {List<Student> stus = new ArrayList<Student>(); for (int i = 1; i < 21; i++) { stus.add(new Student(i,"name"+i, "phone"+i,"email"+i)); } // Save student information to request.setAttribute("stus", "stus"); / / forward requests to a JSP page request. The output data in getRequestDispatcher (". / test/showStudent JSP "). The forward (request, response); }}Copy the code

ShowStudent. JSP page

<%@page import="java.util.ArrayList"%> <%@page import="com.atguigu.pojo.Student"%> <%@page import="java.util.List"%> <%@  page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <! PUBLIC DOCTYPE HTML "- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd" > < HTML > < head > < meta  http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <style type="text/css"> table{ width: 500px; border: 1px solid red; border-collapse: collapse; } th , td{ border: 1px solid red; } </style> </head> <body> <% List<Student> stus = (List<Student>) request.getAttribute("stus"); % > < table > < tr > < th > id < / th > < th > name < / th > < th > call < / th > < th > email < / th > < th > action < / th > < / tr > < % for (int I = 0; i < stus.size(); i++) { %> <% Student stu = stus.get(i); %> <tr> <td><%=stu.getId() %></td> <td><%=stu.getName() %></td> <td><%=stu.getPhone() %></td> <td><%=stu.getEmail() % > < / td > < td > modify, delete, < / td > < / tr > < %} % > < / table > < / body > < / HTML >Copy the code

12. What is a Listener? The Listener is one of the three components of JavaWeb: Servlet, Filter, and Listener

A Listener, as the name suggests, listens for changes in the state of something and then reports information back to the user. 1. Monitor state changes of things; 2. Feedback user results

The ServletContextListener listener listens for the creation and destruction of a ServletContext object.

The ServletContext is created when the Web project starts and destroyed when the Web project stops

How to use the ServletContextListener listener is as follows: 1. Write a class that implements the ServletContextListener interface. 2

ServletContextListenerImpl code:

public class ServletContextListenerImpl implements ServletContextListener { /** * */ @override public void contextInitialized(ServletContextEvent sce) { System.out.println("ServletContext object created la la la …………" ); } /** * When the ServletContext object is destroyed, Public void contextDestroyed(ServletContextEvent sce) { System.out.println("ServletContext object destroyed la la la …………" ); }}Copy the code

Configuration in web.xml:

<! -- The listener tag configures the listener --> <listener> <! - the listener - full name of the class class listener configuration - > < listener - class > com. Atguigu. Listener. ServletContextListenerImpl < / listener - class > </listener>Copy the code