executeupdate vs executequery vs execute

ResultSet executeQuery() – Used for reading the content of the database.
output will be in form of ResultSet.
eg – SELECT statement.

int executeUpdate() – Used for DML(altering the database).
output will be in int.
eg – DROP TABLE or DATABASE, INSERT into TABLE, UPDATE TABLE, DELETE from TABLE statements.

boolean execute() – Executing SQL statements.
output will be in boolean. TRUE indicates the result is a ResultSet and FALSE indicates it has the int value which denotes number of rows affected by the query.
eg – DROP TABLE or DATABASE, INSERT into TABLE, UPDATE TABLE, DELETE from TABLE statements.

Element Locators using XPath

Expressions

 xpath=xpathExpression
   xpath=//img[@alt='The image alt text']
   xpath=//table[@id='table1']//tr[4]/td[2]
   xpath=//a[contains(@href,'#id1')]
   xpath=//a[contains(@href,'#id1')]/@class
   xpath=(//table[@class='stylee'])//th[text()='theHeaderText']/../td
   xpath=//input[@name='name2' and @value='yes']
   xpath=//*[text()="right"]

DOM – Javascript

 xpath=xpathExpression
 dom=document.forms['myForm'].myDropdown
 dom=document.images[56]
 dom=function foo() { return document.links[1]; }; foo();

How to find particular text in web driver method

WebDriver driver = new FirefoxDriver();
driver.get("https://localhost:8080/Login");

//Finds the xpath of element which contains UserName
WebElement strElemnt1 = driver.findElement(By.xpath("html/body/div[1]/div[2]/div[2]/div[2]/p[1]/b"));

How to get Last Row in Table

//How to get Last Row in Table 
String cssLast="table[class='dataTable']>tr:first-child>td:last-child"
String cssFirst="table[class='dataTable']>tr:last-child>td:last-child"

driver.findElement(By.cssSelector(cssLast)).getText();
driver.findElement(By.cssSelector(cssFirst)).getText();

By Using XPath

//By Using XPath
WebElement lastCellInFirstRow = driver.findElement(By.xpath("table[@class='dataTable']//tr[1]//td[last()]"));
WebElement lastCellInLastRow = driver.findElement(By.xpath("table[@class='dataTable']//tr[last()]//td[last()]"));

How to detect custom attribute

//How to detect custom attribute 
assertTrue(selenium.isElementPresent("//*[@btn-tag-title='Sign In']"));
selenium.click("//*[@btn-tag-title='Sign In']");

assertTrue(selenium.isElementPresent("css=*[btn-tag-title='Sign In']"));
selenium.click("css=*[btn-tag-title='Sign In']");

Finding custom attribute of span where attr=”data-automation-id” and val=”SEL_ERR”

//HTML Code
<span data-automation-id="SEL_ERR">
  Error Description
</span>

//Selenium Code
driver.findElement(By.cssSelector("span[data-automation-id='SEL-ERR']"));

If Selenium cannot find it, it’ll throw an exception. Exceptions are costly. You can use .findElements instead (mentioned in 1)), which will simply return an empty list if it cannot find the element you are looking for

driver.findElements(By.cssSelector("span[data-automation-id='SEL-ERR']")).size() != 0;

For setting the Bean value in struts-config.xml we should use the form-beans tag.The form-beans tag might contain any number of bean property defined within form-bean as below.

Defining a Simple Bean Property

<form-beans>
 <form-bean name="userBean" type="org.apache.struts.action.DynaActionForm">
   <form-property name="userName" initial="This is Bean Value" type="java.lang.String" />	
 </form-bean>
</form-beans>

In the above code I am creating a userBean and setting its value is initialized to This is Bean Value.

Now in the action mapping part of the struts-config.xml I am going to map the above created bean to path as said below

<action-mappings>
 <action path="/showBeanValue" type="org.apache.struts.actions.ForwardAction" parameter="/showBeanValue.jsp"/>				
 <action name="userBean" path="/Login" />		
</action-mappings>

In the first line I am defining action path as showBeanValue and it is going to forward to page showBeanValue.jsp when some one access the showBeanValue.do in url.

In the second statement I am creating a dummy form since the the html form action should not be empty.

 
  <%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
  <%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>     
  <html:form action="/Login">
    <bean:write name="userBean" property="userName"></bean:write>
    <bean:write name="userBean" property="userAge"></bean:write>
  </html:form>

