Monday, March 28, 2016

Login Validation for paid and unpaid users with eradication of SQL Injection:

HTML Page:

<html>
<body>
<form action="login.jsp" method="post">
<label>User:</label>
<input type="email" name="uname" required><br>
<label>Password:</label>
<input type="password" name="pass" required><br>

<button type="submit">Login</button>
</form>
</body>
</html>

JSP for Login:


<%@ page import="java.sql.*"%>
<% 
         String name=request.getParameter("uname"); //getting uname from html page
String pass=request.getParameter("pass");    // getting password from html
if(name==null && pass==null && name=="" && pass=="")
{
out.println("please fill all fields");
}
Connection con=null;
Statement st=null;
ResultSet rs=null;
String sql= " select * from users where users= ' "+name+" ' ";
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");           // the driver may differ as this is for ms access.
  con=DriverManager.getconnection("jdbc:odbc:DB_Name");
   st=con.createStatement();
   rs=st.executeQuery(sql);
   if(rs.next())
    {
                String user=rs.getString(1);   //getting username from DB
                String passwrd=rs.getString(2);   //getting password from DB
                
                if (pass.matches(passwrd))       // using matches method for password so that SQL Injection fails.
                                   {
                    session.setAttribute("userid", user);          //setting userid and password as session for filteration.
                     String verify=rs.getString(9);
                    if(verify.matches("paid"))              // verifying user if paid or not.
                 {
%>
<jsp:forward page="paiduser.jsp"/> // if user is paid it will go to paid user page else to unpaid  user page.
    <%
                                 }
                               else
                               {
                                                   %>
        <jsp:forward page="unpaiduser.jsp"/>
            <%
                               }
  
               } 
 out.println("Oop's! you are not Authenticated Person");
               
            
        } }
catch(SQLException e1)
{
System.out.println(e1);
}

finally
{
    st.close();
     con.close();
}
            %>

Tuesday, March 22, 2016

Tool for Json file Conversion.
Get the Data from DB And Make a json file for parsing it in Android or in any applications.

<%@ page import="java.io.*,java.util.*, javax.servlet.*, java.sql.*" %>
<%
Connection con=null;
    Statement st=null;
    ResultSet rs=null;
    String cid=" ";
    String cname=" ";
            String category=" ";
            String image=" ";
            String num=" ";
            String area=" ";
            String video=" ";
            String user=" ";
          String sql="select * from company";   //query passed in rs=st.executeQuery(sql);
    
      //File creation
 String strPath = "F:\\company.json";     // file path to store file at with this extension .json name
 File strFile = new File(strPath);
 boolean fileCreated = strFile.createNewFile();         // file creation with name and with (.)dot extension json
 //File appending
 Writer objWriter = new BufferedWriter(new FileWriter(strFile));
objWriter.write("{'employees':[");     //json object creation with name employee.
try                 //getting connection and values from DB. (attributes like address will have problem in json as we will have substring in that, so use xml for that)
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");     
con=DriverManager.getConnection("jdbc:odbc:DB_name");
   st=con.createStatement();
   rs=st.executeQuery(sql);
   while(rs.next())      //while will iterate and print all values in this object
                     {
                cid=rs.getString(1);
                cname=rs.getString(2);
                category =rs.getString(3);
                image =rs.getString(6);
                num=rs.getString(9);
                area=rs.getString(10);
                video=rs.getString(11);
                user=rs.getString(14);
             
 objWriter.write("{'cid':'"+cid+"', 'company Name':'"+cname+"', 'category':'"+category+"', 'image':'http://www.xyz.com/"+image+"', 'number':'"+num+"', 'area':'"+area+"', 'video':'http://www.xyz.com/"+video+"', 'User':'"+user+"'},");  // finish it in one line.
     
            }
            objWriter.write("]}"); // after iteration close the while and close the employees object
            objWriter.flush();   
 objWriter.close();            
 out.println("JSON Generated successfully");     //JSON file generated.
             
}
catch(SQLException e)            
               {
    out.println(e);
}
%> 


Net beans Build Failed When 

" Deployment error: Access to Tomcat server has not been authorized. Set the correct username and password with the "manager-script" role in the Tomcat customizer in the Server Manager. See the server log for details. "


This happens when you change your username and password in your netbeans, as your netbeans tomcat will have tomcat-user.xml which have default value, either change that or else maintain that record..

to check and rectify mistake go to:

C:\Documents and Settings\{User}\.netbeans\7.1\apache-tomcat-7.0.22.0_base\conf

