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)后本线程才进入对象锁定池准备获得对象锁进入运行状态。
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