Sie sind auf Seite 1von 10

Web.

xml
<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/webapp_2_2.dtd"> <web-app> <!-- Action Servlet Configuration --> <servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <init-param> <param-name>application</param-name> <param-value>ApplicationResources</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- Action Servlet Mapping --> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!-- Application Tag Library Descriptor --> <taglib> <taglib-uri>/WEB-INF/app.tld</taglib-uri> <taglib-location>/WEB-INF/app.tld</taglib-location> </taglib> <!-- Struts Tag Library Descriptors --> <taglib> <taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri> <taglib-location>/WEB-INF/struts-bean.tld</taglib-location> </taglib> <welcome-file-list> <welcome-file>home.jsp</welcome-file> </welcome-file-list> </web-app>

struts-config.xml
<?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.0//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd"> <struts-config> 1. <data-sources> <data-source type="org.apache.commons.dbcp.BasicDataSource driverClass = "sun.jdbc.odbc.JdbcOdbcDriver" url = "jdbc:odbc:raaja" username ="scott" password ="tiger" autocommit = True maxCount = 10 minCount = 3 />

</data-sources> 2. <form-beans> 1. <form-bean name="tatateleForm" type="org.apache.struts.action.DynaActionForm"> <form-property name="phno" type="java.lang.String" /> </form-bean> 2. <form-bean name="loginForm" type="org.apache.struts.validator.DynaValidatorForm" dynamic=true> <form-property name="uid" type="java.lang.String" /> </form-bean> 3. <form-bean name="Accbean" type="accdemo.AccViewForm" /> </form-beans> 3. <global-exceptions> <exception path = login.jsp type=con.InvalidLoginException key=global.error.invalidLogin scopr=request /> </global-exceptions> 4. <global-forwards> <forward name="result" path="/result.jsp" redirect=true/> </global-forwards> 5. <action-mappings> path = "/details" type = "BankAction" name = "tatateleForm" scope ="request" input = "/TataTeleServicesLtd.jsp" validate= "true" > <forward name="bills" path="/telephonebills.jsp" /> </action> 6. <message-resources parameter="ApplicationResources"/> 7. a. <plug-in className="org.apache.struts.validator.ValidatorPlugIn"> <set-property property="pathnames" Value=org/apache/struts/validator/validator-rules.xml, /WEB-INF/validation.xml"/> <set-property property="stopOnFirstError" value="false"/> </plug-in> b. <plug-in className="org.apache.struts.tiles.TilesPlugin" > <set-property property="definitions-config" value="/WEB-INF/tileDefinitions.xml" /> <set-property property="definitions-debug" value="2" /> <set-property property="definitions-parser-details" value="2" /> <set-property property="definitions-parser-validate" value="true" /> </plug-in> </struts-config> <action

validation.xml
<!DOCTYPE form-validation PUBLIC "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.0//EN" "http://jakarta.apache.org/commons/dtds/validator_1_0.dtd"> <form-validation> <formset> <form name="AccountFormBean"> <field property="accNo" depends="required, minBalance"> <arg0 key="bank.add.jsp.accno"/> </field> </form> </formset>

</form-validation> FormBean class public final class AccountEditForm extends ActionForm { public void reset(ActionMapping actionmapping, HttpServletRequest httpservletrequest) { System.out.println("reset method"); } public ActionErrors validate(ActionMapping mapping, HttpServletRequest request){ ActionErrors errors = new ActionErrors(); errors.add("accno", new ActionError("err.accno.empty", accno)); return errors; } }

Action Class
Public final class AccountAction extends Action{ MessageResources msgres = null; public ActionForward execute(ActionMapping map, ActionForm form, HttpServletRequest req, HttpServletResponse res) throws Exception{ String accno = (String) PropertyUtils.getSimpleProperty(form, "accno"); ActionMessage mesg=null; ActionMessages messages=new ActionMessages(); mesg = new ActionMessage(msg.acc.notfound); messages.add(ActionMessages.GLOBAL_MESSAGE, mesg); saveMessages(request,messages); return(mapping.findForward(status)); msgres = getResources(reuest); If(row<=0){ messages.add("insert", new ActionMessage("account.create.failed")); saveErrors(request, messages); return (new ActionForward(mapping.getInput())); } } }