you can find tomcat-user.xml
open that with notepad and see the last line
it must be

<user username="ide" password="Agt7ViLa" roles="manager-script,admin"/></tomcat-users>

again go back to netbeans
  • click on tools
  • select servers.
  • set Username: "ide" & password: "Agt7ViLa".

or else change it. but you have to edit the file as well as in netbeans.
then go to netbeans and run the project.

For more info subscribe us or follow us at aksoftdeveloper.blogspot.in or contact us at softdevelopr007@gmail.com

Bye Have a nice day

Monday, March 21, 2016

New User Signup: create folder when signup and a row in a DB:

//HTML Page for Signup form


<%-- 
    Document   : signup
    Created on : Feb 11, 2016, 11:33:09 AM
    Author     : Ak-47
--%>
<!DOCTYPE html>
<html>
    <head>
        <title>signup</title>
  <meta charset="utf-8">
    <script>
    function myFunction()  // function to check passsword and confirm password
    {
    var a,b;
    a=document.form1.pass.value;
    b=document.form1.passw.value;
    
    if(a!=b || a=="")
        {
         alert("Password doesnt match");  
         form1.action = 'http://www.google.com/';
         
        }
        else
            {
             form1.action='insertuser.jsp';   
            }
    }
</script>
    </head>
    <body>
       
            <form name="form1" onsubmit="myFunction()" action="insertuser.jsp" method="post">
  
    <label>First Name: </label>
           <input type="text" name="fname" placeholder="Enter First Name" required>
   
    <label>Last Name: </label>
         <input type="text" name="lname" placeholder="Enter Last Name" required>
   
    <label>Email:</label>
      <input type="email" name="email" placeholder="Enter email" required>
 
 <label>Mobile:</label>
      <input type="text" name="mobile" placeholder="Enter Cellular Number" required>
   
            <label>Password:</label>
      <input type="password" name="pass" placeholder="Enter password" required>
            
    <label>Confirm Password:</label>
      <input type="password" name="passw" placeholder="Enter password again" required>
   
         <label>Date of Birth:</label>
      <input type="date" name="dob">
            
   <label>Gender:</label>
        <select name="gender">
          <option value="Male">Male</option>
    <option value="Female">Female</option>
    <option value="Transgender">Transgender</option>
      </select>
      
                  <label>Address:</label>
        <textarea rows="5" name="address" required></textarea>
    
      <button type="submit" class="btn btn-default">Submit</button>
    </form>
    
    </body>
</html>

//JSp page (Insertuser.jsp)

<%-- 
    Document   : insertuser
    Created on : Feb 11, 2016, 1:53:30 PM
    Author     : Ak-47
--%>
<%@ page import="java.io.*,java.util.*, javax.servlet.*, java.sql.*, databasecon.*" %>
<%@ page import="javax.servlet.http.*" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
        <%

//declaring all the variables

        String fname=request.getParameter("fname");
        String lname=request.getParameter("lname");
        String userid=request.getParameter("email");
        String pass=request.getParameter("pass");
        String mobile=request.getParameter("mobile");
        String dob=request.getParameter("dob");
        String gender=request.getParameter("gender");
        String address=request.getParameter("address");
            
        String filePath="C:/proj/zot/web/user"; 
// declaring the file path where we want to create user folder and upload data later.
        
       try
       { 
File root = new File(filePath);
        File newfolder = new File(root, "/"+userid); //creating the new folder
            newfolder.mkdir();
                    filePath=filePath+"/"+userid+"/";
                    File newfldr = new File(filePath, "gallery");
            newfldr.mkdir();
            File newfoldr = new File(filePath, "products");
            newfoldr.mkdir();   

                Connection con=null;
Statement st=null;
      String sql="insert into users values ('"+userid+"','"+pass+"','"+fname+"','"+lname+"','"+dob+"','"+gender+"','"+mobile+"','"+address+"')";         
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getconnection("jdbc:odbc:DB_Name");  //these drivers are only for ms-access.
  st=con.createStatement();
   int x=st.executeUpdate(sql);
   if(x!=0)
    {
out.println("created successfully : <h2>"+userid+" : "+mobile+"</h2><br>");
             out.println("for more details Contact us. <br>");
   }
                       else
                       {
 out.println( userid + " already exists");
                   
                       }
            st.close();
            con.close();
        
                                           
       }
       catch(SQLException e)
                             {
      out.println(userid +" Already exists "+e);
       }
    %>
    </body>
</html>

Contact Us At: softdevelopr007@gmail.com

