Han shunping Servlet and JSP learning notes

Source: Internet
Author: User
Tags rowcount

Java EE Overview:

Java EE is an open platform with many technologies, including 13 core technologies (Java EE is the general term for 13 technologies ). Create an overall concept.

Thirteen J2EE technologies (specifications)

1. Java database connection (JDBC ). -- JDBC defines four different drivers: 1. JDBC-ODBC bridge, 2. JDBC-native Drive Axle 3, JDBC-Network Bridge 4. pure Java driver.

2. Java Naming and Directory Interface (JNDI) [it is used to access the basic structure of directories used in advanced network application development ].

3. enterprise Java Beans [Enterprise Java Beans, EJB) (it provides an architecture to develop and configure distributed business logic to the client, therefore, it can significantly reduce the development scalability and complexity of enterprise applications. ].

4. assumerver pages [JSPs ].

5. java Servlets [most of the functions provided by servlets are the same as those provided by JSP. Most of JSP's functions are HTML code, with only a small amount of Java code, while servlets is the opposite. It is completely written in Java, and generate HTML code ].

6. Java IDL/CORBA [not used much ].

7. Java Transaction System (JTA)/Java Transaction Service (JTs) [not used much ].

8. javamail and javabenas activation architectures (javans activationframework, JAF ). Javamail is an API used to access the mail service ].

9. Java Messenger Service (JMS) [JMS is an API used to communicate with the information-oriented Middle Layer ].

10. Extended Markup Language [Extensible Markup Language, XML ].

11. 12. 13 currently popular pass framework STRUTS + hibernate + spring [SSH ].

------------------------------------------------------------------------------

There are several important development modes in Java EE development:

1. model1 Mode 2. model2 mode (model2x mode (rarely used) 3. MVC Mode

I. model1 Mode

The basis of model1 is a JSP file, which consists of some independent JSP files and other Java classes (not required ). The JSP obtains the required data from httprequest, processes the business logic, and then returns the result to the browser through response.

From the above analysis, we can see that the model1 mode can be divided into two types:

1. model1 (pure JSP technology without any Java class ).

2. model1 (JSP + Java class ).

Disadvantages of model1 mode:

1. The presentation layer and business layer are mixed together (messy !).

2. in the development process, it is not conducive to collaborative development by multiple people.

3. It is not conducive to later maintenance.

Advantages of the model1 mode:

1. simple and fast development.

2. Suitable for developing small projects.

Ii. model1 (combined with Java class) development mode. Some books refer to it as MV mode, I .e. mà model (Java class, business logic layer) and và view (JSP, interface Layer ).

1. A database should have a class: conndb. Java (get the connection ).

2. Each table in the database corresponds to two classes: (1) userbean. Java (users table) class. (2) userbeancl. Java (business logic, that is, the operation on the users table) class.

For example:

Login. jsp inputs data. logincl. jsp processes data by calling Java class (model), and wel. jsp displays data. This is a perfect development model.

Disadvantages:

1. JSP technology mainly serves as the interface, but logincl. jsp calls Java class (model) here to complete user verification, which is a little strange.

2. wel. JSP is used to display User Information (display data), but, wel. in addition to displaying data, JSP also calls a Java class (model). the elegance of the Code disappears, and the division of labor cannot be achieved in the future.

3. Servlet technology handles page jumps as quickly and conveniently as possible. Don't we need to skip this?

Iii. MVC development mode: m (model), V (view), and C (Controller ).

MVC is a design pattern that forcibly separates the input, processing, and output of the application program. The MVC application is divided into three core components: model, view, and controller. They process their own tasks.

M is mainly implemented by Java class, or Java Bean, EIB, etc.

V is implemented by JSP

C is implemented by servlet.

The above example is improved:

1. Add a controller (servlet): replace logincl. jsp with a servlet to give full play to the advantage of Servlet as a control transit.

2. Call the model in the Controller (servlet) to complete user verification and prepare the user information data to be displayed.

 

Summary of the MVC development model:

Processing process: the Controller first receives the user's request and determines which model should be called for processing. Then, it calls the model to process the user's request and return data, finally, the Controller displays the data returned by the model in the corresponding view and presents it to the user through a browser.

Disadvantages of the MVC mode:

1. The workload has increased.

Since developers divide an application into three parts, using MVC also means that you are going to manage more files than before. It seems that our workload has increased, but remember that this is not worth mentioning compared to the benefits it can bring us.

2. Small projects are not applicable; otherwise, machine-gun attacks will occur.

3. It is more difficult to debug the application.

MVC advocates separation of models and views, which also makes it difficult to debug applications. Each component must be thoroughly tested before use. Once your components have been tested, you can reuse them without any worries.

------------------------------------------------------------------------------

The username in the database is Chinese and garbled Chinese characters (generally, transcoding is required only when Chinese characters are available for data query ):

When a form is submitted, it contains Chinese characters and garbled characters.

There are three methods to solve Chinese Garbled text:

1. Re-transcoding, such as, there are string u = "Chinese"; u = newstring (U. getbytes ("iso-8859-1"), "gb2312 ");

2. Use a filter to solve the problem [Detailed description]

3. Modify tomcat to configure the servlet. xml file [unstable.]. The specific operations are as follows:

<Connectorport = "8080" protocol = "HTTP/1.1" maxthreads = "150" connectiontimeout = "20000" redirectport = "8443"/> changed:

<Connectorport = "8080" protocol = "HTTP/1.1" maxthreads = "150" connectiontimeout = "20000" redirectport = "8443" uriencoding = "GBK"/>

Add the uriencoding attribute to the <connector> element. The value is "GBK", indicating that the values sent by client requests are all encoded according to gb2312, in this way, you do not need to convert the code in business processing, which greatly simplifies the program and improves the execution efficiency.

When the request is garbled, it can be solved as follows (you must write it as follows ):

Name = new string (request. getparameter ("username"). getbytes ("ISO-8859-1"), "gb2312 ");

------------------------------------------------------------------------------

3. inherit from the httpservlet class (This class includes the doget and dopost methods)

Servlet Lifecycle

1. the init () function is used to initialize the servlet (similar to the class constructor, this function is called only once (when the user first accesses the page servlet .).).

2. business logic functions (such as service, doget, and dopost) are called every time a user accesses the servlet. It has two parameters: servletrequest-used to obtain client information, servletresponse-used to return information to the client ).