Tags
JSP JSP life Cycle 1. Jsp Page Translation 2. Jsp Page compilation 3. loads class 4. create instance 5. call the JspInit(). 6. call the _JspService(). 7. call the JspDestroy(). Servlet Life Cycle 1. Instance does not exist, container loads servlet class, creates instance. 2. Init() call. 3. Service() call 4. Destroy() call. Http 1. Init(). 2. Service(). From service() doGet(). doPost(). doPut(). doHead(). doDelete(). doTrace(). doOptions(). 3. Destroy().

<%@ page import="com.peers.action.AccountFormBean" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %> <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %> <%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %> Tags: 1. Directives:

1. 2. 3.

<%@ page import, info, language, contentType, extends,session, buffer, autoflush, isThreadSafe, errorpage, isErrorPage > <%@ include file=copyright.html %> <%@ taglib uri="" prefix="" %>

Implicit Objects: request, response, pageContext, application, out, config, page, session, exception Object Scopes: page, request, session, and application. Least most Visible visible 2. Scripting Elements: expression, scriptlets, declarations. 1. Expressions: <%=cdetails%> or <%=appBean.getname()%> 2. Scriptlets: <% . %> 3. Declarations: page level variables <%! Int i=0; %> Comments: Jsp comments <%---> Html comments: <!---> Java comments: // or /* */ Exception Handling: <%@ page isErrorPage=false errorPage=errorHandler.jsp: %> 3. Action: 1. <jsp:useBean id =user class= scope= /> <jsp:getProperty name=user property= /> <jsp:setProperty name=user property= value= /> </jsp:useBean> <jsp:forward page=<%=somepage%> <jsp:param name=name1 value=value1 /> </jsp:forward> <jsp:include page=shoppingcart.jsp flush=true /> <jsp:plugin type=bean/applet code=classfilename />

2. 3. 4.

Not to cache(ie cookies) Web browser caching <% response.setHeader(Cache-control,no-store); response.setHeader(Pragma,no-cache); response.setDateHeader(Expires,0); %> Proxy server caching response.setHeader(Cache-control,private); EJB
Life cycle of stateful session bean Does not exist Life cycle of entity bean Does not exist create() newInstance() setSessionContext() ejbCreate() Pool State / memory ejbActivate() Method ready state business logic methods ejbPassivate() Passive ejbActivate() Method ready state ejbStore() ejbLoad() ejbPassivate()

1.create() newInstance() 2. setSessionContext() 3.ejbCreate()

1.remove() 2.ejbRemove()

remote.remove() home.remove() ejbRemove()

Life cycle of stateless session bean 1. setSessionContext 2. ejbCreate

Does not exist


ejbRemove Life cycle of Message Driven Bean 1. setMessageDrivenContext ejbRemove 2. ejbCreate

Ready

Does not exist

Ready