Uploading file to folder and storing the path to Database


All the fellows of java developer who doesnt know how to upload file in web apps, follow these few steps.

first of all download these three files
  • commons-fileupload-1.3.1-bin
  • commons-fileupload-1.3.1-bin.tar
  • commons-io-2.4-bin
then upload this file to libraries in IDE (Netbeans or Eclipse)
then write this code.

// Html Code //

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <title>upload video</title>
 
<script>
    function myFunction()
    {
        alert("Are you sure?, dont want to upload your Video??");
       window.location.href = "http://www.xyz.com/dashboard.jsp";
    }
</script>
    </head>
    <body>
        
        <form action="insertvideo.jsp" method="post" enctype="multipart/form-data">
            <center><strong><h2>Insert Video for company</h2></strong></center><hr>
       
    <label>Video:</label>
    
      <input type="file" class="form-control" name="filev">
          
      <button type="submit">Submit</button>
    
    <button type="button" onclick="myFunction()">Cancel</button>
        
  
        </form>
    </body>
</html>



// JSP CODE //


<%@ page import="java.io.*, javax.servlet.*, java.sql.*" %>
<%@ page import="javax.servlet.http.*" %>
<%@page import="java.util.*, java.math.*" %>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.disk.*" %>
<%@ page import="org.apache.commons.fileupload.servlet.*" %>
<%@ page import="org.apache.commons.io.output.*" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <%
String userid=(String) session.getAttribute("user");
if (userid==null) {%>
        <jsp:forward page="admin.jsp"/>
<%       
}%>

<%
   
        String videoname="art"; //default name for path into DB
              File file ;
   int maxFileSize = 100000 * 1024; //limit size for file 100MB
   int maxMemSize = 100000 * 1024;  // 100,000 KB equals 100MB
   
   String filePath = "F:/proj/zot/vid/"; // path of the folder
  
   String contentType = request.getContentType();
   if ((contentType.indexOf("multipart/form-data") >= 0)) {

      DiskFileItemFactory factory = new DiskFileItemFactory();
      // maximum size that will be stored in memory
      factory.setSizeThreshold(maxMemSize);
      // Location to save data that is larger than maxMemSize.
      factory.setRepository(new File("c:\\temp"));

      // Create a new file upload handler
      ServletFileUpload upload = new ServletFileUpload(factory);
      // maximum file size to be uploaded.
      upload.setSizeMax( maxFileSize );
       try{ 
            
         // Parse the request to get file items.
            
         List fileItems = upload.parseRequest(request);

         // Process the uploaded file items
         Iterator i = fileItems.iterator();

         out.println("<html>");
         out.println("<head>");
         out.println("<title>JSP File upload</title>");  
         out.println("</head>");
         out.println("<body>");
         while ( i.hasNext () ) 
         {
             FileItem fi = (FileItem)i.next();
              if ( !fi.isFormField () )
            {
             // Get the uploaded file parameters
        
                String fieldName = fi.getFieldName();
                
                
            String fileName = fi.getName();
            boolean isInMemory = fi.isInMemory();
            long sizeInBytes = fi.getSize();
            videoname=fi.getName(); // storing the name of file.
            // Write the file
            if( fileName.lastIndexOf("\\") >= 0 ){
            file = new File( filePath + 
            fileName.substring( fileName.lastIndexOf("\\"))) ;
            }else{
            file = new File( filePath + 
            fileName.substring(fileName.lastIndexOf("\\")+1)) ;
            }
            fi.write( file ) ;
          
          Connection con=null;
Statement st=null;
ResultSet rs=null;
        String videopath="vid/"+videoname; //now declare variable and set the video path upload into DB.
        
       Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        con=DriverManager.getconnection("jdbc:odbc:DB_Name");
   st=con.createStatement();
String sql="insert into video_table values ('"+videopath+"')";         
   int x=st.executeUpdate(sql);
   if(x!=0)
    {%>
                 <jsp:forward page="dashboard.jsp"/>
<%
   }
                       else{
 out.println("Unable to upload");
                   }
             con.close();
        st.close(); 
            }
            
         }
         
         out.println("</body>");
         out.println("</html>");
      }catch(Exception ex) {
         System.out.println(ex);
      }
   }else{
      out.println("<html>");
      out.println("<head>");
      out.println("<title>Servlet upload</title>");  
      out.println("</head>");
      out.println("<body>");
      out.println("<p>No file uploaded</p>"); 
      out.println("</body>");
      out.println("</html>");
   }
  
   
            %>
    </body>
</html>