Showing posts with label J2EE. Show all posts
Showing posts with label J2EE. Show all posts
Saturday, July 5, 2014
Today I am going to discuss with the first step of JPA - Java Persistence API. JPA helps you in object-relational mapping and reduces a lot of task of coders, otherwise they have to write a lot of JDBC codes. All those things are done automatically by the Persistence provider. Throughout all the topics related to JPA that we will cover will consider EclipseLink as the JPA provider.
    After all necessary setups, the first thing you will have to do is to write a JPA entity. Many IDE like Eclipse can automatically create it, but we will show how to write it and what are the steps. You must have seen the JavaBean style classes. Here our first task is to write a class in that style only. Next we will make some modifications to make it a JPA entity.
Sunday, September 15, 2013
Today I am going to show you how you can generate and validate captcha. A CAPTCHA (an acronym for "Completely Automated Public Turing test to tell Computers and Humans Apart"), a trademark of Carnegie Mellon University, is a type of challenge-response test used in computing to determine whether or not the user is human. This requires the user to type the letters of a distorted image, sometimes with the addition of an obscured sequence of letters or digits that appears on the screen. Because the test is administered by a computer, in contrast to the standard Turing test that is administered by a human, a CAPTCHA is sometimes described as a reverse Turing test. This test is most common when someone registers or opens a new account in any website.
       Here we will be using jcaptcha library for captcha generation and validation. In our demo we will follow MVC architecture to carry this out. We have the following classes, servlets and JSPs in our project.

  • login.jsp : This is the home page. Here the captcha challenge image will be shown with a text-box to enter the characters.  On submitting it is validated by a servlet.
  • CaptchaService class : This is a singleton class that is responsible for generating the instance that will help in generating the challenge image.
  • CaptchaGeneratorServlet class : this servlet has a GET method which generates the image with CaptchaService class and converts it to a byte array and then writes to the output stream. The image is generated using the session id of the user which is used as the captcha id.
  • CaptchaVerifierServlet class : It has a POST method which receives the input characters from usere and validates it. The result is returned as a boolean which is set as a session attribute and for the result to be shown it is forwarded to a JSP.
  • results.jsp : It extracts the session attribute and displays result according to that.


-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
/* Code for login.jsp */
<!DOCTYPE html>
<html>
<head>
<title>JCaptcha Demo</title>
</head>
<body>
   <h2>JCaptcha Demo</h2>
   <form action="captcha-verifier" method="post">
      <input type="hidden" name="captchaID" value="<%= session.getId() %>"/>
      <table><tr>
           <td valign="middle">Enter these letters:<br/>
           <img src="./captcha-generator" align="middle" alt="Enter the 
             characters appearing in this image" border="1"/></td>
           <td><input type="text" name="inChars"/></td>
         </tr>
         <tr>
           <td><input type="submit" value="Submit"/></td>
         </tr>
      </table>
   </form>
</body>
</html>


/* Code for CaptchaService.java */
package java_code_house.jcaptcha;

import com.octo.captcha.service.image.ImageCaptchaService;
import com.octo.captcha.service.image.DefaultManageableImageCaptchaService;

public class CaptchaService{
    // a singleton class
    private static ImageCaptchaService instance = new DefaultManageableImageCaptchaService();
    
    public static ImageCaptchaService getInstance(){
     return instance;
    }

}



/* Code for CaptchaGeneratorServlet.java */
package java_code_house.jcaptcha;

import com.octo.captcha.service.CaptchaServiceException;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/captcha-generator")
public class CaptchaGeneratorServlet extends HttpServlet{
 private static final long serialVersionUID=1L;
 
 protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
  ByteArrayOutputStream imgStream = new ByteArrayOutputStream();
  byte[] captchaBytes=null;

   try{
   // Session ID is used to identify the particular captcha
   String captchaId = request.getSession().getId();
   // Generate the captcha image
   BufferedImage img = CaptchaService.getInstance().getImageChallengeForID(
     captchaId, request.getLocale() );
   ImageIO.write(img, "jpeg", imgStream );
   captchaBytes = imgStream.toByteArray();

    // Clear any existing flag
   request.getSession().removeAttribute("result");
  }catch( CaptchaServiceException|IOException ex ) {
   System.out.println(ex);
  }

