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

Monday, 8 October 2018

File listing and download using hyperlink in JSP from any folder.

Why I am writing this blog? In network some times we don't have server/FTP server(I personally think that it is not more interactive, i.e it can't be in a form of web page) and we have to share any file/s to more than 50 people, then we stuck in messages like "No more connections can be made.. bla bla bla" or either network restriction policy don't allow to do so. Apart from this there may be other issues that can stop to access shared folders in network. I have seen all these kind of problem in accessing shared documents.

So I tried to make web page like application where user can view and download their files via web page. For that you require obviously Tomcat Server for running JSP pages.

So, you should have working knowledge of Tomcat Server.

Create a JSP page and save in your project directory and use this code.

   <p><% 
File folder = new File("G:\\tomcatserver\\webapps\\softshare\\share\\fonts");
File[] listOfFiles = folder.listFiles();
%><table><%
     for (int i = 0; i < listOfFiles.length; i++) {
      if (listOfFiles[i].isFile()) {
String pp="share/fonts/"+listOfFiles[i].getName();
%><tr><td width="500px"><a href="<%=pp%>"><%=listOfFiles[i].getName()%></a><%
   %></td><td><%
Path path=Paths.get(listOfFiles[i].getPath());
BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
out.println(attr.creationTime().toString().substring(0,10));
out.println(" </td></tr>");
      }
    }
%></table><%
 %></p>

Now lets see the code in details-

File folder = new File("G:\\tomcatserver\\webapps\\softshare\\share\\fonts"); //path of folder
File[] listOfFiles = folder.listFiles(); // will store file in array.

This code will read the files of fonts/ folder. The font folder should be in your project directory, it should not be out your tomcat server.

 String pp="share/fonts/"+listOfFiles[i].getName();

pp will store the relative path of files.

Now you will be able to list and download your file via hyperlink.

Monday, 18 June 2018

Run your JSP page as Servlet.

Developing JSP page is easier than Servlet. But Servlet has some benefit over JSP. So if we want to run Servlet by developing our page in JSP then we can do it very easily. Although we know that all JSP page is first converted into Servlet and then run. But it makes JSP slower than Servlet. Since Servlet is written in Java while JSP is written in HTML, so it becomes difficult to design in Servlet. Another headache with Servlet that it requires compilation after every changes in code.

Servlets are best suited for large data processing and manipulation. It can also be best suited where you don't want reveal your file name without using any platform.

So if we want develop our page in JSP because of easiness in design, custom tags for calling Beans and use of JavaScript and run it as Servlet because of speed and processing then we can do it in following way:-

I assume that you have good idea of running Servlet on Apache Tomcat Server.

Create your JSP page/project on any of your favourite IDE with your desired design and save it to your project root directory. Now run this page on your server. If it is OK then do the following-

1. Go to Tomcat home folder ------> Work --------> Catalina ----------> localhost

Here you will see your project folder. Inside this folder you will find org folder.
In org folder, there is another folder apache and then jsp folder. In this jsp folder you will see the all Servlet  with the name of your JSP page you have created in your project. These Servlets are created when you run your JSP page on browser (as you know that all JSP are first converted into Servlet before run on browser).

2. Copy this folder (org) to your project/WEB-INF/classes location.

Now in your web.xml, do the Servlet configuration like this.

<servlet>
<servlet-name>sm</servlet-name>
      <servlet-class>org.apache.jsp.home1_jsp</servlet-class>
</servlet>

<servlet-mapping>
        <servlet-name>sm</servlet-name>
        <url-pattern>/sm.arv</url-pattern>
 </servlet-mapping>

If your server is capable of running Servlet, it will also run.

Like this you can convert your all pages/project in Servlet.

Advantages:-

This kind of work can also hide your business logic of your coding from others when you have to distribute your project or share with others.

Also you can design your page in JSP and run as Servlet and you don't need to compile it everytime (for compilation just run JSP page automatically it will be compiled).

You can also hide your file extension (.htm, .html, .jsp).


Monday, 12 September 2016

