Monday, January 12, 2015

Jersey FrameWork Login Page with java Sql Connection


Used Software
  1. Eclipse
  2. SQL
Require Jars
  1. Jersey Jara
  2. MySql Connection jars  

File Structure

 

Code

web.xml
________________________________________________________________________________
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>com.restapi.demo</display-name>
  <welcome-file-list>
              <welcome-file>
V2_EmpLogin.jsp </welcome-file>
  </welcome-file-list>
  <servlet>
             <servlet-name>Jersey REST Service</servlet-name>
             <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
            <init-param>
                          <param-name>com.sun.jersey.config.property.packages</param-name>
                          <param-value>com.restapi.demo</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
          <servlet-name>Jersey REST Service</servlet-name>
          <url-pattern>/api/*</url-pattern>
  </servlet-mapping>
</web-app>


V2_EmpLogin.jsp
_________________________________________________________________________________

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Get User Details</title>
</head>
<body>
<pre>
<form action="V2_EmpLoginServlet" method="post">

    Name    :<input type = "text" name = "username">
    Password:<input type = "text" name = "password">
   
    <input type = "submit" value="Submit">
</form>
</pre>
</body>
</html>


__________________________________________________________________________________

V2_EmpLoginServlet.java

package com.restapi.demo.database;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
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 javax.ws.rs.core.Cookie;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.representation.Form;

/**
 * Servlet implementation class V2_EmpDatabaseServlet
 */
@WebServlet("/V2_EmpLoginServlet")
public class V2_EmpLoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
      
    /**
     * @see HttpServlet#HttpServlet()
     */
    public V2_EmpLoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        // TODO Auto-generated method stub
        Client client= Client.create();

        String userName=(String)request.getParameter("username");
        String password=(String)request.getParameter("password");
       
        Form form= new Form();
       
        form.add("username", userName);
        //form.add("password", password);
        Cookie cookie= new Cookie("password", password);
        WebResource webResource=client.resource("http://localhost:8080/com.restapi.demo/api/v2/emplogin");
        ClientResponse clientResponse=webResource.accept("text/html").cookie(cookie).post(ClientResponse.class, form);
       
        int output=clientResponse.getStatus();
        if(output==200)
        {
            System.out.println("true");
            response.sendRedirect("V2_LoginSuccess.jsp");
        }
        else
        {
            RequestDispatcher rd = getServletContext().getRequestDispatcher("/V2_EmpLogin.jsp");
            PrintWriter out= response.getWriter();
            out.println("<font color=red>Either user name or password is wrong.</font>");
            rd.include(request, response);
           
        }
    }

}
_________________________________________________________________________________
V2_Database.java

package com.restapi.demo.database;

import java.sql.*;

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/v2")

public class V2_Database
{
    @POST
    @Path("/emplogin")
    @Produces(MediaType.TEXT_HTML)
    public Response returnDatabase(@FormParam("username") String username,@CookieParam("password") String password)
    {
        try
        {
            System.out.println("->"+username);
            System.out.println("->"+password);
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test","root","root");
            PreparedStatement ps = con.prepareStatement("select username,password from users where username = ? and password = ?");
            ps.setString(1, username);
            ps.setString(2, password);
            ResultSet rs = ps.executeQuery();
            int count=0;
            while(rs.next())
            {
                count++;
            }
           
            if(count==1)
            {
                System.out.println("Succussful");
                return Response.status(200).build();
            }
            else
            {
                System.out.println("wrong id and passs");
                return Response.status(201).build();
            }
        }
        catch (Exception e)
        {
            System.out.println("Exception--->"+e);// TODO: handle exception
        }
        return null;
    }

}
 _____________________________________________________________________________

Testing

Test for Wrong Id and Password

Enter Correct ID and Password


No comments:

Post a Comment