只有注册用户登录后才能阅读该文。
阅读全文
posted @
2007-06-14 03:31 Sun River|
编辑 收藏
Part I Java SE
1. tell me some classes in the java collections?
2. hashmap is interface or class?
3. what is reflection? how do you use it? give an situation.
Part II JavaScript
1. How to create a new browser?
Part III XML and SOAP
1. XSL for what?
2. Caster for what?
3. JDOM explain?
4. JAXB?
5. explain soap?
6. what kind class in soap?
7.
Part IV JDBC and transaction and weblogic setup for db?
1. Oracle stored procedure?
2. Prefined statement?
3.
Part V Struts
Part VI Java EE
posted @
2007-06-02 01:03 Sun River|
编辑 收藏
Yet only a handful of those protocols are commonly used, chief amongst them is HTTP. HTTP is particularly attractive because it is accepted by corporate firewalls. Consequently, HTTP has outgrown its origins in Web browsing and has been adopted by many applications. For example, the latest XML protocols, such as SOAP, are also build on HTTP.
Java Support
Java supports HTTP through two APIs. The servlet API (and JSP) covers server-side programming while the java.net package offers client-side support through HttpURLConnection.
While I have had few problems with the servlet API, I have found that HttpURLConnection requires some work to interface with firewalls. All the services you need are available but the documentation is sketchy at best. Here are some of the problems I have encountered... and the solutions.
Typically, a client on a corporate network has no direct connection to the Internet. Access goes through proxy servers that monitor the traffic and enforce security rules.
The Basics
In the java.net API, proxies are supported through two system properties: http.proxyHost and http.proxyPort. They must be set to the proxy server and port respectively. The following code fragment illustrates it:
String url = http://www.marchal.com/,
proxy = "proxy.mydomain.com",
port = "8080";
URL server = new URL(url);
Properties systemProperties = System.getProperties();
systemProperties.setProperty("http.proxyHost",proxy);
systemProperties.setProperty("http.proxyPort",port);
HttpURLConnection connection = (HttpURLConnection)server.openConnection();
connection.connect();
InputStream in = connection.getInputStream();
readResponse(in);
Of course, you would need to use the proxy and port values suitable for your network. You can most likely find them in the configuration of your browser. If unsure, ask your system administrator.
Using Authentication
Increasingly, companies require employees to log in to the proxy before accessing the Internet. Login is used to better monitor Internet usage; for example, to monitor what sites are visited.
HttpURLConnection supports proxy authentication through the Authenticator class. To enable authentication, your application subclasses Authenticator and defines the getPasswordAuthentication() method. A minimalist implementation is as follows:
public class SimpleAuthenticator extends Authenticator
{
private String username, password;
public SimpleAuthenticator(String username,String password)
{
this.username = username;
this.password = password;
}
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(
username,password.toCharArray();
}
}
Next, it must register the authenticator through Authenticator.setDefault(). If we adapt the previous code sample to use Authenticator, it looks like this:
String url = "http://www.marchal.com/",
proxy = "proxy.mydomain.com",
port = "8080",
username = "usr",
password = "pwd";
Authenticator.setDefault(new SimpleAuthenticator(username,password));
URL server = new URL(url);
Properties systemProperties = System.getProperties();
systemProperties.setProperty("http.proxyHost",proxy);
systemProperties.setProperty("http.proxyPort",port);
HttpURLConnection connection = ( HttpURLConnection)server.openConnection();
connection.connect();
InputStream in = connection.getInputStream();
readResponse(in);
A More Serious Issue
So far, I have covered the most common situations where HttpURLConnection works properly. However, I have encountered a few networks where HttpURLConnection is not usable.
It appears that the problem is linked to a faulty configuration of the DNS server. For some reason, HttpURLConnection always attempts to resolve the host name against the DNS server. Normally, it fails gracefully and the connection goes is rerouted through the proxy server. A few DNS servers return an inappropriate answer that results in a UnknownHostException.
There's an interesting theoretical debate as to whether the DNS server behaviour is acceptable. Although I am no expert on the topic, it would appear it is not. However, as a developer, you seldom have the option to reconfigure the DNS server, so you have to find a workaround.
My solution is to roll out my own implementation of the HTTP protocol. In its simplest form, a GET request looks like the following listing:
String url = "http://www.marchal.com/",
proxy = "proxy.mydomain.com",
port = "8080",
authentication = "usr:pwd";
URL server = new URL(url);
Socket socket = new Socket(proxy,port);
Writer writer = new OutputStreamWriter(socket.getOutputStream(), "US-ASCII");
writer.write("GET " + server.toExternalForm() + " HTTP/1.0\r\n");
writer.write("Host: " + server.getHost() + "\r\n");
writer.write("Proxy-Authorization: Basic "
+ new sun.misc.BASE64Encoder().encode(authentication.getBytes())+ "\r\n\r\n");
writer.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(
socket.getInputStream(),"US-ASCII"));
String line = reader.readLine();
if(line != null && line.startsWith("HTTP/"))
{
int sp = line.indexOf(' ');
String status = line.substring(sp + 1,sp + 4);
if(status.equals("200"))
{
while(line.length() != 0)
line = reader.readLine();
readResponse(reader);
}
else throw new FileNotFoundException("Host reports error " + status);
}
else
throw new IOException("Bad protocol");
reader.close();
writer.close();
socket.close();
Notice that the proxy username and password are given as username:password and are later encoded in base 64.
Conclusion
HTTP is an interesting protocol because it is supported by all corporate firewalls. The Java developer needs to pay special attention to proxies and other authentication issues, though.
posted @
2007-03-06 10:52 Sun River|
编辑 收藏
(1)假设在helloapp应用中有一个hello.jsp,它的文件路径如下: %CATALINA_HOME%/webapps/helloapp/hello/hello.jsp 那么在浏览器端访问hello.jsp的URL是什么? (单选) 选项: (A) http://localhost:8080/hello.jsp (B) http://localhost:8080/helloapp/hello.jsp (C) http://localhost:8080/helloapp/hello/hello.jsp
(2)假设在helloapp应用中有一个HelloServlet类,它位于org.javathinker包下,那么这个类的class文件应该放
在什么目录下? (单选) 选项: (A) helloapp/HelloServlet.class (B) helloapp/WEB-INF/HelloServlet.class (C) helloapp/WEB-INF/classes/HelloServlet.class (D) helloapp/WEB-INF/classes/org/javathinker/HelloServlet.class
|
|
(3)假设在helloapp应用中有一个HelloServlet类,它在web.xml文件中的配置如下:
<servlet>
<servlet-name> HelloServlet </servlet-name>
<servlet-class>org.javathinker.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> HelloServlet </servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
那么在浏览器端访问HelloServlet的URL是什么? (单选)
选项:
(A) http://localhost:8080/HelloServlet
(B) http://localhost:8080/helloapp/HelloServlet
(C) http://localhost:8080/helloapp/org/javathinker/hello
(D) http://localhost:8080/helloapp/hello
(4)客户请求访问HTML页面与访问Servlet有什么异同?(多选)
选项:
(A)相同:都使用HTTP协议
(B)区别:前者Web服务器直接返回HTML页面,后者Web服务器调用Servlet的方法,由Servlet动态生成HTML页面
(C)相同:前者Web服务器直接返回HTML页面,后者Web服务器直接返回Servlet的源代码。
(D)区别:后者需要在web.xml中配置URL路径。
(E)区别:前者使用HTTP协议,后者使用RMI协议。
(5)HttpServletRequest对象是由谁创建的?(单选)
选项:
(A)由Servlet容器负责创建,对于每个HTTP请求, Servlet容器都会创建一个HttpServletRequest对象
(B)由JavaWeb应用的Servlet或JSP组件负责创建,当Servlet或JSP组件响应HTTP请求时,先创建
HttpServletRequest对象
(6)从HTTP请求中,获得请求参数,应该调用哪个方法? (单选)
选项:
(A)调用HttpServletRequest对象的getAttribute()方法
(B)调用ServletContext对象的getAttribute()方法
(C)调用HttpServletRequest对象的getParameter()方法
(7)ServletContext对象是由谁创建的?(单选)
选项:
(A)由Servlet容器负责创建,对于每个HTTP请求, Servlet容器都会创建一个ServletContext对象
(B)由JavaWeb应用本身负责为自己创建一个ServletContext对象
(C)由Servlet容器负责创建,对于每个JavaWeb应用,在启动时,Servlet容器都会创建一个ServletContext对象
(8)jspForward1.jsp要把请求转发给jspForward2.jsp,应该在jspForward1.jsp中如何实现? (单选)
选项:
(A) <a href=“jspForward2.jsp”>jspForward2.jsp </a>
(B) <jsp:forward page=“jspForward2.jsp”>
(9)当浏览器第二次访问以下JSP网页时的输出结果是什么?(单选)
<!% int a=0; %>
<%
int b=0;
a++;
b++;
%>
a:<%= a %> <br>
b:<%= b %>
选项:
(A) a=0 b=0
(B) a=1 b=1
(c) a=2 b=1
(10)下面哪个说法是正确的? (单选)
选项:
(A) 对于每个要求访问maillogin.jsp的HTTP请求,Servlet容器都会创建一个HttpSession对象
(B)每个HttpSession对象都有惟一的ID。
(C)JavaWeb应用程序必须负责为HttpSession分配惟一的ID
(11)如果不希望JSP网页支持Session,应该如何办? (单选)
选项:
(A) 调用HttpSession的invalidate()方法
(B) <%@ page session= “false\">
(12)在标签处理类中,如何访问session范围内的共享数据? (多选)
选项:
(A)在TagSupport类中定义了session成员变量,直接调用它的getAttribute()方法即可。
(B)在标签处理类TagSupport类中定义了pageContext成员变量,先通过它的getSession()方法获得当前的
HttpSession对象,再调用HttpSession对象的getAttribute()方法。
(C)pageContext.getAttribute(“attributename”,PageContext.SESSION_SCOPE)
(13)在下面的选项中,哪些是TagSupport类的doStartTag()方法的有效返回值? (多选)
选项:
(A) Tag.SKIP_BODY
(B) Tag.SKIY_PAGE
(C) Tag.EVAL_BODY_INCLUDE
(D) Tag.EVAL_PAGE
(14)以下代码能否编译通过,假如能编译通过,运行时得到什么打印结果?(单选)
request.setAttribute(\"count\",new Integer(0));
Integer count = request.getAttribute(\"count\");
选项:
A)不能编译通过 B)能编译通过,并正常运行
C) 编译通过,但运行时抛出ClassCastException
》答案:
(1)C (2)D (3)D (4)A,B,D (5)A (6)C (7)C (8)B (9)C (10)B
(11)B (12)B,C (13)A,C (14)A
判断题:(其它试题请下载)
1 . Java 程序里 , 创建新的类对象用关键字 new ,回收无用的类对象使用关键字 free 。
2 .对象可以赋值,只要使用赋值号(等号)即可,相当于生成了一个各属性与赋值对象相同的新对象。
3 .有的类定义时可以不定义构造函数,所以构造函数不是必需的。
4 .类及其属性、方法可以同时有一个以上的修饰符来修饰。
5 . Java 的屏幕坐标是以像素为单位,容器的左下角被确定为坐标的起点
6 .抽象方法必须在抽象类中,所以抽象类中的方法都必须是抽象方法。
7 . Final 类中的属性和方法都必须被 final 修饰符修饰。
8 .最终类不能派生子类,最终方法不能被覆盖。
9 .子类要调用父类的方法,必须使用 super 关键字。
10 .一个 Java 类可以有多个父类。
11 .如果 p 是父类 Parent 的对象,而 c 是子类 Child 的对象,则语句 c = p 是正确的。
12 .一个类如果实现了某个接口,那么它必须重载该接口中的所有方法。
13 .当一个方法在运行过程中产生一个异常,则这个方法会终止,但是整个程序不一定终止运行。
14 .接口是特殊的类,所以接口也可以继承,子接口将继承父接口的所有常量和抽象方法。
15 .用“ + ”可以实现字符串的拼接,用 - 可以从一个字符串中去除一个字符子串。
16 .使用方法 length( ) 可以获得字符串或数组的长度。
17 .设 String 对象 s=”Hello ” ,运行语句 System.out.println(s.concat(“World!”)); 后 String 对象 s 的内容为 ”Hello world!” ,所以语句输出为
Hello world!
18 .创建 Vector 对象时构造函数给定的是其中可以包容的元素个数,使用中应注意不能超越这个数值。
19 .所有的鼠标事件都由 MouseListener 监听接口的监听者来处理。
20 .一个容器中可以混合使用多种布局策略。
21 . Java 中,并非每个事件类都只对应一个事件。
22 .一个线程对象的具体操作是由 run() 方法的内容确定的,但是 Thread 类的 run() 方法是空的 , 其中没有内容 ; 所以用户程序要么派生一个 Thread 的子类并在子类里重新定义 run() 方法 , 要么使一个类实现 Runnable 接口并书写其中 run() 方法的方法体。
23 . Java 的源代码中定义几个类,编译结果就生成几个以 .class 为后缀的字节码文件。
24 . Java Applet 是由独立的解释器程序来运行的。
25 . Java Applet 只能在图形界面下工作。
26 . Java 的字符类型采用的是 ASCII 编码。
27 . Java 的各种数据类型占用固定长度,与具体的软硬件平台环境无关
28 . Applet 是一种特殊的 Panel ,它是 Java Applet 程序的最外层容器。
29 .子类的域和方法的数目一定大于等于父类的域和方法的数目。
30 . System 类不能实例化,即不能创建 System 类的对象。
31 .用户自定义的图形界面元素也可以响应用户的动作,具有交互功能
32 . Java 中数组的元素可以是简单数据类型的量,也可以是某一类的对象。
33 . Vector 类中的对象不能是简单数据类型。
34 . Java 中的 String 类的对象既可以是字符串常量,也可以是字符串变量。
35 .容器是用来组织其他界面成分和元素的单元,它不能嵌套其他容器。
posted @
2007-02-22 11:59 Sun River|
编辑 收藏
-
How EJB Invocation happens? - Retrieve Home Object reference from Naming Service via JNDI. Return Home Object reference to the client. Create me a new EJB Object through Home Object interface. Create EJB Object from the Ejb Object. Return EJB Object reference to the client. Invoke business method using EJB Object reference. Delegate request to Bean (Enterprise Bean).
-
Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a value in the HttpSession from inside an EJB? - You can pass the HttpSession as parameter to an EJB method, only if all objects in session are serializable.This has to be consider as passed-by-value, that means that it’s read-only in the EJB. If anything is altered from inside the EJB, it won’t be reflected back to the HttpSession of the Servlet Container.The pass-by-reference can be used between EJBs Remote Interfaces, as they are remote references. While it is possible to pass an HttpSession as a parameter to an EJB object, it is considered to be bad practice in terms of object-oriented design. This is because you are creating an unnecessary coupling between back-end objects (EJBs) and front-end objects (HttpSession). Create a higher-level of abstraction for your EJBs API. Rather than passing the whole, fat, HttpSession (which carries with it a bunch of http semantics), create a class that acts as a value object (or structure) that holds all the data you need to pass back and forth between front-end/back-end. Consider the case where your EJB needs to support a non HTTP-based client. This higher level of abstraction will be flexible enough to support it.
-
The EJB container implements the EJBHome and EJBObject classes. For every request from a unique client, does the container create a separate instance of the generated EJBHome and EJBObject classes? - The EJB container maintains an instance pool. The container uses these instances for the EJB Home reference irrespective of the client request. while refering the EJB Object classes the container creates a separate instance for each client request. The instance pool maintenance is up to the implementation of the container. If the container provides one, it is available otherwise it is not mandatory for the provider to implement it. Having said that, yes most of the container providers implement the pooling functionality to increase the performance of the application server. The way it is implemented is, again, up to the implementer.
-
Can the primary key in the entity bean be a Java primitive type such as int? - The primary key can’t be a primitive type. Use the primitive wrapper classes, instead. For example, you can use java.lang.Integer as the primary key class, but not int (it has to be a class, not a primitive).
-
Can you control when passivation occurs? - The developer, according to the specification, cannot directly control when passivation occurs. Although for Stateful Session Beans, the container cannot passivate an instance that is inside a transaction. So using transactions can be a a strategy to control passivation. The ejbPassivate() method is called during passivation, so the developer has control over what to do during this exercise and can implement the require optimized logic. Some EJB containers, such as BEA WebLogic, provide the ability to tune the container to minimize passivation calls. Taken from the WebLogic 6.0 DTD -”The passivation-strategy can be either “default” or “transaction”. With the default setting the container will attempt to keep a working set of beans in the cache. With the “transaction” setting, the container will passivate the bean after every transaction (or method call for a non-transactional invocation).
-
What is the advantage of using Entity bean for database operations, over directly using JDBC API to do database operations? When would I use one over the other? - Entity Beans actually represents the data in a database. It is not that Entity Beans replaces JDBC API. There are two types of Entity Beans Container Managed and Bean Mananged. In Container Managed Entity Bean - Whenever the instance of the bean is created the container automatically retrieves the data from the DB/Persistance storage and assigns to the object variables in bean for user to manipulate or use them. For this the developer needs to map the fields in the database to the variables in deployment descriptor files (which varies for each vendor). In the Bean Managed Entity Bean - The developer has to specifically make connection, retrive values, assign them to the objects in the ejbLoad() which will be called by the container when it instatiates a bean object. Similarly in the ejbStore() the container saves the object values back the the persistance storage. ejbLoad and ejbStore are callback methods and can be only invoked by the container. Apart from this, when you use Entity beans you dont need to worry about database transaction handling, database connection pooling etc. which are taken care by the ejb container.
-
What is EJB QL? - EJB QL is a Query Language provided for navigation across a network of enterprise beans and dependent objects defined by means of container managed persistence. EJB QL is introduced in the EJB 2.0 specification. The EJB QL query language defines finder methods for entity beans with container managed persistenceand is portable across containers and persistence managers. EJB QL is used for queries of two types of finder methods: Finder methods that are defined in the home interface of an entity bean and which return entity objects. Select methods, which are not exposed to the client, but which are used by the Bean Provider to select persistent values that are maintained by the Persistence Manager or to select entity objects that are related to the entity bean on which the query is defined.
-
Brief description about local interfaces? - EEJB was originally designed around remote invocation using the Java Remote Method Invocation (RMI) mechanism, and later extended to support to standard CORBA transport for these calls using RMI/IIOP. This design allowed for maximum flexibility in developing applications without consideration for the deployment scenario, and was a strong feature in support of a goal of component reuse in J2EE. Many developers are using EJBs locally, that is, some or all of their EJB calls are between beans in a single container. With this feedback in mind, the EJB 2.0 expert group has created a local interface mechanism. The local interface may be defined for a bean during development, to allow streamlined calls to the bean if a caller is in the same container. This does not involve the overhead involved with RMI like marshalling etc. This facility will thus improve the performance of applications in which co-location is planned. Local interfaces also provide the foundation for container-managed relationships among entity beans with container-managed persistence.
-
What are the special design care that must be taken when you work with local interfaces? - It is important to understand that the calling semantics of local interfaces are different from those of remote interfaces. For example, remote interfaces pass parameters using call-by-value semantics, while local interfaces use call-by-reference. This means that in order to use local interfaces safely, application developers need to carefully consider potential deployment scenarios up front, then decide which interfaces can be local and which remote, and finally, develop the application code with these choices in mind. While EJB 2.0 local interfaces are extremely useful in some situations, the long-term costs of these choices, especially when changing requirements and component reuse are taken into account, need to be factored into the design decision.
-
What happens if remove( ) is never invoked on a session bean? - In case of a stateless session bean it may not matter if we call or not as in both cases nothing is done. The number of beans in cache is managed by the container. In case of stateful session bean, the bean may be kept in cache till either the session times out, in which case the bean is removed or when there is a requirement for memory in which case the data is cached and the bean is sent to free pool.
-
What is the difference between Message Driven Beans and Stateless Session beans? - In several ways, the dynamic creation and allocation of message-driven bean instances mimics the behavior of stateless session EJB instances, which exist only for the duration of a particular method call. However, message-driven beans are different from stateless session EJBs (and other types of EJBs) in several significant ways: Message-driven beans process multiple JMS messages asynchronously, rather than processing a serialized sequence of method calls. Message-driven beans have no home or remote interface, and therefore cannot be directly accessed by internal or external clients. Clients interact with message-driven beans only indirectly, by sending a message to a JMS Queue or Topic. Only the container directly interacts with a message-driven bean by creating bean instances and passing JMS messages to those instances as necessary. The Container maintains the entire lifecycle of a message-driven bean; instances cannot be created or removed as a result of client requests or other API calls.
-
How can I call one EJB from inside of another EJB? - EJBs can be clients of other EJBs. It just works. Use JNDI to locate the Home Interface of the other bean, then acquire an instance reference, and so forth.
-
What is an EJB Context? - EJBContext is an interface that is implemented by the container, and it is also a part of the bean-container contract. Entity beans use a subclass of EJBContext called EntityContext. Session beans use a subclass called SessionContext. These EJBContext objects provide the bean class with information about its container, the client using the bean and the bean itself. They also provide other functions. See the API docs and the spec for more details.
posted @
2006-12-18 19:28 Sun River|
编辑 收藏
-- Facade: Provide a unified interface to a set of interfaces in a subsystem, it defines a higher-level interface that makes the subsystem easier to use.
posted @
2006-12-15 19:33 Sun River|
编辑 收藏
Question:
How you will handle exceptions in Struts?
Answer: In Struts you can handle the exceptions in two ways:
a) Declarative Exception Handling: You can either define global exception handling tags in your struts-config.xml or define the exception handling tags within <action>..</action> tag.
Example:
<exception
key="database.error.duplicate"
path="/UserExists.jsp"
type="mybank.account.DuplicateUserException"/>
b) Programmatic Exception Handling: Here you can use try{}catch{} block to handle the exception.
Question:Explain Struts navigation flow?
Struts Navigation flow.
1) A request is made from previously displayed view.
2) The request reaches the ActionServlet which acts as the controller .The ActionServlet Looksup the requested URI in an XML file (Struts-Config.xml) and determines the name of the Action class that has to perform the requested business logic.
3)The Action Class performs its logic on the Model Components associated with the Application.
4) Once The Action has been completed its processing it returns the control to the Action Servlet.As part of its return the Action Class provides a key to determine where the results should be forwarded for presentation.
5)The request is complete when the Action Servlet responds by forwarding the request to the view, and this view represents the result of the action.
Question: What is the purpose of tiles-def.xml file, resourcebundle.properties file, validation.xml file?
1. tiles-def.xml
tiles-def.xml is used as a configuration file for an appliction during tiles development. You can define the layout / header / footer / body content for your View.
Eg:
<tiles-definitions>
<definition name="siteLayoutDef" path="/layout/thbiSiteLayout.jsp">
<put name="title" value="Title of the page" />
<put name="header" value="/include/thbiheader.jsp" />
<put name="footer" value="/include/thbifooter.jsp" />
<put name="content" type="string">
Content goes here
</put>
</definition>
</tiles-definitions>
<tiles-definitions>
<definition name="userlogin" extends="siteLayoutDef">
<put name="content" value="/dir/login.jsp" />
</definition>
</tiles-definitions>
2. validation.xml
The validation.xml file is used to declare sets of validations that should be applied to Form Beans.
Each Form Bean you want to validate has its own definition in this file. Inside that definition, you specify the validations you want to apply to the Form Bean's fields.
Eg:
<form-validation>
<formset>
<form name="logonForm">
<field property="username"
depends="required">
<arg0 key=" prompt.username"/>
</field>
<field property="password"
depends="required">
<arg0 key="prompt.password"/>
</field>
</form>
</formset>
</form-validation>
3. Resourcebundle.properties
Instead of having hard-coded error messages in the framework, Struts Validator allows you to specify a key to a message in the ApplicationResources.properties (or resourcebundle.properties) file that should be returned if a validation fails.
Eg:
In ApplicationResources.properties
errors.registrationForm.name={0} Is an invalid name.
In the registrationForm.jsp
<html:messages id="messages" property="name">
<font color="red">
<bean:write name="messages" />
</html:messages>
Output(in red color) : abc Is an invalid name
=================
1. Purpose of tiles-def.xml file is used to in the design face of the webpage. For example in the webpage "top or bottom or left is
fixed" center might be dynamically chaged.
It is used for the easy design of the web sites. Reusability
2. resourcebundle.properties file is used for lot of purpose. One of its purpose is internationalization. We can make our page to view on any language. It is independent of it. Just based on the browser setting it selects the language and it displayed as you mentioned in the resourcebundle.properties file.
3. Validation rule.xml is used to put all the validation of the front-end in the validationrule.xml. So it verifies. If the same rule is applied in more than one page. No need to write the code once again in each page. Use validation to chek the errors in forms.
============================
tiles-def.xml - is required if your application incorporates the tiles framework in the "View" part of MVC. Generally we used to have a traditional JSP's (Which contgains HTML & java scriplets) are used in view. But Tiles is an advanced (mode or less ) implementation of frames used in HTML. We used to define the frames in HTML to seperate the header html, footer html, menu or left tree and body.html to reuse the contents. Hence in the same way, Tiles are defined to reuse the jsp's in struts like architectures, and we can define the jsp's which all are to be display at runtime, by providing the jsp names at runtime. To incorporate this we need tile-def.xml and the Class generally which extends RequestProcessor should extend TilesRequestProcessor.
resourcebundle.properties — It is to incorporate i18n (internationalization) in View part of MVC.
validation.xml - This file is responsible for business validations carried at server side before processing the request actually. It reduces the complexity in writing _JavaScript validations, and in this way, we can hide the validations from the user, in View of MVC.
Question: What we will define in Struts-config.xml file. And explain their purpose?
In struts-config.xml we define Date Sources / Form Beans / Global Exceptions / Global Forwards / Action Mappings / Message Resources / Plug-ins
Example :
<!– Date Sources –>
<data-sources>
<data-source autoCommit="false" description="First Database Config" driverClass=" org.gjt.mm.mysql.Driver" maxCount="4" minCount="2" password="admin" url="jdbc: mysql://localhost/ARTICLEDB" user="admin">
</<data-sources>
<!– Form Beans –>
<form-beans>
<form-bean name="registrationForm" type="com.aaa.merchant.wsp.ActionForms.RegistrationForm">
</form-bean>
<!– Global Exceptions –>
<global-exceptions>
<exception key="some.key" type="java.io.IOException" handler="com.yourcorp.ExceptionHandler"/>
</global-exceptions>
<!– A global-forward is retrieved by the ActionMapping findForward method. When the findForward method can't find a locally defined forward with the specified name, it searches the global-forwards available and return the one it finds.–>
<global-forwards>
<forward name="logoff" path="/logoff"/>
<forward name="logon" path="/logon.jsp"/>
</global-forwards>
<!– Actionn Mappings –>
<action-mappings>
<action path="/validateRegistration" type="com.dd.merchant.wsp.Actions.ValidateRegistration" validate="true" input="" name="registrationForm">
<forward name="success" path="/logon.jsp">
</forward>
</action>
</action-mappings>
<!– Message Resources –>
<message-resources parameter="wsppaymentsweb.resources.ApplicationResources"/>
<!– Plug-ins –>
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
</plug-in>
===============================
Struts-Config.xml is one of the most important part of any web application based on Sturts. This file is responsible for instructing the Struts what forms are available, what actions are available, and also allows a number of plug-in models to be added to the base Struts package. It can contain Data Source Configuration,Form Bean Definitions, Global Forward Definitions,Action Mapping Definitions, Message Resources Definitions etc.
The most important are Form Bean Definitions, Global Forward Definitions,Action Mapping Definitions.
The <form-bean/> is configured using only two attributes, name and type and doesn't contain any body. The form-bean tag is used to describe an instance of a particular Form Bean that will be later bound to action.
The attribute name specifies the name of the form bean, which is a unique identifier to this form bean & the attribute type specifies the absolute path of the class file.
<global-forwards/>: It is also configured using only two attributes, name and path and there is also an optional attribute redirect. The <forward/> specifies the mapping of a logical name to a context-relative URI path. In the above sample xml file we can see, one of the <forward/> is specified with the name as failure and its corresponding path as index.jsp. That means whenever the logical name failure is encountered the action will be forwarded to the index.jsp page.
The optional attribute redirect is set to false by default. When it is set to true it causes the ActionServlet to use HttpSevletResponse.sendRedirect() method.
<action-mappings/>: The action mapping mainly defines the mapping between the logical Action name and the physical action class. Now lets have an understanding about its attributes.
· The attribute path must be compulsorily defined and it should start with a '/' character. It specifies the context relative path of the submitted request.
· The type attribute specifies the absolute path of the fully qualified class name of the Action class.
· The attribute name must be the same as that of the form bean name for which you want to associate the action.
· The attribute scope specifies the scope of the particular form bean which is an optional one and its default value is session.
· The next attribute validate is also an optional one which by default is set to true. When set to true, the validate() method in the form bean is called which gets associated with a particular Action.
· The next attribute, input is also optional. Whenever a validation error is encountered then the control returns to the path specified in the input attribute.
<controller/>: The <controller/> can be used to modify the default behaviour of the Struts Controller i.e, we can define a RequestProcessor.
===============================
In struts-config.xml, we define all the global-forwards, action mappings, view mappings, form-bean mappings, controller mapping and finally message-resources declaration if any.
Why we need to declare means, the Controller servelet defined in struts internally looks for this xml file for its proceddings. In real scenario, that the controller servlet inplemented internally is nothing but a slave to this struts-config.xml. The information provided in this file is nothing but like the intelligence to the controller servlet to say - what to do in which situation ?
So, Controller servlet, needs this file to proceede/ run the application.
What is DispatchAction?
DispatchAction is specialized child of Struts Action class. It combines or group the methods that can further access the bussiness logic at a single place. The method can be anyone from CRUD [Create,Retrieve,Update or Delete] or it can be security check one like autheniticate user etc.
This class apart from having thread-safe execute method also can have user-defined methods.
In struts-config.xml files following changes are required for Dispatch action to work:
<action-mappings>
<action path="/login"
type ="com…..LoginAction"
name ="loginForm"
parameter ="task"
scope = "request"
validate = "false"
input = "/index.jsp">
<forward name="success" path="/jsp/common/index.jsp"/>
<forward name="loginagain" path="/index.jsp"/>
</action>
</action-mappings>
If above is your struts-config.xml file structure and LoginAction extends DispatchAction instead of normal Action class. And assuming [keep assuming] your LoginAction class have method named authenticateUser, then in your login.jsp add any hidden parameter called task with value as your method name and on submit of that page following will be the url:
http://localhost:8080/yourproject/jsp/login.jsp?login.do&task=authenticateUser
Thus if we try to combine the last part of this puzzle we get the climax at struts-config.xml file's action-mapping tag described above. The parameter property of <action> tag have the task as it's value pointing to task variable in the request having it's value as authenticateUser hence the framework search in the LoginAction a method called authenticateUser through reflection and forwards the execution flow to it. This is all folks, the briallancy of Struts framework. Note DispatchAction class is included in 1.1 version.
How to call ejb from Struts?
We can call EJB from struts by using the service locator design patteren or by Using initial context with create home object and getting return remote referenc object.
What is the difference between ActionErrors and ActionMessages?
There is no differnece between these two classes.All the behavior of ActionErrors was copied into ActionMessages and vice versa. This was done in the attempt to clearly signal that these classes can be used to pass any kind of messages from the controller to the view — where as errors being only one kind of message.
The difference between saveErrors(…) and saveMessages(…) is simply the attribute name under which the ActionMessages object is stored, providing two convenient default locations for storing controller messages for use by the view. If you look more closely at the html:errors and html:messages tags, you can actually use them to get an ActionMessages object from any arbitrary attribute name in any scope.
What are the various Struts tag libraries?
The Struts distribution includes four tag libraries for the JSP framework (in struts-config.xml) :
* Bean tag library [ struts-bean.tld ] : Contains tags for accessing JavaBeans and their properties. Developers can also define new beans and set properties
* HTML tag library [ struts-html.tld ] : Contains tags to output standard HTML, including forms, textfields, checkboxes, radio buttons
* Logic tag library [ struts-logic.tld ] : Contains tags for generating conditional output, iteration capabilities and flow management
* Tiles or Template tag library [ struts-tiles.tld / struts-template.tld ] : For tiles implementation
* Nested tag library [ struts-nested.tld ] : allows the use of nested beans.
The libraries are designed to:
* Facilitate the separation of presentation and business logic.
* Dynamically generate Web pages.
* Implement the flow of control to and from the ActionServlet.
How you will handle errors and exceptions using Struts?
Struts exception handling can be done by two ways:
1. Declarative (using struts features via struts-config.xml)
<global-exceptions>
<exception
type="hansen.playground.MyException2"
key ="errors.exception2"
path="/error.jsp"/>
</global-exceptions>
This makes coding in the Action class very simple
Since the execute method declares throws Exception we don't need a try-catch block.
Struts saves the exception using one of its global constants. You may use the field G lobals.EXCEPTION_KEY to retrieve it from the request object.
2. Programmatic (using the usual try-catch exception handling in Action Class)
===============
We can Handle the errors by holding them into ActionError or ActionErrors classes defined by struts Framework. The other way around is by using the methods say saveErrors()….etc defined in Action class and can throw the error messages.
=================
Struts handles errors by providing the ActionErrors class which is
extended from org.apache.struts.action…
To install your customized exception handler, the first step is to
create a class that extends org.apache.struts.action.ExceptionHandler. There are
two methods that you can override, execute() and storeException().
For handling exceptions you have to mention in <global-exceptions> tag
of struts-config.xml which accepts attributes like exception type,key and
path.
How you will save the data across different pages for a particular client request using Struts?
One simple and general way is by using session Object.
In specific, we can pass this by using request Object as well.
======================================
Create an appropriate instance of ActionForm that is form bean and store that form bean in session scope. So that it is available to all the pages that for a part of the request.
request.getSession()
session.setAttribute()
What is Action Class? What are the methods in Action class?
An Action class is some thing like an adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed to process this request.
The controller (RequestProcessor) will select an appropriate Action for each request, create an instance (if necessary), and call the execute method. Struts Action class is a unit of logic. It is where a call to business function is made. In short the Action class acts like a bridge between client side(user action) and business operation(on server.
Some of the impotant methods of Action class are, execute()
generateToken() resetToken() getServlet()
Explain about token feature in Struts?
Use the Action Token methods to prevent duplicate submits:
There are methods built into the Struts action to generate one-use tokens. A token is placed in the session when a form is populated and also into the HTML form as a hidden property. When the form is returned, the token is validated. If validation fails, then the form has already been submitted, and the user can be apprised.
saveToken(request)
on the return trip,
isTokenValid(request)
resetToken(request)
What is the difference between ActionForm and DynaActionForm
# The DynaActionForm bloats up the Struts config file with the xml based definition. This gets annoying as the Struts Config file grow larger.
# The DynaActionForm is not strongly typed as the ActionForm. This means there is no compile time checking for the form fields. Detecting them at runtime is painful and makes you go through redeployment.
# ActionForm can be cleanly organized in packages as against the flat organization in the Struts Config file.
# ActionForm were designed to act as a Firewall between HTTP and the Action classes, i.e. isolate and encapsulate the HTTP request parameters from direct use in Actions. With DynaActionForm, the property access is no different than using request.getParameter( .. ).
# DynaActionForm construction at runtime requires a lot of Java Reflection (Introspection) machinery that can be avoided.
# Time savings from DynaActionForm is insignificant. It doesn t take long for today s IDEs to generate getters and setters for the ActionForm attributes. (Let us say that you made a silly typo in accessing the DynaActionForm properties in the Action instance. It takes less time to generate the getters and setters in the IDE than fixing your Action code and redeploying your web application)
posted @
2006-12-04 15:46 Sun River|
编辑 收藏
Tech Tips Quiz
Over the years, the Enterprise Java Technologies Tech Tips have covered a wide variety of enterprise Java technology topics. Here's a short quiz that tests your knowledge of some topics covered in past Tech Tips. You can find the answers at the end of the quiz.
1.
Which of the following inheritance strategies is not supported by the Java Persistence API?
a.
Single Table Per Class Hierarchy
b.
Joined Subclass
c.
Single Table Per Class
d.
Multiple Hierarchy
2.
What is the primary purpose of the
javax.xml.ws.Provider
API?
a.
Binds XML to Java objects.
b.
Allows web services to work directly with messages.
c.
Simplifies WSDL creation.
d.
Specifies the URL of a web service provider.
e.
None of the above
3.
Which of the following statements about the
ELResolver
class is true?
a.
In Java EE 5, the classes
VariableResolver
and
PropertyResolver
have been merged into the
ELResolver
class.
b.
The way an expression is resolved can be customized by adding custom
ELResolver
subclasses to the
ELResolver
chain.
c.
To make an
ELResolver
class visible to the Java EE runtime, it must be declared in an application configuration resource file.
d.
All of the above.
4.
What does the
<service-name-pattern>
element in the following set of XML statements do:
<handler-chains xmlns="http://java.sun.com/xml/ns/javaee">
<handler-chain>\
<service-name-pattern
xmlns:ns1="http://example.com/handlers">
ns1:HelloService
</service-name-pattern>
<handler/>
<handler/>
</handler-chain>
</handler-chains>
a.
Applies the handlers specified in the
<handler-chain>
element to the service with the Java EE qname
{http://example.com/handlers}HelloService
.
b.
Adds a service named
HelloService
to the handlers specified in the
<handler-chain>
element.
c.
Applies the handlers specified in the
<handler-chain>
element to all ports whose names begin with
HelloService
.
d.
None of the above.
5.
What role does an
XMLHttpRequest
object play in an AJAX-enabled application?
a.
It's used as a proxy to transmit requests to a server in a different domain.
b.
It's used to identify a filter for exchange of XML-based
AJAX
requests between the client and server.
c.
It's used to transmit
AJAX
requests asynchronously over HTTP to a server-side component.
d.
There is no such thing as an
XMLHttpRequest
object.
Answers
1.
Which of the following inheritance strategies is not supported by the Java Persistence API?
d.
Multiple Hierarchy. The Java Persistence API allows for three different inheritance strategies that dictate how subclasses are mapped to database tables. The three strategies are single table per class hierarchy, joined subclass, and single table per class.
2.
What is the primary purpose of the
javax.xml.ws.Provider
API?
b.
Allows web services to work directly with messages. The JAX-WS 2.0 specification provides two new APIs which make it possible for web services to work with messages or message payloads. The APIs are
javax.xml.ws.Provider
and
java.xml.ws.Dispatch
.
Provider
is a server-side API, while
Dispatch
is a client-side API.
3.
Which of the following statements about the
ELResolver
class is true?
d.
All of the above. For more about the
ELResolver
class, especially how to create a customized
ELResolver
.
4. What does the
<service-name-pattern>
element in the following set of XML statements do:
<handler-chains xmlns="http://java.sun.com/xml/ns/javaee">
<handler-chain>
<service-name-pattern
xmlns:ns1="http://example.com/handlers">
ns1:HelloService
</service-name-pattern>
<handler/>
<handler/>
</handler-chain>
</handler-chains>
e. Applies the handlers in the specified in the <handler-chain>
element to the service with the Java EE qname {http://example.com/handlers}HelloService
. The <service-name-pattern>
element applies handlers to specific services. Handlers are interceptors that can be easily plugged into the JAX-WS 2.0 runtime environment to do additional processing of inbound and outbound messages. A handler chain is an ordered list of handlers that is used for configuring handlers. .
5.What role does an
XMLHttpRequest
object play in an AJAX-enabled application?
c.
It's used to transmit
AJAX
requests asynchronously over HTTP to a server-side component. An
XMLHttpRequest
object plays a central role in the
AJAX
methodology as the means of interaction between the client and server-side component that processes
AJAX
requests.
posted @
2006-11-27 09:26 Sun River|
编辑 收藏
摘要: Part
I.
XSLT Programming
1) What is the exac...
阅读全文
posted @
2006-11-27 08:00 Sun River|
编辑 收藏
1).
Processing (parsing) XML documents using:
- Document Object Model (DOM)
- Simple API for XML (SAX)
Transforming XML documents using
- XSL/XSLT
- XPath
2). Steps for DOM Parsing
1. Tell the system which parser you will use
2. Create a JAXP document builder
3. Invoke the parser to create a Document representing an XML
document
4. Normalize the tree
5. Obtain the root node of the tree
6. Examine and modify properties of the node
3).
Steps for SAX Parsing
1. Tell the system which parser you want to use
2. Create a parser instance
3. Create a content handler to respond to parsing events
4. Invoke the parser with the designated content handler and
document
posted @
2006-11-27 05:26 Sun River|
编辑 收藏