Sunday, June 30, 2013

Widening VS Auto Boxing during Overloading

Hi,

In this post we will see the usage of Over loading ,Boxing and widening concepts with an example.

Lets see how the above concepts are related with an example :

Example :-
public class WideningBoxing {
//Overloading example with boxing and widening
public void method(Integer x, Integer y)
{
System.out.println(" in Integer ");
}

public void method(float x, float y)
{
System.out.println("in float");
}
public static void main(String[] args) {
WideningBoxing wb=new WideningBoxing();
wb.method(1, 2);
}
}


Explanation :- Here we have two methods with same names,different parameter types.
We are calling this method from main .

Now the question is which method will be invoked when we call wb.method(1, 2);

The method with Integer or method with float parameters?


JVM will prefer to take widening than boxing here.
So the output will be
in float

The main reason behind this is widening was being implemented before auto boxing, so the API writers thought that the existing functionality should work same ,it should not be changed by adding new auto boxing feature.


This is the common Java interview Question


Note :- Widening is preferred than Boxing 

This is the key take away point from this post.

                     Happy Learning

Please provide your valuable comments on this article and share it across your network.




Page refreshing

Hi,

In this post we will discuss about refreshing a web page at regular interval of time.
There are many ways to do this .
  • Using Java script
  • Setting response headers etc.

We would have seen many popular websites like Facebook, GMail etc. where a page will be refreshing automatically and updating the content at regular intervals of time.
Lets see how to refresh a JSP page with an example.

By using response header
Example :-

PageRefresh.jsp
<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<%@page import="java.util.Date" %>
<head>
<title>Page refresh</title>
</head>
<body>
<%response.setHeader("refresh","5");%>
<%Date date=new Date(); %>
<%="Current time " +date %>
</body>
</html>

Here we have used response.setHeader("refresh","5") ,which takes two parameters—refresh attribute and time interval for page refreshing in seconds. PageRefresh.jsp will be refreshing every 5 seconds and displaying the cureent date and time

Output:-

Current time Sun Jun 30 10:21:21 IST 2013

Current time Sun Jun 30 10:21:26 IST 2013

Environment details :-
  • Eclipse Juno
  • Apache Tomcat

                      Happy Learning

Please provide your valuable comments on this article and share it across your network.



Friday, June 21, 2013

Implementing Remember me functionality using Cookies in Java

Hi All,
Welcome to Java-recent.
In this post we will discuss about implementing Remember Me feature in Java web applications.
We would have come across sites where we will have a login form with an option like remember me etc.When we enter credentials and click on this option ,later point return to this page previously  entered credentials will be shown.How did this implementation happen?

One way of implementing this is using Cookies.

Cookie:- is a information sent from server to a browser and gets stored in browsers folder,generally used to maintain state of an user.This data will be sent back to server for subsequent requests

"A cookie, also known as an HTTP cookie, web cookie, or browser cookie, is a small piece of data sent from a website and stored in a user's web browser while a user is browsing a website. When the user browses the same website in the future, the data stored in the cookie is sent back to the website by the browser to notify the website of the user's previous activity." reference from http://en.wikipedia.org/wiki/HTTP_cookie

Cookies are usually transferred in header data

Here we will implement rembember me using functionality using
  • Cookies
  • JSF 2.0
  • Eclipse IDE

Scenario :-
  • We will have a login page with following components
    • UserName text field
    • Password secret input field
    • Submit button
    • Remember me check box
  • A managedbean which will bind these components and perform validations and setting cookies etc.

Source code :-

RememberMe.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Remember me</title>
</head>
<body>
<f:view>
<h:form>
User name<h:inputText value="#{rememberBean.uName }"></h:inputText>
<br>
Password <h:inputSecret value="#{rememberBean.password }"></h:inputSecret>
<br>
<h:commandButton value="Submit" action="#{rememberBean.submit }"></h:commandButton>
<h:selectBooleanCheckbox value="#{rememberBean.checkBox }"></h:selectBooleanCheckbox>Remember me
</h:form>
</f:view>
</body>
</html>