   // Set appropriate http headers
  response.setHeader( "Cache-Control", "no-store" );
  response.setHeader( "Pragma", "no-cache" );
  response.setDateHeader( "Expires", 0 );
  response.setContentType( "image/jpeg");

   // Write the image to the client
  OutputStream os = response.getOutputStream();
  os.write(captchaBytes);
  os.flush();
  os.close();
 }

}



/* Code for CaptchaVerifierServlet.java */
package java_code_house.jcaptcha;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.octo.captcha.service.CaptchaServiceException;

@WebServlet("/captcha-verifier")
public class CaptchaVerifierServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;

  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // Get the request params
  String cId = request.getParameter("captchaID");
  String inChars = request.getParameter("inChars");

   // Validate whether input from user is correct
  boolean hasPassed = validateCaptcha(cId, inChars );
  
  // Set flag into session
  request.getSession().setAttribute( "result", new Boolean(hasPassed) );

   // Forward request to results page
  request.getRequestDispatcher( "/results.jsp" ).forward( request, response );
 }

  private boolean validateCaptcha( String captchaId, String inputChars ){
  boolean b = false;
  try{
   b = CaptchaService.getInstance().validateResponseForID( captchaId, inputChars );
  }catch( CaptchaServiceException cse ){}
  return b;
 }

}



/* Code for results.jsp */
<!DOCTYPE html> 
<html>
<head>
<title>JCaptcha Demo - Result</title>
</head>
<body>
    <% Boolean b = (Boolean)session.getAttribute("result");
        if ( b!=null && b.booleanValue() ){
    %>
             Congrats!  You passed the Captcha test!
    <% } else { %>
             Sorry, you failed the Captcha test.
    <% } %>
</body>
</html>

-------------------------------------------------------------------------------------------------------------------------
Download Links
-------------------------------------------------------------------------------------------------------------------------
NOTE : While exporting the project from eclipse, optimization for Apache Tomcat v7 was done. Also it includes the source files as well as the jar files required to execute this.

Happy coding :)
Wednesday, July 24, 2013
Today I will show you how you can use the power of filters to do session tracking. We will create a special type of filter here that will do session tracking. You people must have experienced that when you visit some websites(like facebook,twitter etc) you cannot access all the pages until you are logged in. Today we will implement this feature. We will write a session filter that checks for a certain attribute in the session object to see whether the user is already logged in or not. If the user is logged in then he can access those pages otherwise will be redirected to the home page. Here the filter will act as a phantom and intercept the request and according to that send the response.
   Here we will consider that as soon as the user logs in a attribute named "user" is set with object of some User class that contains all user details using methods getSession(false) and getAttribute(). So we will test whether taht attribute exists or not. If it exists then he will be able to access the requested page, otherwise will be redirected to login page using sendRedirect().
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class SessionFilter implements Filter {

public void destroy() {
System.out.println("SessionFilter destroyed");
}

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req=(HttpServletRequest)request;   //casting
HttpServletResponse res=(HttpServletResponse)response;
HttpSession session=req.getSession(false);  //getting session object
if(session!=null){
   Object usr=session.getAttribute("user");  //getting attribute
   if(usr==null){  //if its null then not logged in
   System.out.println("Invalid Session");
   res.sendRedirect("./login.jsp");  //redirecting to login page
   }
   else
       chain.doFilter(req, res);  //permitting to access if logged in
}
else
    res.sendRedirect("./login.jsp");  //redirecting if no session object
}

public void init(FilterConfig fConfig) throws ServletException {
System.out.println("SessionFilter initialized");
}
}

NOTE : If you are using servlet 3.0 then mention the url's for which you want to add this filter using WebFilter annotation. But if you are using Servlet2.5 then use the <filter-mapping> tag in web.xml to map this filter to url's. So depending on your web-app use the different way you want , so I am not mentioning it in my code.
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------
Saturday, May 4, 2013
Today I will tell you how you can get the parameter values submitted by a client to a server using servlets. Here you will see different process of extracting the form parameters depending on your requirements. Here we will use getParameter() , getParameterValues() , getParameterNames() and getParameterMap() methods.
 getParameter() : This method returns only a single value associated with the parameter name. This is generally used when you have only one value for a parameter.