Ajax search from MYSQL database example in JSP

Ajax is used to get data dynamically by just pressing key. This example is the demonstration of getting data from database by just typing characters in textfield. In ajax you don't need to press submit button to get data. I assume that you have made MySQL database.

Now create a form that contains textfield.

search.html

To type something to be searched

<form name="vinform"  method="get" >
<input type="search" name="t1" size="80" placeholder="Type to search" onKeyUp="sendInfo()" class="textfieldsearch" style="height:35px;" autofocus>
</form>

To show data on this page add

<span id="arvind"> </span>

Include javascript code given bellow to this file

<script>
var request;
function sendInfo()
{
               var v=document.vinform.t1.value;
               var url="search.jsp?val="+v;

              if(window.XMLHttpRequest){
             request=new XMLHttpRequest();
             }
             else if(window.ActiveXObject){
             request=new ActiveXObject("Microsoft.XMLHTTP");
             }
             try
            {
              request.onreadystatechange=getInfo;
              request.open("GET",url,true);
              request.send();
             }
             catch(e)
            {
               alert("Unable to connect to server");
           }
}

function getInfo(){
          if(request.readyState==4){
          var val=request.responseText;
           document.getElementById('arvind').innerHTML=val;
           }
}
</script>


Now on search.jsp page write

search.jsp

<%@ page import="java.sql.*"%>

<%
String s=request.getParameter("val");
if(s==null || s.trim().equals("")){
out.print("Please Type anything to search");

}else{
out.println("<img src='ajax-loader.gif' alt='Searching'></img>");

String search=s;


try{

Statement stmt=null;
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/itcentre","root","aarvindd");

stmt = con.createStatement();
String sql="select * from table where cl_name like '%"+search+"%' " ;
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
out.println(rs.getString(1));
       out.println(rs.getString(2));

       }
rs.close();
stmt.close();
con.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}


%>

Thursday, 8 September 2016

Session management using user authentication in JSP/Servlet

AMAZON TV & APPLIANCES SALE
Session management is a very crucial technique to check whether authenticated user is using the service or not. Only login process is not enough to manage the authentication. System must be maintained to check every request from the authenticated user. It should be maintained till the user logout.

It means, system should maintain session on every page requested by user. We can see the very strict user authentication in bank websites.

In general, session management should check

  1. Whether user has pressed back button after logout and he/she can view the pages before logout, even he/she has logged out or not?
  2. Whether user can view pages by directly typing the URL in browser's address bar after loged out or not?
  3. Whether user can view pages from browser history or not?
  4. Whether user has pressed browser back button and not pressed back button provided by application, even he/she is logged in (Often in banking applications).

These are some aspects of session management, when we develop any application. This list may be increased.

Now look here, how we manage session using JSP/Servlet.
Create login page.

Login.jsp

<form id="form1" method="post" action="loginvalidate.jsp">
 <table width="835" height="217" border="1" align="center" bordercolor="" bgcolor="#C0EFDE">
        <tr>
          <td width="116" height="40">&nbsp;</td>
          <td colspan="2"><div align="center">
            <h4>Login</h4>
          </div></td>
          <td width="219">&nbsp;</td>
        </tr>
        <tr height="10">
          <td height="56">&nbsp;</td>
          <td width="200"><label>
            <div align="center">Username</div>
          </label></td>
          <td width="272"><label>
            <input name="username" type="text" size="35" style="height:30px;" placeholder="Enter Your Username" required />
          </label></td>
          <td>&nbsp;</td>
        </tr>
<tr height="10">
          <td height="61">&nbsp;</td>
          <td><label>
            <div align="center">Password</div>
          </label></td>
          <td><label>
            <input name="password" type="password" size="35" style="height:30px;" placeholder="Enter Your Password" required />
          </label></td>
          <td>&nbsp;</td>
