Detailed JSP

Detailed
explanation of JSP 1. Basic concepts of JSP
1. Software architecture B/S architecture: Browser/Server,            the biggest advantage of
browser-server is: once deployed, accessed everywhere. C/S architecture: Client/Server, client-server            has rich functions and events, and can fully use a series of computer resources. But upgrade and maintenance are inconvenient. 2. The working principle of the B/S architecture adopts the request + corresponding working mode to interact. 1. Enter to open the browser, enter the URL, and press Enter. 2. The request will be sent by the client browser to the WEB application server for processing. 3. The WEB application server sends the response result (html\css\js\image...) back to the client browser 4. The browser renders and parses the html and presents the page. 3. URL definition: Uniform Resource Locator. Find web resources by URL. Format: Protocol part Host address Target resource address Parameters Example : http://www.cnblogs.com/java/articlelist.jsp?key=tomcat Explanation: Protocol part: http protocol Host address: www.cnblogs.com Resource address: java /articlelist.jsp parameter part: key=tomcat   Note: The default port of the http protocol is: 80. 4. web server



















is a program that can serve documents to requesting browsers. Provide online information browsing services.
Common WEB servers: IIS, Tomcat, WebLogic, Apache, Nginx...
5.Tomcat
download address:
http://tomcat.apache.org/Directory
structure:
1.bin directory: used to store some tomcat Core components, start and stop commands.
    2.conf directory: TOMCAT's configuration directory, which stores a series of tomcat configuration files.
    3.lib directory: store all the Jar packages required for TOMCAT to run.
    4.logs directory: store all log files generated during tomcat startup and operation.
    5.temp directory: temporary directory
    6.webapps directory: the directory published by the web site
    7.work directory: the working directory of the dynamic website published in tomcat.
How to modify the default port of Tomcat:
1. Open the Tomcat directory and find the server.xml file in the conf directory;
2. Find the configuration section <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort=" 8443"/>
3. Change the port to the target port.
6. Configure tomcat in eclipse
1>.Window ->
2>. Expand the Server node and select Runtime Environment.
3>. Click the Add button from the right, select Apache Tomcat 7.0 from the dialog box, and click Next
4>. In the pop-up Tomcat Server dialog box, select the decompression directory of the previous Tomcat. Click Finish.
7. Introduction to the directory structure of the dynamic website created by
eclipse
.
3>.build directory: the compilation directory of java files and jsp files
4>.Web Content -> WEB-INF directory: All files in this directory will not be directly accessed by the client (browser).
So some sensitive resource files can be placed in this directory. For example, the configuration file web.xml file of the website exists in this directory.
8. How to publish a web site in eclipse
1>. Open the Server window
2>. Right-click on the blank area of ​​the Server window, select: New -> Server, a new server window will pop up
3>. Select Tomcat v7.0 Server from the window , click Finish.
4>. Double-click the newly added Tomcat v7.0 Server node, and a new dialog box will pop up.
Select Server Locations from the dialog and check the second item: Use Tomcat installation;

