Showing posts with label JSP. Show all posts
Showing posts with label JSP. Show all posts

Sunday, 24 April 2016

How to initialize the common connection before any Servlet / JSP will be accessed ?


Scenario
I need to initialize the common connection before any servlet / jsp will be accessed.

Solution
Make the connection in a context listener and save it.

Example
public class MyServletContextListener implements ServletContextListener {
  public void contextInitialized(ServletContextEvent event) {
     ServletContext sc = event.getServletContext();
     // Make connection and put connection object in servlet context
  }

  public void contextDestroyed(ServletContextEvent event) {
     // Clean up code here

  }

}

Saturday, 23 April 2016

What is the main advantage of JSP over Servlet ?


Separation of concerns
Avoids embedding Java code in HTML pages

How to download images from database in JSP ?


Download images from database in JSP
1) Create a webpage "imageDownload.jsp"  to display and download the image from database. All images will show as hyperlink image.
2) Another "image.jsp" is used to retrieve image.

Implementation
Step 1. To create a "imageupload" table in Database
CREATE TABLE 'imageupload' (
 'id' bigint(20) NOT NULL auto_increment,
 'imagefile' blob NOT NULL,

 PRIMARY KEY ('id'))

Step 2. To create a web page  "image.jsp" 
<%@ page import="java.sql.*,java.io.*,java.util.*" %>
<%
String connectionURL = "jdbc:mysql://localhost:3306/userdetails";

if(request.getParameter("imgid")!=null && 
    request.getParameter("imgid")!="")
{
  int id =  Integer.parseInt(request.getParameter("imgid"));
  String filename = "image"+id+".jpg";
  Connection con = null;

  try{     
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    con = DriverManager.getConnection(
                                  connectionURL,"root","root");      
    Statement st1 = con.createStatement();
    String strQuery = "select imagefile from imageupload 
                        where id=" + id;
   
    ResultSet rs1 = st1.executeQuery(strQuery);

    String imgLen="";
    if(rs1.next()) {
      imgLen = rs1.getString(1);
     } 
   
    rs1 = st1.executeQuery(strQuery);
    if(rs1.next()) {
      int len = imgLen.length();
      byte [] rb = new byte[len];
      InputStream readImg = rs1.getBinaryStream(1);
      int index = readImg.read(rb, 0, len); 
      st1.close();
      response.reset();
      response.setContentType("image/jpg");
      response.setHeader("Content-disposition",
                           "attachment; filename=" +filename);
      response.getOutputStream().write(rb, 0, len);
      response.getOutputStream().flush();       
    }
  }
  catch (Exception e) {
    e.printStackTrace();
  }
}

%>

Step 3. To create a "imageDownload.jsp"
<%@ page import="java.sql.*,java.io.*,java.util.*" %>
<HTML>
 <HEAD>  <TITLE>Download Images</TITLE>  </HEAD>
 <BODY>
   <br><br>
  <table align="center" border=0 width="200px">
   <tr>
    <td colspan=2 align="center"><b>Download Images</b></td>
  </tr>
  <tr><td colspan=2>&nbsp;</td></tr>
  <%
  String connectionURL = "jdbc:mysql://localhost:3306/userdetails";
  Connection conn = null;
  try {     
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    conn = DriverManager.getConnection(connectionURL,"root","root");
    Statement stmt = conn.createStatement();
    String strQuery = "select id from imageupload";
   
    ResultSet rs = stmt.executeQuery(strQuery);
    int sno=0;
    while(rs.next())
    {
      sno++;
  %>

  <tr style="background-color:#efefef;" mce_style="background-
        color:#efefef;" mce_style="background-color:#efefef;">
      <td><b><%=sno%></b></td>
      <td align="center">
         <a href="image.jsp?imgid=<%=rs.getInt(1)%>" 
          mce_href="image.jsp?imgid=<%=rs.getInt(1)%>" 
          mce_href="image.jsp?imgid=<%=rs.getInt(1)%>">
             <img src="image.jsp?imgid=<%=rs.getInt(1)%>" 
               mce_src="image.jsp?imgid=<%=rs.getInt(1)%>" 
               width="50" height="50">
          </a>
       </td>
      </tr>
  <%
    }
    rs.close();
    con.close();
    stmt.close();
  }
  catch(Exception e)  {
    e.getMessage();
  }
  %>
 </table>
</BODY>

</HTML>

Friday, 22 April 2016

How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it ?


You can make your JSPs thread-safe by having them implement the
SingleThreadModel interface.

This is done by adding the directive <%@ page isThreadSafe="false" %> within your JSP page.

With this, instead of a single instance of the servlet generated for your JSP page loaded in memory, you will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized.

You can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for your JSP engine.

More importantly, avoid using the tag for variables. If you do use this tag, then you should set is ThreadSafe to true, as mentioned above. Otherwise, all requests to that page will access those variables, causing a nasty race condition.

SingleThreadModel is not recommended for normal use.
There are many pitfalls, including the example above of not being able to use <%! %>

You should try really hard to make them thread-safe the old fashioned way: by making them thread-safe.

What's a better approach for enabling thread-safe servlets and JSPs : SingleThreadModel or Synchronization ?


Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well.
If you anticipate your users to increase in the future, you may be better off implementing explicit synchronization for your shared data.

The key however, is to effectively minimize the amount of code that is synchronzied so that you take maximum advantage of multithreading. 

Also, note that SingleThreadModel is pretty resource intensive from the server's perspective.
The most serious issue however is when the number of concurrent requests exhaust the servlet instance pool.
In that case, all the unserviced requests are queued until something becomes free - which results in poor performance.

Since the usage is non-deterministic, it may not help much even if you did add more memory and increased the size of the instance pool.

Thursday, 14 April 2016

How to export data in a file(txt , xls etc) from JSP ?


STEP 1. Make a link in JSP
<li>
 <a href="export_perform.action" mce_href="export_perform.action">
    Export file
  </a>
</li>


STEP 2. Define the action in Struts.xml with input name property
<action name="export_*" method="{1}" class="com.actions.ExportAction">
  <result name="download" type="stream">
    <param name="contentType">application/octet-stream</param>
    <param name="inputName">fileInputStream</param>
    <param name="contentDisposition"> 
         attachment;filename="fileABC.txt" 
    </param>
    <param name="bufferSize">1024</param>
</result>
</action>


STEP 3. Make an action method in Action Class (ExportAction.java)

FileInputStream fileInputStream;
// getter and setter of fileInputStream property

public String execute() {
  // Generate and write to file
  String filePath = "C:\\abc.txt";
  FileWriter fileWriter;
  try {
fileWriter = new FileWriter(new File(filePath));
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("content line-1");
bufferedWriter.newLine();
bufferedWriter.write("content line-2");
  } catch(Exception e) { }
    bufferedWriter.flush();
    fileWriter.flush();
    bufferedWriter.close();
    fileWriter.close();
    // Set the stream in property to be downloaded

  try {
    fileInputStream = new FileInputStream(new File(filePath));
  } catch (FileNotFoundException e) {
    e.printStackTrace();
  } catch (IOException e) {
    e.printStackTrace();
  }

  return "download";  // return the stream result
}