Friday, July 1, 2016

WebServer : Login Screen

WebServer : Login Screen

http://docs.oracle.com/javaee/6/tutorial/doc/gjiie.html
http://www.tutorialspoint.com/servlets/servlets-form-data.htm  (All sorts of form elements)
http://mrbool.com/using-html-forms-with-servlets/28335
http://www.javatpoint.com/servlet-http-session-login-and-logout-
http://www.javatpoint.com/servlet-http-session-login-and-logout-example
http://tutorials.jenkov.com/java-servlets/index.html

doGet()
  1.  small amount of data
  2.  insensitive data like a query has to be sent as a request.

doPost()
  1.  large amount of  has to be sent.
  2.  sensitive data (Examples are sending data after filling up a form or sending login id and password.)

Note :
Following methods of the HttpServletRequest interface that enable you to authenticate users for a web application programmatically:

    login-An alternative to specifying form-based authentication in an application deployment descriptor.
    logout- which allows an application to reset the caller identity of a request.

Forward():
  1.     Executed in the server side.
  2.     The request is transfer to other resource within same server.
  3.     Any Client
  4.     The request is shared by the target resource.
  5.     It can be used within server.
  6.     We cannot see forwarded message
  7.      faster
  8.     It is declared in RequestDispatcher interface.
  9.     Only Response from Server

sendRedirect():
  1.     Executed in the client side.
  2.     The request is transfer to other resource to different server.
  3.     Only with HTTP clients.
  4.     New request is created for the destination resource.
  5.     It can be used within and outside the server.
  6.     We can see redirected address, it is not transparent.
  7.     slower
  8.     It is declared in HttpServletResponse.
   
Include()
    Forward() + Client Side info()


Application Overview:
Index.html > Login.html > (Pass)Welcome.html or (fail) Login.html

@WebServlet("/Login")
public class MyServerlet1 extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final String sURL="jdbc:mysql://localhost:3306/mydb";
    private static final String sUsername="root";
    private static final String sPassword="password";
   
    public MyServerlet1() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List LRes=null;
        RequestDispatcher rd = null;
        DBHelper DBHelp=new DBHelper();
        PrintWriter out=response.getWriter();
       
        String username = request.getParameter("Usn");
        String password = request.getParameter("Password");
        LRes=DBHelp.SelectQuery(sURL,sUsername,sPassword,"SELECT * FROM mydb.login where UserID ='"+username+"' and Password='"+password+"';");
       
        if(LRes.isEmpty()==false){
            out.print("Login Successful");
            HttpSession session=request.getSession(); 
            session.setAttribute("name",username); 
           // response.sendRedirect(request.getContextPath() + "/WelcomeServlet.jsp");
            rd = request.getRequestDispatcher("/WelcomeServlet.html");
            rd.include(request, response);
            //rd.forward(request, response);  -- This can be used as well
            LRes=null;
        }
        else{
            out.print("Login failed");
        response.sendRedirect(request.getContextPath() + "/Login.html");
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);

    }
}


Database helper Class :
public class DBHelper {   
    public List SelectQuery(String sURL,String sUsn,String sPassword,String sQuery){
        ResultSet rs=null;
        MapListHandler rstoList=new MapListHandler();
        Map<String,Object> MapQuery=new HashMap<String,Object>();
        List resList=null;
       
        try {
            Class.forName("com.mysql.jdbc.Driver");   
            Connection connection = DriverManager.getConnection(sURL,sUsn, sPassword);           
            Statement st=(Statement) connection.createStatement();
             rs=st.executeQuery(sQuery);
             resList= rstoList.handle(rs);
             rs.close();
             st.close();
             connection.close();           
               
      }catch(Exception e){
          System.out.println("Failed to make connection!");
          e.printStackTrace();
      }       
        return resList;
    }
}




Monday, June 27, 2016

Java : doGet vs doPost


doGet vs doPost



In doget() method
  1. There is a security problems are arrival because when the user or client submit the form the associated user name or password has been display on the address bar.
  2.  client can send limited amount of data.
  3.  when the users tries to request for any Read Only data.
doPost() method
  1. when the user submit the form the associated user name or password are not display on the addressbar.
  2. client can send more then data.
  3.   used for Insertion /updation / deletion of data ,

Java : WebServer Database Connection and retreive data

WebServer Database Connection and retrieve data


Notes:

  1. doPost(..) method is generally used for Insertion /updation / deletion of data , 
  2. doGet(..) is used when the users tries to request for any Read Only data.

Pre -Req :

  1.  Using MySQL as DB Server
  2. Download "MySQL connector J.Jar" driver file and paste it into "Project/WebContent/WEB-INF/lib" folder path.
  3. Add the same file into project build directory.
  4. Download "Apache Commons DbUtils" jar file and paste it into "Project/WebContent/WEB-INF/lib" folder path.
  5. Repeat step 3.

DBHelper method: 
The below method return the results of the query in the form of Query list.


    public List SelectQuery(String sURL,String sUsn,String sPassword,String sQuery){
        ResultSet rs=null;
        MapListHandler rstoList=new MapListHandler();
        Map<String,Object> MapQuery=new HashMap<String,Object>();
        List resList=null;
       
        try {
            Class.forName("com.mysql.jdbc.Driver");   
            Connection connection = DriverManager.getConnection(sURL,sUsn, sPassword);           
            Statement st=(Statement) connection.createStatement();
             rs=st.executeQuery(sQuery);
             resList= rstoList.handle(rs);
             rs.close();
             st.close();
             connection.close();           
               
      }catch(Exception e){
          System.out.println("Failed to make connection!");
          e.printStackTrace();
      }       
        return resList;
    }


 Serverlet :
 Calling Method 

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {    
        DBHelper DBHelp=new DBHelper();
         PrintWriter out=response.getWriter();
        out.print(DBHelp.SelectQuery(sURL,sUsername,sPassword,"Select * from mydb.login;"));
    }