Finally Control + S to save.
5>. Right-click Tomcat, select "Add And Remove"
, select the target website from the left side of the dialog box, and click the Add button to add it to the right side.
Finally click Finish.
9. Solve the problem of Chinese garbled characters in JSP
1>.Window -> Pereferences to open the dialog box, select General -> Content Types:
select Text -> JSP from the right, and then change ISO-8859-1 in the bottom text box For UTF-8
2>. Select General -> Workspace
from the bottom right, select text file encoding, change to: UTF-8.
3>. Select the Web -> JSP Files node, select ISO 10646/Unicode(UTF-8)
from the Encoding on the right,
and then click OK.
10.JSP
JSP (Java Server Pages). JSPs are Java pages that run on the server side. Implemented using HTML nested Java code.
11. Write JAVA code in JSP
1>. <% ... %>
You can write multiple lines of java code in it, and each line ends with a semicolon. Note: Methods cannot be defined.
2>. <%! ... %>
Only global variables and methods can be defined in it.
3>.<%= ... %>
Enter content into the page. Equivalent to <% out.write("abc"); %> == <%= "abc" %>
12. If you import other packages
in , add the attribute import to the page directive, and the value is the package name.
<%@ page import="java.util.*" %>
13. Configure the default page
For example , configure index.jsp as the default page.
1>.Open the web.xml file and modify the welcome-file-list;
2>.Add <welcome-file>index.jsp</welcome-file> to the first node
Note: After each web.xml is modified , to restart Tomcat.
14. The difference between get and post
1. get will follow the parameters to the url address; post will not.
2. The data submitted by get has a size limit, but Post does not.
3. Get submission is not safe, post submission is safe.
4. The get method is conducive to Url propagation, while the post method is not conducive to url propagation.
15. Http status code
200 The request is successful
404 The requested resource does not exist
500 Internal server error
302 Redirection
2. Nine built-in objects of JSP
1. Request object: request
request.
request.setAttibute(String, Object) Store data
Object request.getAttribute(String) Get data
String value = request.getParameter("parameter name"); Get a single value of a parameter
String[] Values ​​= request.getParameterValues("Parameter name "); Get multiple values ​​of a parameter
Note : Only data stored in the same request can be shared.
2. Output object: out
3. Response object: response
forwarding and redirection
Redirection : The client will send two requests to the server successively.
response.sendRedirect("welcome.jsp");
Redirection is client behavior.
Forwarding: The client sends a request to the server, the server requests another page address, and finally responds the result to the client
request.getRequestDispatcher("login.jsp").forward(request, response);
forwarding is the behavior of the server.
4. Application object: application
application is a shared data storage area developed by the server. All sessions can read and write data from the application.
The data stored in the application is always valid (the data is invalid until the server is shut down).
applicaton.setAttribute(String key, Object value);//Save or modify data
Object applicaton.getAttribute(String key); //Read data
applicaton.removeAttribute(String key);//Remove data
5. Session object: session
After the client sends a request to the server for the first time, the session is established. When the browser is closed and reopened, it is another new session. The server creates a separate data storage area for each session.
The data stored in the session is limited by the validity period. The default session timeout is 30 minutes.
There are two ways to change the default timeout time:
way 1: Modify the session expiration time
in the :
<session-config>
        <session-timeout>30</session-timeout>
</session-config>
way Two: Modify session.setMaxInactiveInterval (30*60) through Java code ;// Introduce other methods of session
in seconds 1.session.setAttribute(String key, Object value);//Save or modify 2.Object session.getAttribute( String key); //read data



3.session.removeAttribute(String key);//Remove data
4.session.invalid();//Set session invalidation (session invalidation and all stored data of the session will be lost)
6. Page context object: pageContext
7 .Page object: page
8. Configuration object: config
9. Exception object: exception
3. Cookie introduction
1>.Cookie stores data on the client computer.
Cookie cookie1 = new Cookie(String, String);
write a cookie to the client, use response: response.addCookie(...);
to get the client's cookie, use request: request.getCookies();
2>.Cookie also has a life cycle (expiration date), via cookie.setMaxAge(int seconds).
If seconds=0, it means that the cookie is automatically invalidated when the browser is closed;
if seconds<0, it means that the cookie is deleted from the client;
if seconds>0, it means the specific time when the cookie expires.
Note: JSESSIONID is a cookie added by the system. After each session is created, JSESSIONID will be added to the cookie.
3>. For some insensitive (unimportant) business data, and the amount of data is small, it can be stored in cookies.
4>. Differences in cookie, session, and application in storing data.
The same point:
cookie, session, application can store data.
Differences:
1. Both session and application store data on the server side;
2. Cookies store data on the client side;
3. Session is a user session level, and different users cannot share data; application is global, and all users share data .
4. Session and application will put pressure on the server, while cookies will not.
Fourth, JSP garbled problem (java background garbled)
JSP defaults to ISO-8859-1 encoding, which does not support Chinese characters and other characters. So you need to set the encoding format in the background.
Encoding solution when sending a request in GET mode:
The first one: String title = request.getParameter("advtitle");
    String title1 = new String(title.getBytes("ISO-8859-1"), "UTF-8 ");