getParameterValues() : It returns an array of all values associated with a parameter name. This is used when you have multiple values for a parameter.
getParameterNames() : It returns an Enumeration<String> which are the different parameter names. Now you can use individual name and extract the values. This is used when you dont know the param names. But in reality you will always know them from beforehand.
getParameterMap() : It returns a Map of parameter names mapped to all values associated with each parameter. This is the most general case.
--------------------------------------------------------------------------------------------------------------------------
Servlet Source Code
--------------------------------------------------------------------------------------------------------------------------
import java.util.Map;
import java.util.Set;
import java.util.Iterator;
import java.util.Enumeration;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebServlet;

@WebServlet("/paramReader")
public class ParamReader extends HttpServlet{
   public void doGet(HttpServletRequest req,HttpServletResponse res){
        //used when one parameter has only one value
String fn=req.getParameter("fn");

//used when one parameter has more than one vakue
String str[]=req.getParameterValues("fn");  //getting all values

//used when parameter names are unknown
Enumeration<String> en=req.getParameterNames();  //getting all names
while(en.hasMoreElements())
          req.getParameter(en.nextElement());  //getting vakue
     
      //used to get whole map
Map<String,String[]> m=req.getParameterMap();
Set<String> s=m.keySet();  //key set means param names
Iterator<String> it=s.iterator();
while(it.hasNext())
          m.get(it.next());  //param values
   }
}
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared
Sunday, February 17, 2013
I have already posted how you can upload a file to server with servlet. Today I will post how to download a file from server with servlet. You know how to send HTML data to client. But there may be situation where client may want to download a file hosted by server. So, here I will write the servlet code that will send the file to the client. The two important things that you will have to remember are :
  • MIME type : You will have to set the content type. This is necessary as Container has no idea about type of file. If the type is set then the browser will automatically open the file in client's default application for that particular type.This is done using response.setContentType() method which takes in MIME type as parameter.
  • I/O stream : You will have to use OutputStream and not PrintWriter. This is because we will be sending binary data and not HTML. This is done using response.getOutputStream() method which returns a reference to the object of java.io.OutputStream.
Screenshot of output
Output as seen in Firefox
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.ServletContext;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/a/b/download")
public class Downloader extends HttpServlet{

    @Override
    public void doGet(HttpServletRequest req,HttpServletResponse res){
        res.setContentType("application/pdf"); //setting MIME type
        ServletContext ctx = getServletContext();
        
        try{
            //getting stream to file
            InputStream is = ctx.getResourceAsStream("/ALG_3rd.pdf");
            int read = 0;
            byte[] bytes = new byte[1024]; //setting buffer
            OutputStream os = res.getOutputStream();  //getting stream

            while ((read = is.read(bytes)) != -1) //reading file
               os.write(bytes, 0, read);  //writing to stream

            os.flush();  //closing streams
            os.close();
        }catch(Exception e){}
    }
}


--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the project archive from Mediafire
DOWNLOAD the project archive from 4shared
NOTE : The archive does not contain the pdf. So remember to add it while using it.
Sunday, November 25, 2012
Everyone of you know that files are being uploaded to the server and you can easily download them. You must have thought of how these files are being uploaded to server. Today I am going to post how you can very easily create your own file upload server; Previously before Servlet3.0 technology you might have seen that it was a bit difficult process and you had to use third-party library like Apache-commons. But now it has become very easy.
  • The first thing you will have to do is to create the upload-form using HTML. In the form you will have to mention the enctype="multipart/form-data" .
  • In servlet there is an annotation called MultipartConfig . It has different params like location, maxFileSize and so on. The location should be a valid folder path on server where the file will be uploaded. Now write the part and also do string processing to get the name of the file ro use the same name while uploading it.
  • Now display the details of the file uploaded by request forwarding to a JSP.
--------------------------------------------------------------------------------------------------------------------------
HTML form and code
--------------------------------------------------------------------------------------------------------------------------
Select a file to upload

<html>
  <body>
     <h3>File Upload Form</h3>
      Select a file to upload
      <form action="./upload.html" method="post"
                enctype="multipart/form-data">
            <input type="file" name="file" size="50" />
            <br/>
            <input type="submit" value="Upload File" />
      </form>
  </body>
</html>
--------------------------------------------------------------------------------------------------------------------------
 Servlet and JSP Code