load-on-startup is a tag element which appear inside servlet tag in web.xml.load-on-startup tells the web container about loading of a particular servlet. if you don’t specify load-on-startup then container will load a particular servlet when it feels necessary most likely when first request for that servlet will come, this may lead to longer response time for that query if Servlet is making database connection which contribute network latency or time consuming job.

 <servlet>
   <servlet-name>StartUpServlet</servlet-name>
   <servlet-class>com.mugil.tutor.ConfigServlet</servlet-class>
   <load-on-startup>1</load-on-startup>
  </servlet>

Points to remember

  • If load-on-startup value is same for two servlet than they will be loaded in an order on which they are declared inside web.xml file.
  • If load-on-startup is 0 or negative integer than Servlet will be loaded when Container feels to load them.
  • load-on-startup guarantees loading, initialization and call to init() method of servlet by web container.
  • If there is no load-on-startup element for any servlet than they will be loaded when web container decides to load them.

Lower the value of load-on-startup, servlet will be loaded first.

Use during Connection pool, downloading files or data from network or prepare environment ready for servicing client in terms of initializing cache, clearing pipelines and loading important data in memory

Add the JSTL Library as below

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

Populating a Text Box

  <input name="txtUserName" id="txtUserName" type="text" value='<c:out value="${User.userName}"></c:out>'>

Populating a Dropdown List
Type 1

 <select name="cboAge" id="cboAge">
  <c:forEach begin="20" end="60" var="i">
    <option value="${i}" <c:if test="${i == User.age}">Selected</c:if>>${i}</option>    			
  </c:forEach>
 </select>

Type 2

 <select name="cboLocation" id="cboLocation">
   <option value="Chennai">Chennai</option>
   <option value="Bangalore">Bangalore</option>
   <option value="Mumbai">Mumbai</option>
  </select>

Javascript Code

$('document').ready(function(){
  $('#cboLocation').val('<c:out value="${User.location}"></c:out>');
});

Populating Radio buttons

<input name="rdoGender" type="radio" id="rdoMale" value="1" <c:out value="${User.gender == 1?'checked':''}"></c:out>><label for="rdoMale">Male</label>
<input name="rdoGender" type="radio" id="rdoFemale" value="0" <c:out value="${User.gender == 0?'checked':''}"></c:out>><label for="rdoFemale">Female</label>

Populating Check boxes

 <input name="chkSkills" type="checkbox" id="chkJava" value="Java" <c:if test="${fn:contains(User.skills, 'Java')}">Checked</c:if>><label for="chkJava">Java</label>    	
Posted in JSP.

While storing the HTML code in oracle db the column type should be CLOB rather than BLOB. Incase if you have used BLOB for storing the HTML code while carrying out update you should first convert the content in to hexadecimal values as below.

  SELECT (RAWTOHEX(UTL_RAW.CAST_TO_RAW('Test'))) 
    FROM DUAL;

The above code returns Hexadecimal value for test as below
54657374

Now if you want to update the Hexadecimal you need to do the same thing.

UPDATE TemplateTbl
   SET TemplateConetent = (RAWTOHEX (UTL_RAW.cast_to_raw ('Mugil &nbsp; Nikkhil')))
   WHERE TemplateId = TL2600

The above code seems to be fine but it does not work as the &nbsp; would be interrupted as if a variable prompting you to enter the variable value.

To overcome this issue &nbsp; should be replace with &&nbsp; as below

UPDATE TemplateTbl
   SET TemplateConetent = (RAWTOHEX (UTL_RAW.cast_to_raw ('Mugil &&nbsp; Nikkhil')))
   WHERE TemplateId = TL2600

Cheers. We are Done. :-).

You can create autoincrement column in oracle in two ways.

Method 1 : Using sequence

Table Creation Query

 CREATE TABLE tblusers(UserId INT, UserName VARCHAR(50));

Sequence Creation Query

  CREATE SEQUENCE tblusers_userid_seq 
         MINVALUE 1 MAXVALUE 999999999999999999999999999 
         START WITH 1 INCREMENT BY 1 CACHE 20;

The above code creates a sequence for table tblusers with name tblusers_userid_seq with start value of 1 and limit 999999999999999999999999999.

