JSP9 built-in objects (no need for new, can be used directly)
pageContext JSP page container
request request object
response object
session response object
application global object
config configuration object (server configuration information)
out output object
page The current JSP page object (equivalent to this in java)
exception exception object
application global object
——String getContextPath() virtual path
——String getRealPath("virtual path") absolute path (absolute path relative to virtual path)
(Built-in objects do not include cookies)
Four scope objects
pageContext JSP page container The current page is valid but invalid after the page jumps
request Request object The same request is valid, request forwarding can be obtained (internal server), redirection cannot be obtained (return to client, client re-request)
session Session object The same session is valid (no matter how you jump, it is valid, and it is invalid after closing and switching browsers)
The application global object is globally valid, valid during the entire project operation (closing the service and other projects are invalid)
Try to use the smallest range, because the larger the range of the object, the greater the performance loss caused
Methods shared by the above four objects:
Object getAttribute (String name): Get the attribute value according to the attribute name
void setAttribute(String name, Object obj): set attribute value (new, modified)
setAttribute("a", "b") //If the a object does not exist before, create a new a object with a value of b
If a already exists before, change the value of a to b
void removeAttribute(String name): According to the attribute name, delete the object
The difference between request forwarding and redirection
Request forwarding: xxServlet receives the request, then forwards it directly to yyServlet, and then yyServlet returns to the client. Throughout the process, the client sends a request and receives a response.
Redirection: xxServlet receives the request and sends a response to the client. The client immediately sends a request to access the URL given in xxServlet, which is the path of yyServlet, and then yyServlet sends a response to the client. During the whole process, the client sends two requests and receives two responses.
Request forwarding: Use the forward method in the RequestDispather interface to implement request forwarding.
Request redirection: Use the sendRedirect method of HttpServletResponse to achieve request redirection.
1. Request forwarding: The address bar is the address where the request was made for the first time.
Request redirection: The address bar is not the address of the initial request, but the address of the last response.
2. Request forwarding: In the final Servlet, the request and the transfer request are the same object.
Request redirection: In the final Servlet, the request and the transfer request are not the same object.
3. Request forwarding: It can only be forwarded to the resources of the current web application.
Request redirection: You can redirect to any resource.
4. Request forwarding: / represents the root directory of the current web application.
Request redirection: / represents the root directory of the current web site.
session mechanism
session is stored on the server
Cookie(“JSESSIONID”,“ID值”)
When the client requests the server for the first time, (the JSESSIONID-sessionId match fails), the server will generate a session object (used to save the client’s information), and each session object will have a unique sessiId (used to distinguish other session); the server will generate a cookie that also contains a key-value pair, name=JSESSIONID, value = server sessionId, and then the server will respond to the client while sending the cookie to the client. The client has a cookie (JSESSIONID). (Corresponding to JSESSION-cookieId).
When requesting the server for the second/nth time, the server will first use the JSESSIONID in the client's cookie to match the server's sessionid.
The session is shared when the same client requests
session method
String getId():获取sessionId
boolean isNew(): Determine whether it is a new user (first visit)
void invalidate(): invalidate the session (log out, log out)
void removeAttribute() Add parameters to invalidate part
void setAttribute()
Object getAttribute()
void setMaxInactiveInterval (seconds) set the maximum effective inactive time
request: The data is valid in the same request (not in different browsers)
Session and cookie comparison
session(HttpSession) | cookie | |
Saved location | Server (Security) | Client (insecure) |
Saved content | Object | String |
Three major functions of JDBC API.
Mainly through the following classes/interfaces to achieve
DriverManger: Manage drivers
Connect: Connect (obtained through DriverManger)
effect:
Generate objects for operating the database
Generate Statement object-createstatement()
Generate PreparedStatement object-prepareStatement()
Generate CallableStatement object-prepareCall()
Statement (PreparedStatement is the interface of Statement): add, delete, modify and check (generated by the Connect object)
Statement role: operating database
Addition, deletion and modification: executeUpdate()
Query: executeQuery()
PreparedStatement (recommended)
Role: operating database
Addition, deletion and modification: executeUpdate()
Query: executeQuery()
Assignment operation setXxx()
advantage
1 Coding is more concise
2 Improve performance (pre-compilation)
3 Safely prevent sql injection attacks (mix the customer injection content with the developer's sql statement)
- is the comment statement of sql
CallableStatement: Call the stored procedure/stored function in the database (generated by the Connect object)
connect object.prepareCall (stored procedure or stored function name) function generated
Stored procedure (no return value return, use out parameter instead): {call stored procedure name (parameter list)}
Stored function (with return value): {? = call storage function name (parameter list)}
Result: return result set (generated by Statement etc.)
Role: save the result set select * from xxx
next(): Whether there is data next to the current data: return value true/false
previous() Whether there is data in the previous one of the current data: return value true/false
2 The specific steps of jdbc to access the database
a Import the driver, load the specific driver class
b Establish a connection
c send sql
d Processing result set
Database driver driver.jar
Oreacle ojdbc-x.jar
Mysql mysql-connector-java-x.jar
Sqlserver sqljdbc-x.jar
3 Processing CLOB/BLOB type
mysql:text
Processing slightly larger data
a. Put the storage path into the database, store the file path through JDBC, and then process it according to the IO operation.
b
CLOB: Large text data (novel)
Save
1 First through psmt? (Placeholder) instead of novel content
2 Through pstmt.setCharacterStream (2, reader, (infile.length()); replace the placeholder in the previous step with a novel stream, and inject
take
1Pass Reader reader = rs. getCharacterStream("NOVEL"); save the data of cloc to the Reader object
2 Output the Reader through Writer.
BLOB: Binary byte stream InputStream OutputStream, basically the same as the CLOB steps, the difference (the creation method is different): setBinaryStream(...) getBinaryStream(...)
4 JAVABean
effect
Reduce the complexity of JSP
Improve code reuse rate
Definition: It is a java class that meets the following two points
1 Public modified class, no parameter structure
2 All attributes are private, and set/get methods are provided (if it is a Boolean type, set is changed to is)
Use level java is divided into two categories (similar structure)
One package business logic (login logic) can encapsulate the jdbc code in jsp into the login.java class (login.java)
2 encapsulated data (entity class, Student.java, Person.java) equivalent to a table in the database
Encapsulated business logic is used to manipulate a packaged data
MVC design pattern
M:model is implemented by a functional javabean
V: View display and user interaction technology html, css, js, jsp
C: The controller accepts the request, jumps to the model for processing, and returns the processing result to the request interface. It is recommended to use servet to achieve
jsp>java(servet)>jsp
wealth:
The java class must conform to certain specifications
a must inherit javax.ser.httpservlet
b Rewrite the doget() or dopot() method
doget(): accept all get() requests
dopost(): accept all post() requests
Before using the servlet, you need to configure web.xml, the mapping relationship servlet-mapping interception, through the name matching in the servlet, execute the class
Or @servlet (3.0) annotation method for configuration
Matching process: the request address is matched with the value of @servlet
Five stages of servlet life cycle
Loading and unloading: automatic processing by the servlet container
load
Initialize the init() method, the servlet is loaded and instantiated and then executed. It can be modified to execute when tomcat starts (servlet 2.5, change in web.xml:
<servlet>
<load-on-startup>1</load-on-startup>
</servlet>
Servlet3.0 mode, written in the comments
1 represents the execution order when the first servlet starts
Service service () method, you can override doget (), dopost () method for specific implementation
Destroy destroy(), executed when the servlet is recycled by the system
Uninstall
5 Servlet API: consists of two software packages, the software package corresponding to the http protocol, and other software packages except the http protocol, that is, the Servlet API can be applied to any communication protocol.
The classes and interfaces in the javax.servlet.http package are inherited from http
6 Servlet inheritance relationship
ServletConfig interface
ServletContext getServletContext(): Get the Servlet context object application
String getInitParameter(String name): Get the parameter value named name in the current Servlet range
Servlet2.5 is configured in the xml file
Servlet3.0 is configured in the annotations, belongs to this Servlet only, and cannot be configured with global parameters
The HttpServlet Request method is the same as the request method
a Three-tier architecture
Consistent with the goal of the mvc design pattern, both are for understanding coupling and improving code reuse rate. The difference is that the two have different understanding of the project
b Three layers
Presentation layer (USL user show layer) view, view layer
-Foreground: Corresponding to the View in MVC, used to interact with users and display the interface
Web front-end technologies such as jsp, js, html, css, jquery, etc.
Code location: webContent
-Background: Corresponds to the Controller in MVC, used to control the jump and call the business logic layer
Servlet (springMVC Struts2), located at xxx. servlet package
Business Logic Layer (bll, Business Logic Layer) service layer
-Accept the request of the presentation layer, call
-Assemble the data access layer, logical operations (addition, deletion, modification and investigation)
Generally located in the xxx.service package (can also become: xxx.manager, xx.bll)
Data Access Layer (DAL, Data Access Layer) dao layer
-Direct access to the database operation, atomic operation (addition, deletion, modification, and check)
-Generally located in the xxx.dao package
Get the out object in the servlet: through PrintWriter out = response.getWriter()
Get the session object in the servlet: requster.getSession()
Get the application object in the servlet: reque.getServletContext()
The encoding setting of the response needs to be created before the response object is created
Three-tier optimization
1 Add interface recommendations for interface development: first interface-before implementing the class
——Service, dao join interface
——The naming convention of interfaces and implementation classes: Interface: interface named to implement IXxxService, IXxxDao. Implementation class implements, named XxxDaoImpl, XxxServiceImpl
——When implementing interface/implementation class, the recommended way of writing: interface x = new implementation class();
2 DBUtil general database helper class to simplify the amount of code in the Dao layer
index.jsp ->index_jsp.java->index_jsp.class JSP translated into java and compiled class files exist in the work directory of tomcat
The difference between web debugging and java code debugging: different startup methods, web debugging