Sun River
Topics about Java SE, Servlet/JSP, JDBC, MultiThread, UML, Design Pattern, CSS, JavaScript, Maven, JBoss, Tomcat, ... |
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.
(1)假設(shè)在helloapp應(yīng)用中有一個(gè)hello.jsp,它的文件路徑如下: |
|
(3)假設(shè)在helloapp應(yīng)用中有一個(gè)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是什么? (單選)
選項(xiàng):
(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)客戶請(qǐng)求訪問HTML頁面與訪問Servlet有什么異同?(多選)
選項(xiàng):
(A)相同:都使用HTTP協(xié)議
(B)區(qū)別:前者Web服務(wù)器直接返回HTML頁面,后者Web服務(wù)器調(diào)用Servlet的方法,由Servlet動(dòng)態(tài)生成HTML頁面
(C)相同:前者Web服務(wù)器直接返回HTML頁面,后者Web服務(wù)器直接返回Servlet的源代碼。
(D)區(qū)別:后者需要在web.xml中配置URL路徑。
(E)區(qū)別:前者使用HTTP協(xié)議,后者使用RMI協(xié)議。
(5)HttpServletRequest對(duì)象是由誰創(chuàng)建的?(單選)
選項(xiàng):
(A)由Servlet容器負(fù)責(zé)創(chuàng)建,對(duì)于每個(gè)HTTP請(qǐng)求, Servlet容器都會(huì)創(chuàng)建一個(gè)HttpServletRequest對(duì)象
(B)由JavaWeb應(yīng)用的Servlet或JSP組件負(fù)責(zé)創(chuàng)建,當(dāng)Servlet或JSP組件響應(yīng)HTTP請(qǐng)求時(shí),先創(chuàng)建
HttpServletRequest對(duì)象
(6)從HTTP請(qǐng)求中,獲得請(qǐng)求參數(shù),應(yīng)該調(diào)用哪個(gè)方法? (單選)
選項(xiàng):
(A)調(diào)用HttpServletRequest對(duì)象的getAttribute()方法
(B)調(diào)用ServletContext對(duì)象的getAttribute()方法
(C)調(diào)用HttpServletRequest對(duì)象的getParameter()方法
(7)ServletContext對(duì)象是由誰創(chuàng)建的?(單選)
選項(xiàng):
(A)由Servlet容器負(fù)責(zé)創(chuàng)建,對(duì)于每個(gè)HTTP請(qǐng)求, Servlet容器都會(huì)創(chuàng)建一個(gè)ServletContext對(duì)象
(B)由JavaWeb應(yīng)用本身負(fù)責(zé)為自己創(chuàng)建一個(gè)ServletContext對(duì)象
(C)由Servlet容器負(fù)責(zé)創(chuàng)建,對(duì)于每個(gè)JavaWeb應(yīng)用,在啟動(dòng)時(shí),Servlet容器都會(huì)創(chuàng)建一個(gè)ServletContext對(duì)象
(8)jspForward1.jsp要把請(qǐng)求轉(zhuǎn)發(fā)給jspForward2.jsp,應(yīng)該在jspForward1.jsp中如何實(shí)現(xiàn)? (單選)
選項(xiàng):
(A) <a href=“jspForward2.jsp”>jspForward2.jsp </a>
(B) <jsp:forward page=“jspForward2.jsp”>
(9)當(dāng)瀏覽器第二次訪問以下JSP網(wǎng)頁時(shí)的輸出結(jié)果是什么?(單選)
<!% int a=0;???? %>
<%
???? int b=0;
???? a++;
???? b++;
%>
a:<%= a %> <br>
b:<%= b %>
??
選項(xiàng):
(A)??a=0??b=0
(B) a=1??b=1
(c) a=2??b=1
(10)下面哪個(gè)說法是正確的? (單選)
選項(xiàng):
(A) 對(duì)于每個(gè)要求訪問maillogin.jsp的HTTP請(qǐng)求,Servlet容器都會(huì)創(chuàng)建一個(gè)HttpSession對(duì)象
(B)每個(gè)HttpSession對(duì)象都有惟一的ID。
(C)JavaWeb應(yīng)用程序必須負(fù)責(zé)為HttpSession分配惟一的ID
(11)如果不希望JSP網(wǎng)頁支持Session,應(yīng)該如何辦? (單選)
選項(xiàng):
(A) 調(diào)用HttpSession的invalidate()方法
(B) <%@ page session= “false\">
(12)在標(biāo)簽處理類中,如何訪問session范圍內(nèi)的共享數(shù)據(jù)? (多選)
選項(xiàng):
(A)在TagSupport類中定義了session成員變量,直接調(diào)用它的getAttribute()方法即可。
(B)在標(biāo)簽處理類TagSupport類中定義了pageContext成員變量,先通過它的getSession()方法獲得當(dāng)前的
HttpSession對(duì)象,再調(diào)用HttpSession對(duì)象的getAttribute()方法。
(C)pageContext.getAttribute(“attributename”,PageContext.SESSION_SCOPE)
(13)在下面的選項(xiàng)中,哪些是TagSupport類的doStartTag()方法的有效返回值? (多選)
選項(xiàng):
(A) Tag.SKIP_BODY
(B) Tag.SKIY_PAGE
(C) Tag.EVAL_BODY_INCLUDE
(D) Tag.EVAL_PAGE
(14)以下代碼能否編譯通過,假如能編譯通過,運(yùn)行時(shí)得到什么打印結(jié)果?(單選)
request.setAttribute(\"count\",new Integer(0));
Integer count = request.getAttribute(\"count\");
選項(xiàng):
A)不能編譯通過??B)能編譯通過,并正常運(yùn)行??
C) 編譯通過,但運(yùn)行時(shí)拋出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
判斷題:(其它試題請(qǐng)下載)
1 . Java 程序里 , 創(chuàng)建新的類對(duì)象用關(guān)鍵字 new ,回收無用的類對(duì)象使用關(guān)鍵字 free 。
2 .對(duì)象可以賦值,只要使用賦值號(hào)(等號(hào))即可,相當(dāng)于生成了一個(gè)各屬性與賦值對(duì)象相同的新對(duì)象。
3 .有的類定義時(shí)可以不定義構(gòu)造函數(shù),所以構(gòu)造函數(shù)不是必需的。
4 .類及其屬性、方法可以同時(shí)有一個(gè)以上的修飾符來修飾。
5 . Java 的屏幕坐標(biāo)是以像素為單位,容器的左下角被確定為坐標(biāo)的起點(diǎn)
6 .抽象方法必須在抽象類中,所以抽象類中的方法都必須是抽象方法。
7 . Final 類中的屬性和方法都必須被 final 修飾符修飾。
8 .最終類不能派生子類,最終方法不能被覆蓋。
9 .子類要調(diào)用父類的方法,必須使用 super 關(guān)鍵字。
10 .一個(gè) Java 類可以有多個(gè)父類。
11 .如果 p 是父類 Parent 的對(duì)象,而 c 是子類 Child 的對(duì)象,則語句 c = p 是正確的。
12 .一個(gè)類如果實(shí)現(xiàn)了某個(gè)接口,那么它必須重載該接口中的所有方法。
13 .當(dāng)一個(gè)方法在運(yùn)行過程中產(chǎn)生一個(gè)異常,則這個(gè)方法會(huì)終止,但是整個(gè)程序不一定終止運(yùn)行。
14 .接口是特殊的類,所以接口也可以繼承,子接口將繼承父接口的所有常量和抽象方法。
15 .用“ + ”可以實(shí)現(xiàn)字符串的拼接,用 - 可以從一個(gè)字符串中去除一個(gè)字符子串。
16 .使用方法 length( ) 可以獲得字符串或數(shù)組的長(zhǎng)度。
17 .設(shè) String 對(duì)象 s=”Hello ” ,運(yùn)行語句 System.out.println(s.concat(“World!”)); 后 String 對(duì)象 s 的內(nèi)容為 ”Hello world!” ,所以語句輸出為
Hello world!
18 .創(chuàng)建 Vector 對(duì)象時(shí)構(gòu)造函數(shù)給定的是其中可以包容的元素個(gè)數(shù),使用中應(yīng)注意不能超越這個(gè)數(shù)值。
19 .所有的鼠標(biāo)事件都由 MouseListener 監(jiān)聽接口的監(jiān)聽者來處理。
20 .一個(gè)容器中可以混合使用多種布局策略。
21 . Java 中,并非每個(gè)事件類都只對(duì)應(yīng)一個(gè)事件。
22 .一個(gè)線程對(duì)象的具體操作是由 run() 方法的內(nèi)容確定的,但是 Thread 類的 run() 方法是空的 , 其中沒有內(nèi)容 ; 所以用戶程序要么派生一個(gè) Thread 的子類并在子類里重新定義 run() 方法 , 要么使一個(gè)類實(shí)現(xiàn) Runnable 接口并書寫其中 run() 方法的方法體。
23 . Java 的源代碼中定義幾個(gè)類,編譯結(jié)果就生成幾個(gè)以 .class 為后綴的字節(jié)碼文件。
24 . Java Applet 是由獨(dú)立的解釋器程序來運(yùn)行的。
25 . Java Applet 只能在圖形界面下工作。
26 . Java 的字符類型采用的是 ASCII 編碼。
27 . Java 的各種數(shù)據(jù)類型占用固定長(zhǎng)度,與具體的軟硬件平臺(tái)環(huán)境無關(guān)
28 . Applet 是一種特殊的 Panel ,它是 Java Applet 程序的最外層容器。
29 .子類的域和方法的數(shù)目一定大于等于父類的域和方法的數(shù)目。
30 . System 類不能實(shí)例化,即不能創(chuàng)建 System 類的對(duì)象。
31 .用戶自定義的圖形界面元素也可以響應(yīng)用戶的動(dòng)作,具有交互功能
32 . Java 中數(shù)組的元素可以是簡(jiǎn)單數(shù)據(jù)類型的量,也可以是某一類的對(duì)象。
33 . Vector 類中的對(duì)象不能是簡(jiǎn)單數(shù)據(jù)類型。
34 . Java 中的 String 類的對(duì)象既可以是字符串常量,也可以是字符串變量。
35 .容器是用來組織其他界面成分和元素的單元,它不能嵌套其他容器。
-- 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.
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"
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)
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
c.??????????????????????????????
It's used to transmit
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
XMLHttpRequest
object plays a central role in the
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