Second: Modify the Connector in tomcat's conf->server.xml and add the URIEncoding attribute.
<Connector URIEncoding="UTF-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1"
The encoding solution when sending the request by POST:
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
5. JDBC
1. Basic Concept
Definition : Java DataBase Connectivity. Java database connection technology.
Purpose: used to implement the operation of java programs and various databases (Oracle|Mysql|Sql Server...).
JDBC provides a set of classes and interfaces (APIs) located in the java.sql and javax.sql packages.
2. Steps for JDBC to access the database
1>. Load the driver
First copy the driver jar package file to the lib directory of the web project
Class.for("driver class");//Load the driver
2>. Get the connection object
Connection string: jdbc:mysql://127.0.0.1:3306/newsdb?user=root&password=123456
Connection connection = DriverManager.getConnection("connection string");
3>. Create a Statement and execute the SQL statement
Statement stmt = connection .createStatement();
int count = Statement.
Note:
The SQL processed by the executeUpdate method includes DML (insert|update|delete) and DDL (Create|ALTER|DROP)
        . The return value of the executeUpate() method is int
insert|update|delete The return value is greater than 0, indicating a successful
create The return value of |alter|drop is always 0
Statement.executeQuery(String sql);
Note:
The SQL processed by the executeQuery method includes DQL (select)
4>. Return the ResultSet result or the number of rows affected by the database
ResultSet set = stmt.executeQuery() ;
while(set.next()==true){
    //Take a loop once
    set.getString(arg0);//Take a string
    set.getInt(arg0);//Take an integer
    set.getDouble(columnLabel);/ / Take double
set.getFloat(columnIndex);// Take float
set.getDate(columnIndex);// Take the year, month and day
set.getTime(columnIndex);// Take the hour, minute and second
set.getTimestamp(columnIndex)// Take the year and month day hour minute second    
}
5>.Close the connection
connection.close();
3. SQL injection
  The user enters some special characters, so that the SQL statement dynamically spliced ​​in the program changes the meaning of the original execution, and finally obtains unexpected results.
  The reason for SQL injection is that the SQL statements in the program are dynamically spliced ​​through strings.
  For example:
String sql = "select * from userinfo where username='"+uname+"' and password='"+upass+"'";
If uname = zhangsan upass = 123456, then the value of the above sql variable is:
select * from userinfo where username='zhangsan' and password='
123456'If uname = 1' or 1=1 or '1 upass = 123456, then the value of the above sql variable is:
select * from userinfo where username='1' or 1=1 or '1' and password='123456'
4. How to avoid SQL injection in the program?
Use parameterized queries. Specifically, try not to use the Statement class in the program, but use the PreparedStatement class.
Statement is the parent class of PreparedStatement.
//In the SQL statement, each parameter uses? as a placeholder
String sql = "select count(*) from userinfo where username=? and userpass=?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, username);
stmt.setString(2, userpass);
ResultSet set = stmt.executeQuery();
6. Hierarchical development
1. Hierarchical development
  In the actual development process of the project, the entire project will be divided into interface layer, business logic layer and data layer from top to bottom.
  Three-tier development is a typical development mode in project development practice.
  Purpose: To achieve high cohesion and low coupling.
2. Functions of each layer
  Interface layer
    functions: responsible for data display and collection of user input. That is, the layer that interacts with the user.
          The interface layer generally refers to jsp pages, html pages, etc.
  Business logic layer
    function: responsible for processing the business logic of functional modules, as well as data flow between the interface layer and the data layer.
    The principle of adding classes: add classes
        according to functional modules. For example, if there is a user management module, the UserManagerService class can be added.
  Data layer
    function: interact with the database.
          Generally, SQL statements are written in the data layer; JDBC; Hibernate, mybatis.
    The principle of adding classes:
        add a corresponding data operation class to each data table. For example, in the user table userinfo, add the UserInfoDao class.     The entity class created by the
  entity layer for the data table; + some user-defined entity classes 3. The calling relationship between each layer The   interface layer calls the business logic layer; the   business logic layer calls the data layer;  the   data layer operates the database;   note: call The meaning is to create the corresponding class object in the code, and then call the method through the object.   4. Advantages and disadvantages of layered development :   1. Developers can only focus on one of the layers in the entire structure;   2. The implementation of the original layer can be easily replaced with a new implementation;   3. The layer and the Dependency between   layers; 4. It is beneficial to the reuse of logic of each layer.   Disadvantages:   1. It reduces the performance of the system.   2. It increases the complexity of the program.   3. It sometimes leads to cascading modifications.















Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326316762&siteId=291194637
jsp