RememberBean.java
@RequestScoped
public class RememberBean {
private String uName;
private String password;
private boolean checkBox=false;
private String virtualCheck;

public RememberBean()
{
isChecked();
}
public String getVirtualCheck() {
return virtualCheck;
}

public void setVirtualCheck(String virtualCheck) {
this.virtualCheck = virtualCheck;
}

public String getuName() {
return uName;
}

public void setuName(String uName) {
this.uName = uName;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public boolean isCheckBox() {
return checkBox;
}

public void setCheckBox(boolean checkBox) {
this.checkBox = checkBox;
}

public String submit() {
if (uName != null && password != null) {
FacesContext fc=FacesContext.getCurrentInstance();
if (checkBox == true) {
virtualCheck="true";
//getting current instance of faces context
Cookie cUserName = new Cookie("cUserName", uName);
Cookie cPassword = new Cookie("cPassword", password);
Cookie cVirtualCheck = new Cookie("cVirtualCheck", virtualCheck);
cUserName.setMaxAge(120);
cPassword.setMaxAge(120);
cVirtualCheck.setMaxAge(120);
((HttpServletResponse)(fc.getExternalContext().getResponse())).addCookie(cUserName);
((HttpServletResponse)(fc.getExternalContext().getResponse())).addCookie(cPassword);
((HttpServletResponse)(fc.getExternalContext().getResponse())).addCookie(cVirtualCheck);
}
else
{
virtualCheck="false";
Cookie cVirtualCheck = new Cookie("cVirtualCheck", virtualCheck);
((HttpServletResponse)(fc.getExternalContext().getResponse())).addCookie(cVirtualCheck);
}
}
return "always";
}
public void isChecked()
{
FacesContext fc=FacesContext.getCurrentInstance();
Cookie cookiesArr[]=((HttpServletRequest)(fc.getExternalContext().getRequest())).getCookies();
if(cookiesArr!=null&&cookiesArr.length>0)
for (int i = 0; i < cookiesArr.length; i++) {
String cName=cookiesArr[i].getName();
String cValue=cookiesArr[i].getValue();
System.out.println("---cValue----"+cValue);
if(cName.equals("cUserName"))
{
setuName(cValue);
}else if(cName.equals("cPassword"))
{
setPassword(cValue);
}else if(cName.equals("cVirtualCheck"))
{setVirtualCheck(cValue);
if(getVirtualCheck().equals("false"))
{
setCheckBox(false);
setuName(null);
setPassword(null);
}
else if(getVirtualCheck().equals("true"))
{System.out.println("here in line110");
setCheckBox(true);
}
}
}
{
}
}
}

Explanantion :-
  • submit() method is linked to submit button in RememberMe.jsp
    Here in this method we set the cookies for username,password and check box,if remember me check box is clicked
    Cookie cUserName = new Cookie("cUserName", uName);
    Cookie cPassword = new Cookie("cPassword", password);
    Cookie cVirtualCheck = new Cookie("cVirtualCheck", virtualCheck);
Here we are creating Cookie objects

Below setting age of a cookie in seconds
    cUserName.setMaxAge(24*60*60);
    cPassword.setMaxAge(24*60*60);
    cVirtualCheck.setMaxAge(24*60*60);

Below adding cookies to response
    ((HttpServletResponse)(fc.getExternalContext().getResponse())).addCookie(cUserName);
    ((HttpServletResponse)(fc.getExternalContext().getResponse())).addCookie(cPassword);
    ((HttpServletResponse)(fc.getExternalContext().getResponse())).addCookie(cVirtualCheck);

Then in the bean constructor we are invoking a method called isChecked()

This method will check if already exact cookie is there.If cookies are there then we will retrive their values based on their names and assign it respective fields.
Cookie cookiesArr[]=((HttpServletRequest)(fc.getExternalContext().getRequest())).getCookies();
if(cookiesArr!=null&&cookiesArr.length>0)
for (int i = 0; i < cookiesArr.length; i++) {
String cName=cookiesArr[i].getName();
String cValue=cookiesArr[i].getValue();
System.out.println("---cValue----"+cValue);
if(cName.equals("cUserName"))
{
setuName(cValue);
}else if(cName.equals("cPassword"))
{
setPassword(cValue);
}else if(cName.equals("cVirtualCheck"))
{setVirtualCheck(cValue);
if(getVirtualCheck().equals("false"))
{
setCheckBox(false);
setuName(null);
setPassword(null);
}
else if(getVirtualCheck().equals("true"))
{System.out.println("here in line110");
setCheckBox(true);
}

Ouptput :-

with out checking remember me check box


With checking remember me check box


Note :- in order to save password browser will ask/prompt user to save password or not
Irrespective of Java web technologies and browsers setting and retrieving cookies will play a major role
In eclipse web.xml and faces-config.xml will be automatically created
If we want to delete a cookie,the simplest method is to set its maximum age to zero seconds

Some of the popular posts are :-



Happy Learning

Please provide your valuable comments on this article and share it across your network.



Thursday, June 20, 2013

Prepared Statement-Preventing SQL injections

Hi All,

Welcome to Java-recent.

In this post we will discuss about Prepared Statement-used to execute sql queries from Java.

Lets get into more details.

Prepared Statement :-
  • is an interface from java.sql.PreparedStatement
  • is used to execute queries,set values in a query
  • Prepared statement queries are precompiled and the fetch plan will be stored in cache,so for subsequent requests only execution will happen
  • They are faster than Statement queries because Statement queries will get compiled every time
  • Used in case there is repetetion of a query
  • Prepared statements can be parameterized,parameterization of query values is done by using '?' - place holder in setXXX() method
  • Prepared Statement prevents SQL injection
Syntax :-There are two ways of using prepared statement
1.PreparedStatement preparedStatement = connection.prepareStatement("select * from COMPANY where sid="+"'"+emailId+"'");

2. PreparedStatement preparedStatement = connection.prepareStatement("select * from COMPANY where sid=? AND name=?");
preparedStatement.setInt(1, 101);
preparedStatement.setString(2, "Google");

setXXX() -- takes two parameters first one tells position of the value to be placed,
this starts from 1 .
Second parameter is the respective value to be passed for ?-place holder

The first type of declaration will not prevent SQL injections because we are hardcoding the where clause with a variable.
Second type of declaration will prevent SQL inection because all the parameters passed will be escaped by JDBC

Example Code:- There is a webpage which takes user name as input and pass it into servlet
Servlet retrives emailId as per user name from DB

Design.java
@WebServlet("/Design")
public class Design extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String uName=request.getParameter("name");
Connection conn=null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
//Creating connection object
conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","admin");
String query="select mail from COMPANY where name="+"'"+uName+"'";
PreparedStatement statement =conn.prepareStatement("select mail from COMPANY where name=?1");
statement.setString(1, uName);
System.out.println("query--------"+query);
ResultSet rs= statement.executeQuery(); //Executing query
//List ls=(List) rs;
//System.out.println(ls);
PrintWriter out=response.getWriter();
out.println("<head><body>");
while(rs.next())
{
String emailID= rs.getString("MAIL");
out.println("<h4>"+emailID+"</h4><br>");
}
out.println("</body></head>");
}catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Submit.html
<form action="Design">
Enter name <input name="name"/><br/>
<input type="submit" value="click here to get details"/>

</form>


Here we have used place holder for passing values '?'
conn.prepareStatement("select mail from COMPANY where name=?1");
statement.setString(1, uName);
Case1 :- when we enter value as Google in the form and submit



we will get output as google@gmail.com

Case2 :- Now we will provide some special characters in the form as
' OR '1'='1



Now the resultset will be empty,because the statement ResultSet rs= PreparedStatement.executeQuery(); will remove the escape characters. So unlike in previous post SQLinjection it will not return entire results.








Happy Learning

Please provide your valuable comments on this article and share it across your network.


Like and Share