authentication filter code for implement in web api code example

Example 1: Implement Authentication filter using filter API

//Servlet file
import java.io.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletFilter extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest res, HttpServletResponse resp) throws IOException, ServletException {
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        String str = res.getParameter("name");
        out.print("<h1>Hello " + str + "</h1><h2>You have sucessfully logged in....</h2>");

    }

}

Example 2: Implement Authentication filter using filter API

//Java file
import java.io.*;
import javax.servlet.*;

public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        PrintWriter pw = resp.getWriter();
        String pwd = req.getParameter("password");
        if (pwd.equals("birju")) {
            chain.doFilter(req, resp);
        } else {
            pw.print("Invalid Password");
            RequestDispatcher redi = req.getRequestDispatcher("index.html");
            redi.include(req, resp);
        }
    }

    @Override
    public void destroy() {
    }

}

Tags:

Java Example