Wednesday, June 22, 2016

Creating a simple web Service

Creating a simple web Service


https://www.youtube.com/watch?v=Av6zh817QEc
http://crunchify.com/servlet-tutorial-getting-starting-with-jsp-servlet-example/

Tips:
  1. External Jars go into - Project\WebContent\WEB-INF\lib
  2. Java files (Serverlets) goes into - Project\Java Resources\src\com.package\HERE
  3. JSP files - Project\WebContent\
  4. html files -  Project\WebContent\
  5. JSP files are html files but with different extension 
  6. The 1st html file shown is index.jsp , so this shoulkd not be deleted.



Configuring TomCat WebServer to Eclipse
1. download eclise
2. Download ApacheTomcat zip file Eg:8.73
3. Unzip AcpacheTomcat into a folder
4. Open Eclipse > Window >Preference>Server > Run time Environment>Add
5. In Add Window , Select the respective Apache Server Downloaded and Ck on finish

Validation :
1. In Eclipse > Window >perspective > Open perspective> web
2. In server Tab below> Right ck > new > Server
3. Select the correct server
4. Finish
5. A server gets added into the server tab , Double click on it to open the server settings
6. In Server Locations> Select use custom location and provide new path to save ur server.
7. Also user can change the port numbers in "Ports" Tab
8. save
9. perform right ck on the new server created in server tab> Select start
10. Open browser tab in eclipse > open "http://localhost:8080"
11. User should get 404 error meaninf server is configured correctly and running

Create project

1.    In Eclipse>File> New >Dynamic web project
2. Projectname= webapp-02, Make sure Dynamic Web Module version=2.5, Target runtime =8.0 (or what ever downloaded)
3. next ,again Next
4. Make sure "Generate web.xml" is checked.
5. Finish
6. Project>Rt clk>new >jsp file
7. file name "index.jsp"
8. Next and finish

9. Double ck "Deployment Descriptor" to open web.xml file
10. project>java resources > src>Create a new package "com.pack1
11. project>java resources > src>select package "com.pack1>right ck and create new serverlet>class name as "MyServerlet" (MyServerlet is the name specified  )
12 .open index.jsp and add below lines at the end (note: they are case sensitive):
    <h1>Welcome</h1>
    <form action="MyServerlet">
    <input type="submit" value="send">
    </form>

    </body>
    </html>

13. Open MyServerlet.java > add below code in doGet method :
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out=response.getWriter();
        out.print("hell noi");

    }

14. save all
15. project >Right Ck>Run as "Run on Server"

Monday, May 16, 2016

Java : Inner Class , Nested Class , Static Class and Interfaces

Inner Class , Nested Class , Static Class and Interfaces



interface A {//All implementation in Interface = Static
    static class X{}            //To Avoid : if(X instance of A) ,can be accessed as A.X
    static abstract class Y{}    //Not valid - Cannot instantiate abstract class (static)
    static interface Z{}        //Not valid - Cannot instantiate Interface (static)
}

abstract class B {
    class X{}            //X=private by default
    abstract class Y{}    //
    interface Z{}        //
}

class C {
    void m(){class c{}}//Local inner class(visible only inside this method    )
    static class W{}    //Accessed as C.W
    class X{}            //Nested Class
    abstract class Y{}    // Implementing class needs
    interface Z{}
}


Nested Class:
1. Private by Default
2. Can access all the private members of super class
3.     C face=new C();
    C.X ear1=face.new X(); //logical grouping, readable and maintainable code
    C.X ear2=face.new X();
4. Same operation can also be done using external classes

Friday, May 6, 2016

Java : Important API

Java : Important API


  1. Fileutils : Folder and File Related Operations (also does read ,write,append to text file)
  2. StringUtils: For String Related Operations (contains,indexof,mid,leftpad,join,split,rightpad,leftpad,replace,trim etc.,)
  3. Guava: Additional util operations
  4. WorkBookFactory : Excel Operations (Apache POI)


Alternatives
  1. File>FileReader>BufferedReader : To read text
  2. File>FileWriter >BufferedWriter: To write text

Sunday, April 10, 2016

Java :OOPS Design Rules

OOPS Design Rules

Software :
  1. Perform what it supposed to.
  2. Flexible (by adding OOPS)
  3. Maintainable and Reusable

Object
  1. Object naming should be related to its operation
  2. Each object should not perform unrelated activities
  3. There should not be any unused properties or fields.
  4. Encapsulation helps divide application into logical parts.
  5. Duplicate code should be encapsulated separately
  6. Encapsulate what varies to protect class from unnecessary chages
Delegation: Delegating the current task to  specialized object which is designed to handle that.

Textual Analysis of Use Cases : Nouns = Classes and Verbs =methods.

Interface Vs Class
Coding to Interface is better as user has option to extend open.

Extra Classes make softare inflexible and difficult to change

Monday, April 4, 2016

Find out which process is locking a file or folder in Windows

Find out which process is locking a file or folder in Windows




Have a look at Process Explorer (procexp.exe).
From its introduction:
Ever wondered which program has a particular file or directory open? Now you can find out.
To find out what process is using a specific file follow these steps:
  1. Go to Find, Find Handle or DLL.. or simply press Ctrl+F.
    Enter image description here
  2. Enter the name of the file and press Search.
    Enter image description here
  3. Process Explorer will list all processes that have a handle to the file open. Click on an entry to focus the process in the main window.
    Enter image description here
  4. Optionally, you can then even close the handle manually through the lower pane (Ctrl+L):
    Enter image description here