</tr>
        
        <tr height="10">
          <td height="10">&nbsp;</td>
          <td><label>
            <div align="center">
              <label>              </label>
            </div>
          </label></td>
          <td><label>
            <input type="reset" name="Reset" value="Reset" />
            <input type="submit" name="Submit2" value="Submit" />
          </label></td>
          <td>&nbsp;</td>
        </tr>
        <tr height="10">
          <td height="10">&nbsp;</td>
          <td>&nbsp;</td>
          <td>&nbsp;</td>
          <td>&nbsp;</td>
        </tr>
  </table>
</form>

loginvalidate page check user from database and redirect to proper location.

loginvalidate.jsp

<%
       String username=req.getParameter("username");
String password=req.getParameter("password");
       Connection conn = null;
Statement stmt=null;
String user="";
String pass="";
String type="";
try
  {
Class.forName("com.mysql.jdbc.Driver");
conn =       DriverManager.getConnection("jdbc:mysql://localhost:3306/database","username","password");
//db.dbConnect();
stmt = conn.createStatement();
String sql="select username, password, type from users where username='"+username+"' and password='"+password+"'";
ResultSet rs = stmt.executeQuery(sql);
if(rs.next())
{
user=rs.getString(1);
pass=rs.getString(2);
type=rs.getString(3);
}
if(username.equals(user) && pass.equals(password) )
{
                         HttpSession session = req.getSession(true); 
                         session.setAttribute("user", username); 
                 session.setAttribute("type",type);
                if(type.equals("admin"))
                res.sendRedirect("../IT_JSF/admin/adminpanel.jsp");
                if(type.equals("normal"))
                res.sendRedirect("../IT_JSF/standerd/officehome.jsp");
}
else
{
                res.sendRedirect("../IT_JSF/login-failed.jsp");

}
rs.close();
stmt.close();
conn.close();
}
catch(Exception e)
{
                out.println(e);
}
%>


Now after successful logged in by user, check on every page that use is logged in or not by using code

if(session.getAttribute("user")!=null)
{
       //allow to view the page
       //your full page code
}
else
{
     //redirect to login page
}

Done !!!

Sunday, 4 September 2016

Send data with hyperlink via URL in JSP/JAVA

We all know that we send data to another page using form or using session variables. But, some time we have to send data to another page using hyperlink. Suppose, we have fetched data from database and made id as hyperlink and clicking on it we do some operation like edit, delete or some thing else.

Let's see how we can do it in simple JSP page.



Here you can see update and delete is associated with each record in the form of hyperlink.

Code is-

<td><a href='updaterecord.jsp?srno=<%=rs.getInt(1)%>' target='blank'>Update</td>
<td><a href='deleterecord.jsp?srno=<%=rs.getInt(1)%>' target='blank'>Delete</td>

Using hyperlink we send the srno(primary key- fetched by rs.getInt(1)) of corresponding record to updaterecord.jsp and deleterecord.jsp pages with the help of srno variable.

When we click on update and delete hyperlink the rs.getInt(1) data sent to another page using srno variable via URL. See the URL after clicking on link


 Now on updaterecord.jsp page we can receive srno variable  value using

                  int search=Integer.parseInt(request.getParameter("srno"));

After getting srno of that particular record, we can do anything related to this record.

Saturday, 3 September 2016

Dynamically create rows, checkboxes, buttons in JSP/JAVA

Generally we create rows, check boxes, buttons, hyperlink statically. But when we want it to create dynamically or when we have to associate it with row fetched from database and we don't know the exact result has to come.

If we want to create fixed number of elements dynamically, obviously we use loop like that

<table>
<%
int i=0;
while(i<=10)
{
%>
              <tr><td>your data</td></tr>   //it prints 10 table row
              <input  type="search"  />        // it prints 10 textfield
              <input type="submit" value="Search" />   // it prints 10 buttons
              ..... and so on 
<%
i++;
}
%>
</table>


If we get data from database and want these elements to associate with this then

just change the loop

while(rs.next())
{
// put your elements according to you//
}



Change image source dynamically on hyperlink

 Changing image source dynamically using JQuery. Here in this example I have created there hyperlink and stored all images in the same folde...