--------------------------------------------------------------------------------------------------------------------------
/* Servlet Code */
import java.io.IOException;
import java.util.Collection;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@WebServlet("/upload.html")
@MultipartConfig(location="D:/ Documents",fileSizeThreshold=1024*1024,
maxFileSize=50*1024*1024,maxRequestSize=5*1024*1024*1024)

public final class Uploader extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Collection<Part> parts=request.getParts();
        StringBuffer sb=new StringBuffer();
        sb.append("<h2>Total "+parts.size()+" parts uploaded</h2>");
       
        for(Part p: parts){
            getDetails(sb, p);
            p.write(getFileName(p)); 
//writing file to server
        }
       
        request.setAttribute("partDetails",sb);
        RequestDispatcher view=request.getRequestDispatcher("result.jsp");
        view.forward(request, response); 
//forwarding to JSP
    }
   
    private String getFileName(Part p){
        String header=p.getHeader("content-disposition");
        String filename = header.substring(header.indexOf("filename=\"")).split("\"")[1]; 
//getting filename
       
        return filename;
    }
   
    private void getDetails(StringBuffer sb,Part p){
        sb.append("<p></p>");
        for(String header:p.getHeaderNames()){
            sb.append("<b>"+header+" : </b>");
            sb.append(p.getHeader(header)+"</br>");
        }
    }
}

/* JSP Code */

<html>
    <head><title>Upload Details</title></head>
    <% StringBuffer result=(StringBuffer)request.getAttribute("partDetails");

Output as seen in Chrome
     %>
    <body>
        <%= result %>
    </body>
</html>




--------------------------------------------------------------------------------------------------------------------------
DOWNLOAD LINKS
--------------------------------------------------------------------------------------------------------------------------
Friday, October 26, 2012
--------------------UPDATE-------------------
I have updated my post so that now it can detect IE 11. This modification was necessary as the user-agent of Internet Explorer 11.0 was changed. So check the new code which has an additional if-else block in class BrowserRecognitionModel .
---------------------------------------------------
Today I am going to post program which will be able to detect client's browser details i.e. browser name and version using servlets and JSPs. First of all, user-agent header is extracted and then string processing is done to obtain browser name and version.
Benefits : You will be able to detect which browser is being used by client. Moreover the whole application is being written following the MVC pattern.
BrowserRecogntionServlet.java : contains the code for extracting user-agent and hands it over to the model class and then forwards the result to the JSP and thus acting as controller.
BrowserRecognitionModel.java : contains the code that processes the string and gets the browser version and name.
 browserDetails.jsp : contains the code for showing result.

 Screenshots of output as seen in Chrome and Firefox :
Output in Chrome

Output in Firefox








--------------------------------------------------------------------------------------------------------------------------
SOURCE CODE
--------------------------------------------------------------------------------------------------------------------------
/* Code for servlet(BrowserRecogntionServlet.java) */
package detector.servlets;

import detector.model.BrowserRecognitionModel;
import java.io.PrintWriter;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebServlet;