Client program: onMessage Import ejb, naming, util, rmi; current pkg Public class EjbClient{ public static void main(String args[]){ try{ Properties p = new Properties(); p.put(context.INITIAL_CONTEXT_FACTORY,weblogic.jndi.T3InitialContextFactory); p.put(Context.PROVIDER_URL,t3://localhost:7001); (or) Properties p = System.getProperties(); InitialContext ic = new InitialContext(p); Object obj = ic.lookup(HomeInterface); HomeInterface home = (HomeInterface) obj; RemoteInterface remote = home.create(); int result = remote.businesslogicmethod(); }catch(Exception e){ e.printStackTrace(); } } } LDAP: Light Weight Directory Access Protocol When to use: 1. when you like your data to be available cross platform. 2. To access data from a number of computers or applications. 3. If the records will change less number of times. 4. When we want to store data on a flat file instead of RDBMS. JNDI: Java Naming & Directory Interface. Used to access multiple naming & directory services. It provides ability to directly talk to different network directory services. IIOP: Internet Inter-orb protocol. RMI over IIOP developed by sun & IBM together.

Singleton design Pattern


Class A{ int x; Private A(){} Private static A a = new A(); Public void setX(int b){x=b;} Public int getX(){return x;} Public static A getInstance(){return a;} }

Memory Setting in JVM:


java server Xms256M Xmx1024M XX:PermSize=256M -XX:MaxPermSize=256M java client Xms256M Xmx1024M XX:PermSize=256M -XX:MaxPermSize=256M

Thread Life Cycle


Start() Born State or newly created or ready state stop() X destroy() X

Running State Stop() X notify() notifyAll() resume() X stop() X

wait(), sleep(1000), X suspend(), Blocke d

Dead State

If A is Super class and B is child class and if A a = new B(); then all the variables called with the help of object a is from super class and methods are from child class.

Concurrent Versioning System:


Repository, commit, version conflict, make as merge

Heap: Objects Stack: variables, references and objects are created for method arguments and method variables
ArrayList ArrayList A = new ArrayList(); a.add(aaaa); a.add(bbb); Iterator I = A.iterator(); While(I.hasNext()){ Object obj = I.next(); }

A correlated sub query is closely related to the main query through cross-references to specific values in rows retrieved by the main query. Stored Procedures or functions
Create or replace procedure <procedure name> (x VARCHAR) is begin insert into emp values(x);end; Create or replace procedure <procedure name> (x OUT VARCHAR) is begin insert into emp values -----------;end; Create or replace function <function name> return varchar is begin return a return string; end; Create or replace function <function name> (x varchar) is begin return a return string ||x; end; Scrollable or updatable result set Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE) TYPE_SCROLL_INSENSITIVE CONCUR_READONLY TYPE_FORWARD_ONLY Isolation Levels TRANSACTION_READ_UNCOMMITTED, TRANSACTION_READ_COMMITED, TRANSACTION_REPEATABLE_READ, TRANSACTION_SERIALIZABLE Batch Statements Stmt.addBatch(sql stmt); In I = stmt.executeBatch(); or ResultSet rs= batchUpdate(); Con.setAutoCommit(false/true); con.commit(); con.rollBack(); To get connection from connection pool InitialContext ic = new InitialContexr(); DataSource ds = (DataSource) ic.lookup(jndiname); Connection con = ds.getConnection();

AJAX function showbank(str){ xmlHttp=GetXmlHttpObject(); if (xmlHttp==null) { alert ("Your browser does not support AJAX!"); return; } var url="./bdetails?code="+str; xmlHttp.onreadystatechange=stateChanged; xmlHttp.open("GET",url,true); xmlHttp.send(null); } function GetXmlHttpObject(){ var xmlHttp=null; try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); }catch (e) { // Internet Explorer try{ xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); }catch (e){ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; } function stateChanged() { if (xmlHttp.readyState==4){ if(xmlHttp.status == 200) { var banknameEle = xmlHttp.responseXML.getElementsByTagName("BNAME"); (or) document.getElementById(div tag id0.innerHTML = xmlHttp.responseText var bankname = banknameEle[0].firstChild.nodeValue; window.document.forms[0].bankName.value=bankname; /* var tableid=document.getElementById("pdetails"); var tr1=document.createElement("tr"); var pnameEle=document.createElement("td"); pnameEle.appendChild(document.createTextNode(NAME[i].firstChild.nodeValue)); tr1.appendChild(pnameEle); tr1.setAttribute("onClick","populatePatientFields(this)"); tr1.onmouseover=function(e){ this.bgColor="#D8E4F1" } tr1.onmouseout=function(e){ this.bgColor="white"; } tr1.ondblclick=function(e){ populatePatientFields(this); } tableid.appendChild(tr1); */ } } }

Application of DAO and DTO Public class EmpNoDTO{ int empNo=0; public void setEmpNo(int empNo){ this.empNo=empNo; } public int getEmpNO(){ return this.empNo; } } Public class EmpDetailsVO(){ String empName; String empDeptNo; String empLoc; String addr; EmpDetailsVO(String empName, String empDeptNo, String empLoc, String addr) { this.empName = empName; this.empDeptNo = empDeptNo; this.empLoc = empLoc; this.Addr = Addr; } public String getEName(){ return this.EName; } public String getDeptNo(){ return this.DeptNo; } public String getLoc(){ return this.empLoc; } public String getAddr(){ return this.addr; } } Public class DAOFactory{ public DAOFactory(){} public static Object getDAO(String daoEntry) throws classNotFoundException{ return Class.forName(daoEntry).newInstance(); } } Public class DAOUtil{ public DAOUtil(){} public static Connection getConnection(){ return getDataSource().getConnection(); } public static DataSource getDataSource(){ InitialContext ic = new IntitalContext(); return (DataSource)ic.lookup(JNDIname); } public static void closeConnection(Connection connection) { try{ if(connection != null || !connection.isClosed()) connection.close(); }catch(SQLException sqlexception){ System.out.println(sqlexception); } } private static Connection con = null; }

Public class OraEmpDetailsDAO implements EmpDetailsDAO{ public object getEmpDetails(EmpNoDTO eno) throws SQLException, ClassNotFoundException{ Statement st = con.createStatement(); ResultSet rs= st.executeQuery(select * from emp where eno=+eno.getEmpNo()); EmpDetailsVo vo = null; While(rs.nex()) { vo = new empDetailsVO(rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4)); } return vo; } }

Public class empAction extends Action{ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception{ int eno = Integer.ParseInt(PropertyUtils.getSimple Property(form, eno); EmpNoDTO empno = new EmpNoDTO(); Empno.setEmpNo(eno); EmpDetailsDAO empdetails = (OraEmpDeatilsDAO)DAOFactory.getDAO (java:comp/env/dao/empd etDao); Object o = empDetails.getEmpDetails(eno); EmpDetailsVO vo = (EmpDetailsVO)vo; if(vo != null) { request.setAttribute("ename",vo.getEName()); request.setAttribute("deptno",vo.getDeptNo()); request.setAttribute("loc", vo.getLoc()); request.setAttribute("addr",vo.getAddr()); return actionmapping.findForward("AmountPayDetails"); } else{ return actionmapping.findForward("wrongDetails"); } } } Interface EmpDetailsDAO{ public abstract getEmpDetails(EmpNoDTO eno); }

Q) Difference between functions and stored procedures?. Functions 1) Can be used with Select statement 2) Not returning output parameter but returns Table variables 3) You can join UDF 4) Cannot be used to change server configuration 5) Cannot be used with XML FOR clause 6) Cannot have transaction within function
1. Function is mainly used in the case where it must return a value. 2. Function can be called from SQL statements 3. Functions are normally used for computations. 4. You can have DML (insert,update, delete) statements in a function. 5. Function returns 1 value only. 6. Function wont support deferred name resolution.

Procedures 1) Have to use EXEC or EXECUTE 2)Return output parameter 3) Can create table but wont return Table Variables 4) You cannot join Stored Procedures 5) Can be used to change server configuration 6) Can be used with XML FOR Clause 7) Can have transaction within Stored Procedures 1. Procedure may or may not return a value or may

return more than one value using the OUT parameter. 2. Procedure can not be called from the sql statements 3. Procedures are normally used for executing business logic. 4. You cannot call such a function in a SQL query.

5. Procedure can return multiple values (max 1024). 6. Stored Procedure: supports deferred name resolution.
Example while writing a stored procedure that uses table named tabl1 and tabl2 etc..but actually not exists in database is allowed only in during creation but runtime throws error 7. Stored procedure returns always integer value by default zero. 8. Stored procedure is precompiled execution plan 9. A procedure may modify an object

7. Function return type could be scalar or table or table values 8. Functions are not. 9. Function can only return a value The RETURN statement immediately completes the execution of a subprogram and returns control to the caller.

http://www.geekinterview.com/question_details/4662

10

Das könnte Ihnen auch gefallen