3. the destroy () function is used to destroy servlet instances (release memory). It is used weekly only in the following three cases (1. reload the servlet (webapps), 2. disable tomcat, 3. shut down) after the value of this function is passed, all sessions and contest in the website will be released and empty.


------------------------------------------------------------------------------

Differences between form-based data submission GET requests and post requests

1. Get <post in terms of security, because the data submitted by get is displayed in the address bar of the browser.

2. From the perspective of the size of the submitted content, get <post means that the data submitted by get cannot exceed 2 K, and the data submitted by the surface post is not limited theoretically, but it is not recommended to be larger than 64 K in actual programming.

3. From the perspective of request response speed, get> post requires the server to immediately respond to the request, while the POST request may form a queue request.

From the above points, we recommend that you use Post

The HTML statement printed in sevlet can be enclosed with no quotation marks.

Four data sharing methods for different pages of the same user

1. Cookie (cookie, In the javax. servlet. http. *; Package) (the server saves user information on the client, such as the login name, password... It is a cookie. The data volume is not large, and the server can read from the client as needed .).

Cookie usage: ① cookie is a bit like a table, which has two columns: name, value, and data type. ② Create a cookie (created on the server): cookie
C = newcookie (string name, string Val); ③ Add the cookie to the client: response. addcookie (c); ④ read cookie (read from client to server): Cookie [] allcookie = request. getcookies (); C. getname (); C. getvalue (); Method read ⑤ modify cookie time: C. setmaxage (30); Unit: seconds. If it is negative, the cookie will not be stored. If it is 0, the cookie will be deleted. If no time is set, the cookie will not be saved.

2. sendredirect (address jump, pay attention to Chinese processing)

3. session Technology (when a user opens a browser and accesses a website, the server allocates a space for the browser in the server memory, which is exclusive to the browser, this space is the session space, where the data default time is 30 min, can be modified (modified in the conf-web.xml )).

Session usage: ① get session: httpsessionhs = request. getsession (true );

② Add attributes to the session: HS. setattribut (stringname, object Val); ③ get an attribute from the session: stringname = HS. getattribute (string
Name); ④ delete a sex from the session: HS. removeattribute (string name); ⑤ modify the time when the session exists: HS. setmaxinactiveinterval (20); Unit: seconds. If it is negative, it never times out. If it is 0, it times out immediately.

Because each session attribute occupies the server's memory, software companies are forced to use it.

Note: The window is opened in the form of file-New-window. The session ID remains the same, that is, the same session space.

 

4. Hide form submission (form) (input type = hiddenname = "" value = ""). You can submit the form together. (Obtain method: Req. getparameter (stringname );).


------------------------------------------------------------------------------

Cookie vs session

1. Existing location: the cookie is saved on the client, and the session is saved on the server.

2. Security: In comparison, Cookie security is weaker than Session Security.

3. Network Transmission volume: cookies are transmitted on the client and server over the network, while sessions are stored on the server without transmission.

4. Life Cycle (20 minutes as an example) ① the life cycle of a cookie is cumulative. The timer starts from the time of creation. After 20 minutes, the cookie life cycle ends and the cookie becomes invalid. ② The lifecycle of a session is an interval. The time starts when the session is created. For example, if the session has not been accessed for 20 minutes, the session information is invalid. If within 20 minutes, for example, if a session is accessed within 19th minutes, its life cycle starts to be computed again. ③ In addition, shutdown may end the session lifecycle, but it has no impact on the session.

Use servletcontext (same as session, but all its customers can access it ).

1. Get the servletcontext instance: This. getservletcontext ();

2. You can think of it as a table, which is very similar to session: each row is an attribute. Add attributes: setattribute (string name, object ob );

Value: getattribute (stringname); returns the object.

Delete attribute: removeattribute (stringname );

3. Life Cycle: The Life Cycle of attributes in servletcontext starts from creation and ends when the server is closed.

4. Notes for using servletcontext: because data in servletcontext is stored on the server for a long time, it will occupy the memory. Therefore, we recommend that you do not add too much data to servletcontext .......
Remember

------------------------------------------------------------------------------

Paging Technology (method)

Let's talk about the paging algorithm first:

We need to define four quantities for their respective use, as shown below:

Int pagesize: How many records are displayed on each page

Int pagenow: page number to be displayed

Int pagecount: Total number of pages

Int rowcount: Total number of records

Note:

Pagesize is a specified (constant ).

Pagenow is the selected variable ).

Rowcount is obtained from the table query (a variable ).

Pagecount is calculated. The formula is:

If (rowcount % pagesize = 0)

{

Pagecount = rowcount/pagesize;

}

Else

{

Pagecount = rowcount/pagesize + 1;

}

Then we can query the database. We may naturally think of using

Select field list from table name where ID? And?

However, if a table ID is deleted, a page may have one fewer record.

The final solution is as follows:

Select toppagesize field name list from
Table name whereIDNot in

(Select top pagesize * (pageNow-1)IDFrom
Table name)

Pages can be displayed in a drop-down box or text

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.