@WebServlet("/detect.html")
public class BrowserRecognitionServlet extends HttpServlet{
    @Override
    public void doGet(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException{
        String userAgent=req.getHeader("user-agent");
        /*passing data to model class */
        BrowserRecognitionModel browserDetails=new BrowserRecognitionModel(userAgent);
        /* setting attribute to request for the JSP */
        req.setAttribute("model",browserDetails);
        /* forwarding to JSP for output */
        RequestDispatcher view=req.getRequestDispatcher("/browserDetails.jsp");
        view.forward(req,res);
        }
}

/* Code for model class(BrowserRecognitionModel.java) */
package detector.model;

public class BrowserRecognitionModel {
    private String userAgent,browserName,browserVer;
    public BrowserRecognitionModel(String userAgent){
        this.userAgent=userAgent;
        process();
    }
    private void process(){
        browserName="unknown";
        browserVer="unknown";
        if(userAgent.contains("Chrome")){ //checking if Chrome
            String substring=userAgent.substring(userAgent.indexOf("Chrome")).split(" ")[0];
            browserName=substring.split("/")[0];
            browserVer=substring.split("/")[1];
        }
        else if(userAgent.contains("Firefox")){  //Checking if Firefox
            String substring=userAgent.substring(userAgent.indexOf("Firefox")).split(" ")[0];
            browserName=substring.split("/")[0];
            browserVer=substring.split("/")[1];
        }
        else if(userAgent.contains("MSIE")){ //Checking if Internet Explorer
            String substring=userAgent.substring(userAgent.indexOf("MSIE")).split(";")[0];
            browserName=substring.split(" ")[0];
            browserVer=substring.split(" ")[1];
        }
        else if(userAgent.contains("rv")){ //checking if Internet Explorer 11
     String substring=userAgent.substring(userAgent.indexOf("rv"),userAgent.indexOf(")"));
     browserName="IE";
     browserVer=substring.split(":")[1];
 }
    }
    public String getName(){
        return browserName; //returning browser name
    }
    public String getVersion(){
        return browserVer;  //returning browser version
    }
}

/* Code for JSP(browserDetails.jsp) */
<html>
<head><title>Browser Details</title></head>
<%@ page import="detector.model.BrowserRecognitionModel" %>
<body>
  <h1>Browser Details</h1>
  <%
    BrowserRecognitionModel model=(BrowserRecognitionModel)request.getAttribute("model");
    String browserName=model.getName();
    String version=model.getVersion();
  %>
  <b>Browser Name : </b><%= browserName %></br>
  <b>Browser Version : </b><%= version %>
</body>
</html>

--------------------------------------------------------------------------------------------------------------------------
DOWNLOAD LINKS
--------------------------------------------------------------------------------------------------------------------------
 DOWNLOAD the application(rar) from Mediafire
 DOWNLOAD the application(rar) from 4shared
Monday, October 8, 2012
Today I am going to post a program that will be able to show all the headers associated with a servlet request;  Here in the code request object is used to get an enumerations of headers associated with the request of the client. Then with a loop one by one all the headers are extracted and their corresponding values are available using the getHeader(String headername) method. All these headers and their values are sent to the client as a dynamically generated html. Also note that the values will differ according to the browser which has been used to send the request.
Screenshot of output as seen on Chrome in Windows7
Here is the code for you -->

import java.io.PrintWriter;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebServlet;

@WebServlet("/header.html")
public class HeaderViewer extends HttpServlet{

   public void doGet(HttpServletRequest req,HttpServletResponse res)throws IOException,ServletException{
          Enumeration headers=req.getHeaderNames(); 
/*getting enumerations of all headers */
          PrintWriter out=res.getWriter(); 
//getting writer
          out.write("<html><head><title>HeaderViewer</title></head>");
          out.write("<body><h1><center>Headers associated with your request</center></h1>");
         
          while(headers.hasMoreElements()){
                 String header=(String)headers.nextElement(); 
/*extracting header */
                 out.write("</br><b>"+header+" : </b>"+req.getHeader(header));
/* sending header name and its value to client */
          }
          out.write("</body></html>");
          out.close();
   } 
}
Sunday, October 7, 2012
Today I am going to post a hello world servlet program that uses latest Servlet3.0 technology. For all new users of this technology, I would like to mention that deploying your web-app has been made easy. With this technology you can use annotations to set the URL of your web-app now, which was only possible through deployment descriptor in their previous versions. So here I will post the simplest code to show how to use this method.

import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;


/*http://localhost:8080/def/a/b/simple.html is the complete url when your server is running at port 8080 and your app directory is def */

@WebServlet("/a/b/simple.html") //this is relative URL
public class SimpleServlet extends HttpServlet {

   
    @Override
    public void doGet(HttpServletRequest req,HttpServletResponse res){

       try{
        PrintWriter out = res.getWriter();
/* getting writer yo send dynamic data to client */
        out.println(
            "<html><head><title>Servlet Demo</title></head><body> <h1><center>Hello World</center></h1></body></html>"); 
//sending html data
        out.close();
//closing writer
        }catch(Exception e){ e.printStackTrace();  }
    }

}

Note that we are not mapping servlet in DD but using annotation for that. The URL we are giving is a relative one and false. Client cannot access the file directly as it is inside WEB-INF directory. Also it is written in such a way that client will think its a static html page whereas it is a dynamically generated html by servlet behind the curtain. So we are achieving url hiding and deployment in a very easier way. So try it out guys.

Total Pageviews

Followers


Labels

Popular Posts

free counters