1. request.getAttribute() 和 request.getParameter() 有何區別?
??????request.getParameter()?
??????request 是請求,即把需要的參數得到,一般是從上一個頁面用戶提交的數據中得到?
??????Use request.getParameter() when u are planning to fetch values from a html/jsp page, and use requets.getAttribute() when u want to fetch attribute values which????are set using request.setAttribute() IN A SERVLET.
??????Attributes are set programatically. If you set an attribute, then you can get it. This is typically done by a servlet or java POJO that either does some pre-processing and sets some additional attribute values, or one that processes the request, finds errors and therefore sets attributes and returns the request back to the originator. The originator may look for these attributes (for example error messages) and display them. You don't programatically set parameters, only attributes.?
??????session.getAttribute()?
??????session 是用來保持會話的連接
2. JSP中動態INCLUDE與靜態INCLUDE的區別??
????動態INCLUDE用jsp:include動作實現?
???<jsp:include page="included.jsp" flush="true" />它總是會檢查所含文件中的變化,適合用于包含動態頁面,并且可以帶參數?
???靜態INCLUDE用include偽碼實現,定不會檢查所含文件的變化,適用于包含靜態頁面?
???<%@ include file="included.htm" %>
3. float型float f=3.4是否正確?
?
???不正確。精度不準確,應該用強制類型轉換,如下所示:float f=(float)3.4
4. 用JAVA實現一種排序,JAVA類實現序列化的方法(二種)? 如在COLLECTION框架中,實現比較要實現什么樣的接口?
???JAVA類實現序例化的方法是實現java.io.Serializable接口?
???Collection框架中實現比較要實現Comparable 接口和 Comparator 接口
5. 編程:編寫一個截取字符串的函數,輸入為一個字符串和字節數,輸出為按字節截取的字符串。 但是要保證漢字不被截半個,如“我ABC”4,應該截為“我AB”,輸入“我ABC漢DEF”,6,應該輸出為“我ABC”而不是“我ABC+漢的半個”。
代碼如下:
package test;
class SplitString
{
String SplitStr;
int SplitByte;
public SplitString(String str,int bytes)
{
SplitStr=str;
SplitByte=bytes;
System.out.println("The String is:′"+SplitStr+"′SplitBytes="+SplitByte);
}
public void SplitIt()
{
int loopCount;
loopCount=(SplitStr.length()%SplitByte==0)?(SplitStr.length()/SplitByte):(SplitStr.length()/SplitByte+1);
System.out.println("Will Split into "+loopCount);
for (int i=1;i<=loopCount ;i++ )
{
if (i==loopCount){
System.out.println(SplitStr.substring((i-1)*SplitByte,SplitStr.length()));
} else {
System.out.println(SplitStr.substring((i-1)*SplitByte,(i*SplitByte)));
}
}
}
public static void main(String[] args)
{
SplitString ss = new SplitString("test中dd文dsaf中男大3443n中國43中國人
0ewldfls=103",4);
ss.SplitIt();
}
}
6. String s = new String("xyz");創建了幾個String Object??
????兩個
7. sleep() 和 wait() 有什么區別??
???sleep是線程類(Thread)的方法,導致此線程暫停執行指定時間,給執行機會給其他線程,但是監控狀態依然保持,到時后會自動恢復。調用sleep不會釋放對象鎖。wait是Object類的方法,對此對象調用wait方法導致本線程放棄對象鎖,進入等待此對象的等待鎖定池,只有針對此對象發出notify方法(或notifyAll)后本線程才進入對象鎖定池準備獲得對象鎖進入運行狀態?! ?br />
8. 給我一個你最常見到的runtime exception。ArithmeticException, ArrayStoreException, BufferOverflowException, BufferUnderflowException, CannotRedoException, CannotUndoException, ClassCastException, CMMException, ConcurrentModificationException, DOMException, EmptyStackException, IllegalArgumentException, IllegalMonitorStateException, IllegalPathStateException, IllegalStateException, ImagingOpException, IndexOutOfBoundsException, MissingResourceException, NegativeArraySizeException, NoSuchElementException, NullPointerException, ProfileDataException, ProviderException, RasterformatException, SecurityException, SystemException, UndeclaredThrowableException, UnmodifiableSetException, UnsupportedOperationException
9. 兩個對象值相同(x.equals(y) == true),但卻可有不同的hash code,這句話對不對?不對,有相同的hash code。
10. String?s?=?"Hello?world!";
這個語句聲明的是一個指向對象的引用,名為“s”,可以指向類型為String的任何對象,目前指向"Hello?world!"這個String類型的對象。這就是真正發生的事情。我們并沒有聲明一個String對象,我們只是聲明了一個只能指向String對象的引用變量。所以,如果在剛才那句語句后面,如果再運行一句:
String?string?=?s;
我們是聲明了另外一個只能指向String對象的引用,名為string,并沒有第二個對象產生,string還是指向原來那個對象,也就是,和s指向同一個對象。
11. union和union all有什么不同?
UNION
The UNIONcommand is used to select related information from two tables, much like the JOIN command. However, when using the UNIONcommand all selected columns need to be of the same data type.
UNION命令可以用來選擇兩個有關聯的信息,和JOIN命令非常相似。然而當使用UNION命令時得保證所選擇的欄目數據類型相同。
Note: With UNION, only distinct values are selected.
注意:使用UNION,只有不同的值會被選擇出來。
Using the UNION Command (使用UNION 命令 Example 舉例)
List all different employee names in Norway and USA: 列舉在USA和Norway中不同的人員名字:
SELECT E_Name FROM Employees_Norway UNION SELECT E_Name FROM Employees_USA Result
Note: This command cannot be used to list all employees in Norway and USA. In the example above we have two employees with equal names, and only one of them is listed.
UNIONALL
The UNIONALLcommand is equal to the UNION command, except thatUNIONALL selects all values.
?UNIONALL命令等同于UNION命令,但UNIONALL會選擇全部的值
Example舉例 :
List all employees in Norway and USA:
SELECT E_Name FROM Employees_Norway UNIONALL? SELECT E_Name FROM Employees_USA
UNION運算符:
將兩個或更多查詢的結果組合為單個結果集,該結果集包含聯合查詢中的所有查詢的全部行。 這與使用連接組合兩個表中的列不同
使用UNION組合兩個查詢的結果集的兩個基本規則是:
???所有查詢中的列數和列的順序必須相同。
???數據類型必須兼容。
這種多結果的查詢組合為單一結果及在實際的應用的非常方便。但在應用中也有著問題。
12. 兩個table,問查詢結果,主要是考inner join與left join的。
13. How do I prevent the output of my JSP or Servlet pages from being cached by the browser?
???You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser. Just execute the following scriptlet at the beginning of your JSP pages to prevent them from being cached at the browser. You need both the statements to take care of some of the older browser versions.
<%
response.setHeader("Cache-Control","no-store"); //HTTP 1.1
response.setHeader("Pragma\","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
%>
14 . How does JSP handle run-time exceptions?
???You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page. For example:
<%@ page errorPage=\"error.jsp\" %> redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, if you indicate that it is an error-processing page, via the directive: <%@ page isErrorPage=\"true\" %> Throwable object describing the exception may be accessed within the error page via the exception implicit object. Note: You must always use a relative URL as the value for the errorPage attribute.
15 . What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?
Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well. If you anticipate your users to increase in the future, you may be better off implementing explicit synchronization for your shared data. The key however, is to effectively minimize the amount of code that is synchronzied so that you take maximum advantage of multithreading.
Also, note that SingleThreadModel is pretty resource intensive from the server\'s perspective. The most serious issue however is when the number of concurrent requests exhaust the servlet instance pool. In that case, all the unserviced requests are queued until something becomes free - which results in poor performance. Since the usage is non-deterministic, it may not help much even if you did add more memory and increased the size of the instance pool.
16. How can I enable session tracking for JSP pages if the browser has disabled cookies?
We know that session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting. URL rewriting essentially includes the session ID within the link itself as a name/value pair. However, for this to be effective, you need to append the session ID for each and every link that is part of your servlet response. Adding the session ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input. Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie.
Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp, interact with each other. Basically, we create a new session within hello1.jsp and place an object within this session. The user can then traverse to hello2.jsp by clicking on the link present within the page. Within hello2.jsp, we simply extract the object that was earlier placed in the session and display its contents. Notice that we invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve the session object. Try this example first with cookies enabled. Then disable cookie support, restart the brower, and try again. Each time you should see the maintenance of the session across pages. Do note that to get this example to work with cookies disabled at the browser, your JSP engine has to support URL rewriting.
hello1.jsp
<%@ page session=\"true\" %>
<%
Integer num = new Integer(100);
session.putValue("num",num);
String url =response.encodeURL("hello2.jsp");
%>
<a href=\'<%=url%>\'>hello2.jsp</a>
hello2.jsp
<%@ page session="true" %>
<%
Integer i= (Integer )session.getValue("num");
out.println("Num value in session is " + i.intValue());
%>
17. How do I use a scriptlet to initialize a newly instantiated bean?
A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not restricted to using those alone.
The following example shows the “today” property of the Foo bean initialized to the current date when it is instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action.
<jsp:useBean id="foo" class="com.Bar.Foo" >
<jsp:setProperty name="foo" property="today"
value="<%=java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>" / >
<%-- scriptlets calling bean setter methods go here --%>
</jsp:useBean >
18. What are implicit objects? List them?
Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects re listed below
- request
- response
- pageContext
- session
- application
- out
- config
- page
- exception
|
19. Difference between forward and sendRedirect?
When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completly with in the web container. When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completly new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.
20. Explain the life-cycle mehtods in JSP?
THe generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp package. Hte HttpJspPage interface extends the JspPage interface which inturn extends the Servlet interface of the javax.servlet package. the generated servlet class thus implements all the methods of the these three interfaces. The JspPage interface declares only two mehtods - jspInit() and jspDestroy() that must be implemented by all JSP pages regardless of the client-server protocol. However the JSP specification has provided the HttpJspPage interfaec specifically for the JSp pages serving HTTP requests. This interface declares one method _jspService().
The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is called before any other method, and is called only once for a servlet instance.
The _jspservice()- The container calls the _jspservice() for each request, passing it the request and the response objects.
The jspDestroy()- The container calls this when it decides take the instance out of service. It is the last method called n the servlet instance.
21. What are?the tradeoffs with?having indexes ?
1. Faster selects, slower updates,
2. Extra storage space to store indexes, Updates are slower because in addition to updating the table to have to update the index??????
22. What is?"normalization" ??"Denormalization"? why do you sometimes want to denormalize ?
??
- Normalizing data means eliminating redundant information from table and organizing the data so that future changes to the table are easier.
- Denormalization means allowing redundancy in a table. The main benefit of denormalization?is imporved performance with simplified data retrieval and manipulation. This is done by reduction in the number of joins needed for data processing.
23. What types of index data structures can you have ?
??- An index helps to faster search values in tables. The three most commonly used index types are :
??????1. B-Tree :? builds a tree of possible values with a list of row IDs that have the leaf value. Needs a lot of space and is the default index type for most databases.
??????2. Bitmap : string of bits for each possible value of the column. Each bit string has one bit for each row. Nees only few space and is very fast ( however, domain of value cannot be large, e.g SES(M, F); degree(BS, MS, PHD)
??????3. Hash: a hashing algorithm is used to assign a set of characters to represent a text string such as a composite of keys or partial keys, and compresses the underlying data. Takes longer to build and?is supported by relatively few dataases.
24.?What is?" index covering" of a query ?
???
-?Index covering means that "Data can be found only using indexes, without touching the tables"
25.?What is a?SQL view?
- An output of a query can be stroed as a view,?View acts like small table which meets our criterion. View is a precompiled SQL query which is used to select data from one or more tables. A view is like a table but it doesnt physically take any space. View is a good way to present data in a particular format if you use that query quite often. Vie can also be used to restrict users from accessing the tables directly.?
26. What structure can you implement for the database to speed up tables reads ?
- Follow the rules of DB tuning we have to : 1] properly use indexes ( different type of indexes )
???2] properly locate different DB objects across different tablespaces, files and so on/
???3] create a special space(tablespace) to locate some of the data with special datatype/ ( for example CLOB. LOB...)
27. How do you implement one-to-one, one-to-many and many-to-many relationships while designing tables?
?? One-to-One relationship can be implemented as a single table and rarely as two tables with primary and foreign key relationships. One-to-Many relationships are implemented by spliting the data into two tables with primary key and foreign key relationships. Many-to-Many relationships are implemented using a junction table with the keys from both the tables forming the composite primary key of the junction table.
28. What is difference between primary key and unqiue key ?
Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn't allow NULLs, but unique key allows one NULL only.
29. What is maximum size of a row ?
8060 bytes. Dont be suprised with questionlike ' what is the maximum number of columns per table'. Check out SQL server books online for the page titled : 'Maximum Capacity Specifications".
30. ServletContext和PageContext
PageContext:?? PageContext? extends? JspContext? to? provide? useful? context? information? for? when? JSP? technology? is? used? in? a? Servlet? environment??
ServletContext:??? Defines? a? set? of? methods? that? a? servlet? uses? to? communicate? with? its? servlet? container,? for? example,? to? get? the? MIME? type? of? a? file,? dispatch? requests,? or? write? to? a? log? file。?
The? ServletContext? object? is? contained? within? the? ServletConfig? object,? which? the? Web? server? provides? the? servlet? when? the? servlet? is? initialized??
?