Insertion Query

  INSERT INTO tblusers(UserId, UserName) VALUES (tblusers_userid_seq.nextVal, 'John')

Method 2 : Using Trigger
In Method 2 we can use triggers to carry out auto increment when rows are added to the table.

Before creating trigger you should make the auto increment column as primary key.For that the code is as below

  ALTER TABLE tblusers ADD (
  CONSTRAINT UserId_pk PRIMARY KEY (UserId));

The Creation of sequence and trigger is as follows

CREATE SEQUENCE tblusers_userid_seq;  
CREATE OR REPLACE TRIGGER tblusers_userid_trigg 
BEFORE INSERT ON tblusers 
FOR EACH ROW
BEGIN
  SELECT tblusers_userid_seq.NEXTVAL
  INTO   :new.UserId
  FROM   dual;
END;

Now during insertion there is no need to worry about the auto increment column and the insert query no need to contain the Id column as below

  INSERT INTO tblusers(UserName) VALUES ('John')

Filters are helpful in performing filter functionality in Java web application Application. A filter implements the javax.servlet.Filter interface. The primary filter functionality is implemented by the doFilter() method of the filter.

A filter is used to perform a particular task either before or after the actual functionality of a web application is performed. For example, if a request is made for a particular resource such as a Servlet in web application and a filter is used, the filter code may execute and then pass the user on to the Servlet. The filter may run a check before letting the user to the actual page.The filter checks the user permissions to access a particular servlet, and it might send the user to an error page rather than to the requested resource.

Below is a code which shows the filter in web.xml file

web.xml

 <webapp>
  <filter>
    <filter-name>SampleFilter</filter-name>
    <filter-class>com.mugil.filter.TestFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>SampleFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  </web-app>

Filter code is java is as below
TestFilter.java

public class TestFilter implements Filter 
{
  public void init(FilterConfig fConfig) throws ServletException 
  {
     System.out.println("Filter Initialized");
  }
  
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException 
  {	
     response.setContentType("text/html");
     PrintWriter out = response.getWriter();
     out.print("Filter Executed");		
     chain.doFilter(request, response);
  }

  public void destroy() 
  {
    System.out.println("Filter Destroyed");
  }
}

The init() method will be executed every time the server starts.The doFilter method is executed every time a Servlet or JSP page is accessed in the context.Filter destroy() method is called when the server is stopped.

context – circumstances that form the setting for an event.For our scenario context represents virtual host within which our web application runs.The environment where the WAR file is deployed.

Below is an Example of File which stores variable in context.xml and is available for the whole application.The context.xml file contains the default Context element used for all web applications in the system.

context.xml

  <Context>      
     <Parameter name="companyName" value="My Company, Incorporated"/>
  </Context>

The same thing can be defined in the web.xml file as below
web.xml

  <context-param>
     <param-name>companyName</param-name>
     <param-value>My Company, Incorporated</param-value>
   </context-param>

To access the context variable in Servlet you can use the following code in doGet() Method as below
Test.java

 
protected void doGet(HttpServletRequest request, HttpServletResponse response)
{
  ServletContext servletContext = getServletContext();		  
  PrintWriter out = response.getWriter();
  out.print(servletContext.getInitParameter("companyName"));  
}

Case1: The context variable in web.xml will have highest priority than context.xml in server and application if override attribute is set to true or if it is undefined.

Case2: Defining a context variable in $CATALINA_BASE/conf/context.xml and context.xml file inside your application the former will have more privilege.

Declaring context attributes in web.xml is better since they will work when you deploy your app in other App Servers other than Tomcat.

What is Context Path
A web applications context path is the directory that contains the web applications WEB-INF directory.It points to WebContent directory in your project.

Server context path is the one which tells the location where the WebContent directory is placed during project deployment in server.The following code tells you how to find server context path.

Test.java

protected void doGet(HttpServletRequest request, HttpServletResponse response) 
{	
   ServletContext servletContext = getServletContext();		
   String contextPath = servletContext.getRealPath(File.separator);
   PrintWriter out = response.getWriter();
   out.println("<br/>Context path: " + contextPath);
}  

The above code outputs some directory within tomcat folder like one below
Output

Context path:  D:\Tomcat\wtpwebapps\CustomTag\ 

In my case D:\Tomcat\ is where my tomcat is installed and wtpwebapps\ is the context where my project
\CustomTag\ is deployed