What Are Java Foundation Classes?
Java source program (.java file)-> java byte code file (.class file)-> The byte code file is loaded into the java virtual machine (jvm) by the interpreter (java.exe)-> word The section code file (.class) will be executed in the java virtual machine.
java foundation
discuss
- Chinese name
- java
- Application
- The internet
- Java source program (.java file)-> java byte code file (.class file)-> The byte code file is loaded into the java virtual machine (jvm) by the interpreter (java.exe)-> word The section code file (.class) will be executed in the java virtual machine.
- Java's basic package java.lang contains:
Interface: Comparable, Cloneable, Runable and other classes: Eight basic data type encapsulation classes, Byte, Short, Integer, Long, Boolean, Character, Float, Double, etc. Difference between ArrayList and Vector, HashMap and Hashtable
- Answer: As far as ArrayList and Vector are concerned, there are two aspects:
- I. Synchronization: Vector is thread-safe, that is, synchronous, while ArrayList is unsafe and is not synchronous.
2. Data growth: When growth is needed, Vector defaults to the original one, while ArrayList is half of the original ArrayList, Vector, LinkedList storage performance and characteristics.
ArrayList and Vector both use arrays to store data. The number of array elements is greater than the actual stored data in order to add and insert elements. They both allow indexing elements directly by sequence number, but inserting elements involves memory operations such as moving array elements, so index data Fast and slow data insertion. Because Vector uses the synchronized method (thread-safe), the performance is usually worse than ArrayList. LinkedList uses a doubly linked list to store data. Indexing data by sequence number requires forward or backward traversal. You need to record the preceding and following items of this item, so the insertion speed is fast.
As far as HashMap and HashTable are concerned, there are three main aspects.
1. Historical reasons: Hashtable is based on the old Dictionary class. HashMap is an implementation of the Map interface introduced in Java 1.2. Synchronization: Hashtable is thread-safe, that is, synchronous, and HashMap is not safe for online programs. The value is not synchronized. Only HashMap allows a null key in a collection and multiple null values in a set. Hashtable is a synchronous version of HashMap; HashMap allows null values and a null key. However, Hashtable Nothing is allowed to be null. Objects of the Hashtable class must override the hashCode () and equals () methods of the Object class for other collection types.
I. ArrayList provides fast traversal and quick access. A new RandomAccess interface is now designed, which states that this list supports fast random access. Vector also implements the RandomAccess interface.
2. When traversing HashSet and HashMap, the order is unknown (but adding and deleting are fast). LinkedHashSet and LinkedHashSet are traversed in the order of element insertion (traversal is fast).
three. TreeSet and TreeMap will ensure that the elements are arranged in their natural order. You can also use a comparison rule implemented by the user.
Fourth, HashSet has a hash table to support it. It provides fixed-time performance for basic operations. TreeSet It ensures that the sorted set will be sorted in ascending order of elements and according to natural order.
The Dictionary class is mainly used to convert keywords into values. This class receives a keyword and returns a value. Dictionary is an abstract class, which is a superclass of Hashtable.
The Properties class extends the Hashtable class, but the keywords and values of the Properties object must be String and can write the object to an output stream and save it in a file, which can then be read back to an input stream.
If you need to maintain and search a list of parts, they are identified by a unique alphanumeric serial number, where the parts are part types, which collection should you use? If we change requirements, do you also need to be able to print out parts in order, with their serial numbers?
1.HashMap should be selected
2.TreeMap should be selected
There are several implementation methods for multithreading, what are they? There are several implementation methods for synchronization, what are they?
Answer: There are two implementation methods for multithreading. There are two implementation methods for inheriting the Thread class and implementing the Runnable interface synchronization. They are synchronized, wait, and notify.
Abstract classes and interfaces?
Answer: Both abstract classes and interfaces are used for abstraction, but abstract classes (in Java) can have their own partial implementations, and interfaces are completely an identity (with multiple inheritance functions).
Can an abstract method be both static, native, and synchronized at the same time? Can interfaces not inherit interfaces? Can abstract classes implement interfaces? Can abstract classes inherit concrete classes? ?
Interfaces can inherit interfaces. Abstract classes can implement interfaces. Abstract classes can inherit entity classes, but only if the entity class has an explicit constructor.
Can Anonymous Inner Class extend other classes, can it implement interfaces?
You can inherit other classes or complete other interfaces. This method is commonly used in swing programming.
IO Stream Byte Stream: Data is stored in bytes during storage and transmission. Commonly used to read and write binary data, such as image and sound files.
Character stream: Data is stored in characters when it is stored and transmitted.
Stream: An abstraction of a data source. Its purpose is to access a variety of different data sources (files, networks, memory buffers) in a unified manner. Basic classes for reading and writing files: The File class provides local file system positioning. Describe the function of files and directories. Pipeline streams are used to communicate between threads: PipedInputStream, PipedOutputStream, PipedReader, PipedWriter
Thread 1 PipedOutputStream PipedInputStream Thread 2
keyboard input:
try {
BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
String s = br.readLine ();
System.out.println (s);
} catch (Exception e) {
}
File input and output:
try {
File f = new File ("test.txt");
FileOutputStream fout = new FileOutputStream (f);
fout.write (System.in.read ());
fout.close ();
FileInputStream fin = new FileInputStream (f);
int size = fin.available ();
for (int i = 0; i <size; i ++) {
System.out.print ((char) fin.read ());
}
fin.close ();
} catch (Exception e) {
}
Transfer files over the network:
Client:
File f = new File ("bk.exe");
FileInputStream fin = new FileInputStream (f);
Socket st = new Socket ("localhost", 6000);
BufferedOutputStream bout = new BufferedOutputStream (st.getOutputStream ());
int size = fin.available ();
for (int i = 0; i <size; i ++) {
bout.write (fin.read ());
}
Service-Terminal:
ServerSocket server = new ServerSocket (6000);
Socket st = server.accept ();
File f = new File ("kk.exe");
BufferedInputStream bin = new BufferedInputStream (st.getInputStream ());
FileOutputStream fout = new FileOutputStream (f);
int i = 0;
while (i! =-1) {
i = bin.read ();
fout.write (i);
}
Considerations for serialization and how to achieve the life of a serialized object usually end with the termination of the program that generated the object. Sometimes it may be necessary to save the state of an object and restore it when needed. We call this object's ability to record its state for future regeneration, called the object's persistence. Objects record themselves by writing out values describing their state. This process is called object serialization.
The process of serialization is that the object writes to and reads from the byte stream. After the object state is converted into a byte stream, it can be saved to a file with various byte stream classes in the java.io package, piped to another thread, or sent to another host through a network connection.
One: Object serialization can implement distributed objects.
Second: Java object serialization not only retains the data of an object, but also recursively saves the data of each object referenced by the object.
Common sorting method:
public class Sort {
public static int count = 0;
public boolean LT (int num1, int num2) {
return num1 <num2;
}
public void output (int [] array) {
System.out.print ("Sort" + count + "Sorting:");
for (int i = 0; i <array.length; i ++)
System.out.print (array [i] + "");
System.out.println ();
}
- }
// bubble sort method public void BubbleSort (int [] array) {
boolean swap = true;
int index = 0;
int i = 0;
while (i <array.length-1) {
int temp = array [i];
for (int j = i; j <array.length; j ++) {
if (! LT (array [i], array [j])) {
int temp2 = array [i];
array [i] = array [j];
array [j] = temp2;
swap = true;
index = j;
} else {
swap = false;
}
}
i ++;
if (swap) {
array [i] = array [index];
array [index] = temp;
i ++;
}
output (array);
}
}
- }
// Direct insertion sort method public void InsertSort (int [] array) {
for (int i = 1; i <array.length; ++ i) {
if (LT (array [i], array [i-1])) {
int temp = array [i];
array [i] = array [i-1];
array [i-1] = temp;
for (int j = i-1; j> 0;-j) {
if (LT (array [j], array [j-1])) {
array [j] = array [j-1];
array [j-1] = temp;
} else {
break;
}
}
output (array);
}
}
- }
// Quick sort method private int Partition (int array [], int low, int high) {
int temp = array [low];
int pivotkey = array [low];
while (low <high) {
while (low <high && array [high]> pivotkey)-high;
array [low] = array [high];
while (low <high && array [low] <= pivotkey) ++ low;
array [high] = array [low];
}
array [low] = temp;
output (array);
return low;
}
- public void qsort (int array [], int low, int high) {
- if (low <high) {
int pivotloc = Partition (array, low, high);
QSort (array, low, pivotloc-1);
QSort (array, pivotloc + 1, high);
}
}
- qsort (int array [], int low, int high) {
if (low <high) {
int pivotloc = Partition (array, low, high);
QSort (array, low, pivotloc-1);
QSort (array, pivotloc + 1, high);
}
}
- void QuickSort (int array []) {
QSort (array, 0, array.length-1);
}
public static void main (String args []) {
int array [] = {49,38,65,97,76,13,27,49};
Sort sort = new Sort ();
System.out.println ("=====================================);
sort.output (array);
System.out.println ("Optimized Bubble Sort");
sort.BubbleSort (array);
System.out.println ();
System.out.println ("=====================================);
array = new int [] {49,38,65,97,76,13,27,49};
sort.output (array);
System.out.println ("Inline Sort");
sort.InsertSort (array);
System.out.println ("Insert Sort");
sort.InsertSort (array); System.out.println ();
System.out.println ("=====================================);
array = new int [] {49,38,65,97,76,13,27,49};
sort.output (array);
System.out.println ("Quick Sort");
sort.QuickSort (array);
}
}
For example, in the COLLECTION framework, what kind of interfaces should be implemented?
Comparison in the Collection framework To implement the Comparable interface and Comparator interface What is a thread?
A thread is similar to a process. It is a piece of code that performs a specific function. It is a single sequence of flow control in a program. However, unlike a process, multiple threads of the same type share a memory space and a set of system resources, and the thread itself The data is usually only the register data of the microprocessor and a stack for program execution. So when the system spawns a thread, or switches between threads, the burden is much smaller than the process. Because of this, the thread is called a light-weight process. A process can contain multiple threads.
A thread is a sequential control flow within a program.
1. Process: Each process has independent code and data space (process context), and the overhead of process switching is large.
2. Threads: Lightweight processes. The same type of threads share code and data space. Each thread has an independent run stack and program counter (PC). The overhead of thread switching is small.
3. Multi-process: In the operating system, multiple tasks can be run simultaneously.
4. Multithreading: In the same application, multiple sequential flows execute simultaneously.
Process context), the overhead of process switching is large.
2. Threads: Lightweight processes. The same type of threads share code and data space. Each thread has an independent run stack and program counter (PC). The overhead of thread switching is small.
3. Multi-process: In the operating system, multiple tasks can be run simultaneously.
4. Multithreading: In the same application, multiple sequential flows execute simultaneously. There are similarities and differences between synchronous and asynchronous. Under what circumstances should they be used separately?
Critical resource issues Threads are independent and execute asynchronously, meaning that each thread contains the data or methods required by the runtime, without the need for external resources or methods, and does not have to care about the state or behavior of other threads. However, there are often some threads running at the same time that need to share data. At this time, the status and behavior of other threads need to be considered, otherwise the correctness of the running results of the program cannot be guaranteed.
What we need to do is allow one thread to completely complete its task before allowing the next thread to execute. You must ensure that a shared resource can only be used by one thread at a time. The process for doing this is called synchronization.
Synchronization is the process used to ensure that resources can only be used by one thread at a time.
Synchronization does nothing for single-threaded programs. Using synchronization is three to four times worse than asynchronous.
Critical resource issues Threads are independent and execute asynchronously, meaning that each thread contains the data or methods required by the runtime, without the need for external resources or methods, and does not have to care about the state or behavior of other threads. However, there are often some threads running at the same time that need to share data. At this time, the status and behavior of other threads need to be considered, otherwise the correctness of the running results of the program cannot be guaranteed.
What we need to do is allow one thread to completely complete its task before allowing the next thread to execute. You must ensure that a shared resource can only be used by one thread at a time. The process for doing this is called synchronization.
Synchronization is the process used to ensure that resources can only be used by one thread at a time.
Synchronization does nothing for single-threaded programs. Using synchronization is three to four times worse than asynchronous. Thread method introduction:
Constructor:
Thread ()
Thread (Runable target)
Thread (Runable target, String name)
Thread (ThreadGroup group, Runable target)
Thread (ThreadGroup group, Runable target, String name)
Thread (ThreadGroup group, String name)
The code used to complete the "actual function" of a thread is placed in the run method. The Run method can be overridden in a subclass of Thread or in a Runable object. Once a thread dies, it can never be restarted, otherwise it will throw an exception. Starting an already started thread with the start method will also throw an exception. The isAlive, interrupt, Thread.currentThread, suspend, resume, and stopSleep methods can give low-priority threads the opportunity to execute, and the Yield method can only give threads of the same priority the opportunity to execute. The Join method can make the thread that calls the method execute before this. After this method, the thread that calls the join method will not produce output. What should be noted when using Wait and notify?
They can only be used in synchronized blocks;
They need to be used in pairs;
Wait generally appears in a while loop. The while statement is controlled using a boolean flag.
Deadlock When the locked A object attempts to access another locked B object, the B object must also access the locked A object. As a result, both threads are waiting for the other thread to release resources, and a deadlock occurs.
The difference between STRING and STRINGBUFFER.
Answer: The length of STRING is immutable, and the length of STRINGBUFFER is variable. If you often operate on the contents of the string, especially when the content is to be modified, then use StringBuffer, if you need String at the end, then use the StringBuffer toString () method JDBC call the database basic steps JDBC configuration in WEBLOGIC SERVER 1, Establish a connection pool to the specified database
2. Establish a data source DataSource based on the connection pool
3. When accessing the database, find the data source by the JNDI name of the data source, and then obtain the database connection object through the data source. After obtaining the object, a database statement object and a result set object can be sequentially generated for corresponding database operations. JDBC configuration in WEBLOGIC SERVER 1. Establish a connection pool Connection Pool to a specified database
2. Establish a data source DataSource based on the connection pool
3. When accessing the database, find the data source by the JNDI name of the data source, and then obtain the database connection object through the data source. After obtaining the object, a database statement object and a result set object can be sequentially generated for corresponding database operations. import java.sql. *;
import javax.naming. *;
import javax.sql. *;
import java.util. *;
import javax.rmi. *; java.sql. *;
import javax.naming. *;
import javax.sql. *;
importjava.util. *;
importjavax.rmi. *; public class DataSourceTest {
private static Context getInitialContext () throws Exception {
String url = "t3: // localhost: 7001";
String user = "system";
String password = "11111111";
Properties properties = null;
try {
properties = new Properties ();
properties.put (Context.INITIAL_CONTEXT_FACTORY,
"weblogic.jndi.WLInitialContextFactory");
properties.put (Context.PROVIDER_URL, url);
if (user! = null) {
properties.put (Context.SECURITY_PRINCIPAL, user);
properties.put (Context.SECURITY_CREDENTIALS,
password == null? "": password);
}
return new InitialContext (properties);
} catch (Exception e) {
throw e;
}
}
public static void main (String args []) {
UserTransaction tx = null;
DataSource ds = null;
Context ctx = null;
Connection myConn = null;
try {
ctx = getInitialContext ();
tx = (UserTranscation) ctx.lookup ("javax.transcation.UserTranscation");
tx.begin ();
ds = (DataSource) ctx.lookup ("myTxDataSource");
} catch (Exception e) {
e.printStackTrace ();
}
Statement myStatement = null;
ResultSet myResultSet = null;
try {
myConn = ds.getConnection ();
myStatement = myConn.createStatement ();
myResultSet = myStatement.executeQuery (
"select fullname from employee");
while (myResultSet.next ()) {
System.out.println (myResultSet.getString ("fullname"));
}
tx.commit ();
} catch (Exception e) {
try {
tx.rollback ();
} catch (Exception e) {
}
} finally {
myStatement.close ();
myConn.close ();
}
}
}
import javax.xml.parsers. *;
import javax.xml.transform. *;
import javax.xml.transform.dom. *;
import javax.xml.transform.stream. *;
import java.io. *; public class Student {
public static void main (String args []) {
Document doc;
Element students;
Element stud;
Element fName;
Element sName;
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance ();
DocumentBuilder db = dbf.newDocumentBuilder ();
doc = db.newDocument ();
stud = doc.createElement ("Student"); fName = doc.createElement ("FirstName") ;;
fName.appendChild (doc.createTextNode ("John"));
stud.appendChild (fName);
sName = doc.createElement ("surname");
sName.appendChild (doc.createTextNode ("David"));
stud.appendChild (sName); surname ");
sName.appendChild (doc.createTextNode ("David"));
stud.appendChild (sName); students = doc.createElement ("Students");
students.setAttribute ("Department", "Mathematics");
students.appendChild (stud);
doc.appendChild (students); TransformerFactory tf = TransformerFactory.newInstance ();
Transformer transformer = tf.newTransformer ();
transformer.transform (new DOMSource (doc), new StreamResult (System.out));
} catch (Exception e) {
e.printStackTrace ();
}
}
}
Use the DOM API to display the contents of existing XML documents. Use the DOM API to insert XML document data into the database. Use the DOM API to create XML documents from the database. . The different regions identify the language, currency, character set, date format, and other elements widely used in the presentation of information by specific countries.
Applications that support internationalization have the following characteristics:
1. Support other languages without changing the code.
2. Text elements, messages and pictures are kept outside the source code.
3. The data related to cultural background, such as date and time, decimal values and currency in circulation, will be formatted correctly according to the language and geographic location of the user.
4. Support non-standard character set.
5. Applications can quickly adapt to new locales.
To internationalize an application:
1. Hard-coded characters (such as labels, tooltips, and error messages) that users see must be replaced with characters contained in the ResourceBundle. It is a java properties file that maps keywords to character values. And you can use multiple ResourceBundles in different languages, so you can provide different strings for different languages.
2. Using the Locale object, you can format the data into locale-related data.
3. Internationalized applications must also use a unified character encoding standard character set.
Characters in ResourceBundle. It is a java properties file that maps keywords to character values. And you can use multiple ResourceBundles in different languages, so you can provide different strings for different languages.
2. Using the Locale object, you can format the data into locale-related data.
3. Internationalized applications must also use a unified character encoding standard character set. What are the application servers? What is Servlet in terms of Servlet?
Servlet is a Web component deployed in the Web layer in the J2EE application framework and runs on a Web server or application server that supports Servlet. Servlet provides a "request / response" mechanism for client and server information processing.
The client sends the request to the server; the server sends the request to the servlet; according to the client's request, the servlet dynamically constructs the response information and returns it to the server; the server returns the response to the client program.
What is JSP?
JSP is a Web component deployed in the Web layer in the J2EE application framework, and is an extension of Servlet technology. It makes it easy to add dynamic content to static pages. And by using tag libraries, you can greatly save development time; using JavaBeans with JSP can separate data representation and program implementation.
In the MVC architecture pattern:
Use Servlet as controller and JSP as data view.
What is the difference between CGI and Servlet?
CGI (Common Gateway Interface) is a standard that enables web servers to interact with external applications. But this technology has some serious limitations:
1. CGI applications take up a lot of resources. When the system needs to process a request from a user, a new process is created to handle the request. Once the CGI script stops executing, the system must retract the process. The frequent start and stop of this heavyweight process is very inefficient.
2, CGI is difficult to link to other stages of the request process, because they run in different processes on the web server. This makes it difficult to handle authorization, workflow, and logging.
Java Servlet technology provides a component-based, platform-independent way to build web applications. Servlets do not have the performance limitations encountered by standard CGI applications.
Servlets are more efficient than CGI because:
In the Servlet application, only a single heavyweight process will be created, and a lighter-weight thread is used to complete the request processing for each user request, and these threads are automatically maintained by the JVM. Each client request corresponds to a thread, and each servlet class has only one unique object (instance) in the servlet container. The servlet class will reside in memory after the first load.
Resident memory. 1.Talk about the life cycle of Servlet?
Answer: The servlet instance will be created when the servlet is first requested, and the container calls the instance's init method. If the container has a request to pass to the servlet, it will call the servlet instance's service method. A request will act as a thread. If the server wants to destroy the servlet instance, the destroy method of the servlet instance will be called, otherwise the instance will reside in memory.
What is the difference between forward () and redirect () in JAVA SERVLET API?
Use redirection: When the sendRedirect method is called, the web container returns a response to the browser indicating that a new URL is needed. Because the browser makes a completely new request, any objects stored as request properties before the redirect will disappear.
Use forwarding: When forwarding is invoked for a request, the request is sent to another resource on the server without having to notify the client that the request is handled by a different resource. This process is performed entirely inside the web container, and the client never knows. Unlike redirection, during forwarding, objects can be stored in a request and sent to the next resource for use.
Because the forwarding process takes place entirely on the server and uses no communication with the client, the performance of forwarding is better than redirection.
But if relative paths and other resources are used on the JSP page, the forwarding mechanism will cause problems. Because the browser has no way of knowing that the forwarding occurred, the relative path is only relative to the initial servlet, not the JSP page to which it was forwarded. Using JSP custom tags can solve this problem.
How to implement the servlet single-threaded mode servlet configuration 4. The basic architecture of the servlet public class ServletName extends HttpServlet {
public void doPost (HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
}
public void doGet (HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
}
}
HttpServlet {
public void doPost (HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
}
public void doGet (HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
}
} What is the difference between dynamic INCLUDE and static include in JSP?
Answer: Dynamic INCLUDE implements <jsp: include page = "included.jsp" flush = "true" /> with jsp: include action. It always checks for changes in the included files, and is suitable for including dynamic pages. The parameter static INCLUDE is implemented with include pseudo-code, and it will not check the changes of the included files. It is suitable for including static pages <% @ include file = "included.htm"%>
May let you write a Jdbc and Oracle program and implement data query.
Answer: The procedure is as follows:
package hello.ant;
import java.sql. *;
public class jdbc {
String dbUrl = "jdbc: oracle: thin: @ 127.0.0.1: 1521: orcl";
String theUser = "admin";
String thePw = "manager";
Connection c = null;
Statement conn;
ResultSet rs = null;
public jdbc () {
try {
Class.forName ("oracle.jdbc.driver.OracleDriver"). NewInstance ();
c = DriverManager.getConnection (dbUrl, theUser, thePw);
conn = c.createStatement ();
} catch (Exception e) {
e.printStackTrace ();
}
}
public boolean executeUpdate (String sql) {
try {
conn.executeUpdate (sql);
return true;
} catch (SQLException e) {
e.printStackTrace ();
return false;
}
}
public ResultSet executeQuery (String sql) {
rs = null;
try {
rs = conn.executeQuery (sql);
} catch (SQLException e) {
e.printStackTrace ();
}
return rs;
}
public void close () {
try {
conn.close ();
c.close ();
} catch (Exception e) {
e.printStackTrace ();
}
}
public static void main (String [] args) {
ResultSet rs;
jdbc conn = new jdbc ();
rs = conn.executeQuery ("select * from test");
try {
while (rs.next ()) {
System.out.println (rs.getString ("id"));
System.out.println (rs.getString ("name"));
}
} catch (Exception e) {
e.printStackTrace ();
}
}
} What is the difference between dynamic INCLUDE and static include?
Answer: Dynamic INCLUDE is implemented with the jsp: include action. It always checks for changes in the included files. It is suitable for including dynamic pages. Static INCLUDE can be implemented with the include pseudo-code with parameters. It will not check for changes in the included files , Suitable for including static pages may let you write a Jdbc and Oracle program, and implement data query.
Answer: The procedure is as follows:
package hello.ant;
import java.sql. *;
public class jdbc {
String dbUrl = "jdbc: oracle: thin: @ 127.0.0.1: 1521: orcl";
String theUser = "admin";
String thePw = "manager";
Connection c = null;
Statement conn;
ResultSet rs = null;
public jdbc () {
try {
Class.forName ("oracle.jdbc.driver.OracleDriver"). NewInstance ();
c = DriverManager.getConnection (dbUrl, theUser, thePw);
conn = c.createStatement ();
} catch (Exception e) {
e.printStackTrace ();
}
}
public boolean executeUpdate (String sql) {
try {
conn.executeUpdate (sql);
return true;
} catch (SQLException e) {
e.printStackTrace ();
return false;
}
}
public ResultSet executeQuery (String sql) {
rs = null;
try {
rs = conn.executeQuery (sql);
} catch (SQLException e) {
e.printStackTrace ();
}
return rs;
}
public void close () {
try {
conn.close ();
c.close ();
} catch (Exception e) {
e.printStackTrace ();
}
}
public static void main (String [] args) {
ResultSet rs;
jdbc conn = new jdbc ();
rs = conn.executeQuery ("select * from test");
try {
while (rs.next ()) {
System.out.println (rs.getString ("id"));
System.out.println (rs.getString ("name"));
}
} catch (Exception e) {
e.printStackTrace ();
}
}
}
Tell me how pagination works in a JSP page?
The page needs to save the following parameters:
Total number of rows: Get the total number of rows per page according to the sql statement: Set value Current number of pages: The request parameter page calculates the number of first rows of the current page based on the current number of pages and the number of rows per page, positioning the result set to this row , Take out the number of rows displayed per page for the result set.
Tell me how pagination works in a JSP page?
The page needs to save the following parameters:
Total number of rows: Get the total number of rows per page according to the sql statement: Set value Current number of pages: The request parameter page calculates the number of first rows of the current page based on the current number of pages and the number of rows per page, positioning the result set to this row , Take out the number of rows displayed per page for the result set.
Design Patterns 1. What design patterns are used in development? Where are they used?
A: When people continue to find problems and find solutions to problems in their environment, they find that there are some problems and their solutions that constantly change faces and appear repeatedly, but there are common essences behind these different faces. These common essences Is the pattern. Design patterns are used to describe the core of solutions to these problems.
The factory pattern is specifically responsible for instantiating a large number of classes with a common interface. The factory pattern can dynamically determine which class to instantiate without having to know in advance which class to instantiate each time.
Simple factory pattern or static factory method pattern. The simple factory pattern is a factory object that decides which instance of a product class to create. The simple factory pattern is that a factory class decides which instance of a product class to create based on the parameters passed in.
The simple factory model involves factory roles, abstract product roles, and specific product roles: l Factory-type roles: contain business logic that is closely related to the application. The factory class creates the product object under the direct call of the client. l Abstract product role: The class that holds this role is the parent class of the objects created by the factory method pattern, or the interfaces they share. Specific product role: Any object created by the factory method pattern is an instance of this role.
The advantage is that it allows the client to be relatively independent of the product creation process and does not require modification of the client when a new product is introduced into the system. The disadvantage is that if a new product is added to the system, you need to modify the factory class and add the necessary logic to the factory class.
Factory method mode or polymorphic factory mode. The purpose of the factory method pattern is to define a factory interface for creating product objects, deferring the actual creation to subclasses. In the factory method pattern, the core factory class is no longer responsible for the creation of all products, but the specific creation is left to the subclasses. It is only responsible for giving the interface that a specific factory subclass must implement. This can be used to allow the system to introduce new products without modifying specific plant roles.
The role of the factory method pattern: l Abstract factory role: It does not contain application logic. Any factory class that creates objects in the schema must implement this interface. l Specific factory role: contains logic closely related to the application, and is called by the application to create a product object. l Abstract product role: The supertype of the object created by the factory method pattern, that is, the common parent class or common owned interface of the product object. Specific product role: This role implements the interface declared by the abstract product role.
The singleton pattern ensures that there is only one instance of a class, and it instantiates itself and provides this instance to the entire system.
Features: The singleton class can only have one instance; the singleton class must create its own unique instance; the singleton class must provide this instance to all other objects.
Multi-instance mode Multi-instance classes can have multiple instances, and multi-instance classes must create and manage their own instances and provide their own instances to the outside world.
Can be used in the system for database connection pool, key value cache, etc.
The proxy mode provides a proxy object for an object, and the proxy object controls the reference to the original object.
Roles involved in the proxy model: Abstract theme roles: Declares a common interface between the real theme and the proxy theme, so that the proxy theme role can be used wherever the real theme can be used. Simple factory pattern or static factory method pattern. The simple factory pattern is a factory object that decides which instance of a product class to create. The simple factory pattern is that a factory class decides which instance of a product class to create based on the parameters passed in.
The simple factory model involves factory roles, abstract product roles, and specific product roles: l Factory-type roles: contain business logic that is closely related to the application. The factory class creates the product object under the direct call of the client. l Abstract product role: The class that holds this role is the parent class of the objects created by the factory method pattern, or the interfaces they share. Specific product role: Any object created by the factory method pattern is an instance of this role.
The advantage is that it allows the client to be relatively independent of the product creation process and does not require modification of the client when a new product is introduced into the system. The disadvantage is that if a new product is added to the system, you need to modify the factory class and add the necessary logic to the factory class.
Factory method mode or polymorphic factory mode. The purpose of the factory method pattern is to define a factory interface for creating product objects, deferring the actual creation to subclasses. In the factory method pattern, the core factory class is no longer responsible for the creation of all products, but the specific creation is left to the subclasses. It is only responsible for giving the interface that a specific factory subclass must implement. This can be used to allow the system to introduce new products without modifying specific plant roles.
The role of the factory method pattern: l Abstract factory role: It does not contain application logic. Any factory class that creates objects in the schema must implement this interface. l Specific factory role: contains logic closely related to the application, and is called by the application to create a product object. l Abstract product role: The supertype of the object created by the factory method pattern, that is, the common parent class or common owned interface of the product object. Specific product role: This role implements the interface declared by the abstract product role.
The singleton pattern ensures that there is only one instance of a class, and it instantiates itself and provides this instance to the entire system.
Features: The singleton class can only have one instance; the singleton class must create its own unique instance; the singleton class must provide this instance to all other objects.
Multi-instance mode Multi-instance classes can have multiple instances, and multi-instance classes must create and manage their own instances and provide their own instances to the outside world.
Can be used in the system for database connection pool, key value cache, etc.
The proxy mode provides a proxy object for an object, and the proxy object controls the reference to the original object.
Roles involved in the proxy model: Abstract theme roles: Declares a common interface between the real theme and the proxy theme, so that the proxy theme role can be used wherever the real theme can be used.