Berikut ini penggunaan Filter di Java Servlet menggunakan netbeans. Buat lah sebuah web application dengan nama filterLogin. Adapun struktur aplikasi nya sebagai berikut :
index.html, kode nya sebagai berikut :
Filter Login
CheckoutPage.jsp, kode nya sebagai berikut :
<%@page contentType="text/html" pageEncoding="UTF-8"%>
JSP Page
<%
String userName = null;
String sessionID = null;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for(Cookie cookie : cookies){
if (cookie.getName().equals("user")) {
userName = cookie.getValue();
}
}
}
%>
Hi <%=userName%>, do the checkout.
LoginSuccess.jsp, kode nya sebagai berikut :
<%@page contentType="text/html" pageEncoding="UTF-8"%>
JSP Page
<%
//Allow access only if session exists
String user = (String) session.getAttribute("user");
String userName = null;
String sessionID = null;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for(Cookie cookie : cookies){
if (cookie.getName().equals("user")) {
userName = cookie.getValue();
}
if (cookie.getName().equals("JSESSIONID")) {
sessionID = cookie.getValue();
}
}
}
%>
<%=userName%>, Login successful. Your Session ID=<%=sessionID%>
User=<%=user%>
Checkout Page
AuthenticationFilter.java, kode nya sebagai berikut :
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class AuthenticationFilter implements Filter {
private static final boolean DEBUG = true;
private FilterConfig filterConfig = null;
public AuthenticationFilter(){}
private void doBeforeProcessing(ServletRequest request, ServletResponse response)
throws IOException, ServletException
{
if (DEBUG) {
log("AuthenticationFilter:doBeforeProcessing");
}
}
private void doAfterProcessing(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
if (DEBUG) {
log("AuthenticationFilter:doAfterProcessing");
}
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (DEBUG) {
log("AuthenticationFilter:doFilter");
}
doBeforeProcessing(request, response);
Throwable problem = null;
try {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String uri = req.getRequestURI();
log("Requested Resource::" + uri);
HttpSession session = req.getSession(false);
if (session == null && !(uri.endsWith("html") || uri.endsWith("LoginServlet"))) {
log("Unauthorized access request");
res.sendRedirect("index.html");
} else {
chain.doFilter(request, response);
}
} catch (Throwable t){
problem = t;
t.printStackTrace();
}
doAfterProcessing(request, response);
if (problem != null) {
if (problem instanceof ServletException) {
throw (ServletException) problem;
}
if (problem instanceof IOException) {
throw (IOException) problem;
}
sendProcessingError(problem, response);
}
}
public FilterConfig getFilterConfig(){
return (this.filterConfig);
}
public void setFilterConfig(FilterConfig filterConfig){
this.filterConfig = filterConfig;
}
public void destroy(){
}
public void init(FilterConfig filterConfig){
this.filterConfig = filterConfig;
if (filterConfig != null) {
if (DEBUG) {
log("AuthenticationFilter:Initializing filter");
}
}
}
public String toString()
{
if (filterConfig == null) {
return ("AuthenticationFilter()");
}
StringBuffer sb = new StringBuffer("AuthenticationFilter(");
sb.append(filterConfig);
sb.append(")");
return (sb.toString());
}
private void sendProcessingError(Throwable t, ServletResponse response){
String stackTrace = getStackTrace(t);
if (stackTrace != null && !stackTrace.equals("")) {
try {
response.setContentType("text/html");
PrintStream ps = new PrintStream(response.getOutputStream());
PrintWriter pw = new PrintWriter(ps);
pw.print("\n\nError \n\n\n");
pw.print("
The resource did not process correctly
\n\n");
pw.print(stackTrace);
pw.print("
\n<\\html>"); // N0I18N
pw.close();
ps.close();
response.getOutputStream().close();
} catch (Exception ex){}
} else {
try {
PrintStream ps = new PrintStream(response.getOutputStream());
t.printStackTrace(ps);
ps.close();
response.getOutputStream().close();
} catch(Exception ex){}
}
}
public static String getStackTrace(Throwable t){
String stackTrace = null;
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
pw.close();
sw.close();
stackTrace = sw.getBuffer().toString();
} catch (Exception ex){}
return stackTrace;
}
public void log(String msg){
filterConfig.getServletContext().log(msg);
}
}
LoginServlet.java, kode nya sebagai berikut :
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final String userID = "admin";
private final String password = "123";
/**
* Processes requests for both HTTP GET and POST
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("");
out.println("");
out.println("");
out.println("Servlet LoginServlet ");
out.println("");
out.println("");
out.println("
Servlet LoginServlet at " + request.getContextPath() + "
");
out.println("");
out.println("");
}
}
//
/**
* Handles the HTTP GET method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//processRequest(request, response);
}
/**
* Handles the HTTP POST method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//processRequest(request, response);
String user = request.getParameter("user");
String pwd = request.getParameter("pwd");
if (userID.equals(user) && password.equals(pwd)) {
HttpSession session = request.getSession();
session.setAttribute("user", "Pankaj");
//setting session to expiry in 30 mins
session.setMaxInactiveInterval(30 * 60);
Cookie userName = new Cookie("user", user);
userName.setMaxAge(30 * 60);
response.addCookie(userName);
response.sendRedirect("LoginSuccess.jsp");
} else
{
RequestDispatcher rd = getServletContext().getRequestDispatcher("/index.html");
PrintWriter out = response.getWriter();
out.println("Either user name or password is wrong.");
rd.include(request, response);
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}//
}
LogoutServlet.java, kode nya sebagai berikut :
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author Azie
*/
public class LogoutServlet extends HttpServlet {
/**
* Processes requests for both HTTP GET and POST
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("");
out.println("");
out.println("");
out.println("Servlet LogoutServlet ");
out.println("");
out.println("");
out.println("
Servlet LogoutServlet at " + request.getContextPath() + "
");
out.println("");
out.println("");
}
}
//
/**
* Handles the HTTP GET method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//processRequest(request, response);
}
/**
* Handles the HTTP POST method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//processRequest(request, response);
response.setContentType("text/html");
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for(Cookie cookie : cookies){
if (cookie.getName().equals("JSESSIONID")) {
System.out.println("JSESSIONID=" + cookie.getValue());
break;
}
}
}
//invalidate the session if exists
HttpSession session = request.getSession(false);
System.out.println("User=" + session.getAttribute("user"));
if (session != null) {
session.invalidate();
}
response.sendRedirect("index.html");
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}//
}
RequestLoggingFilter.java, kode nya sebagai berikut :
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Enumeration;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
public class RequestLoggingFilter implements Filter{
private static final boolean DEBUG = true;
private FilterConfig filterConfig = null;
public RequestLoggingFilter(){
}
private void doBeforeProcessing(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
if (DEBUG) {
log("RequestLoggingFilter:doBeforeProcessing");
}
HttpServletRequest req = (HttpServletRequest) request;
Enumeration params = req.getParameterNames();
while(params.hasMoreElements()){
String name = params.nextElement();
String value = request.getParameter(name);
log(req.getRemoteAddr() + "::Request Params::{" + name + "=" + value + "}");
}
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for(Cookie cookie : cookies)
{
log(req.getRemoteAddr() + "::Cookie::{" + cookie.getName() + ", " + cookie.getValue() + "}");
}
}
}
private void doAfterProcessing(ServletRequest request, ServletResponse response)
throws IOException, ServletException
{
if (DEBUG) {
log("RequestLoggingFilter:doAfterProcessing");
}
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException
{
if (DEBUG) {
log("RequestLoggingFilter:doFilter()");
}
doBeforeProcessing(request, response);
Throwable problem = null;
try {
chain.doFilter(request, response);
} catch(Throwable t){
problem = t;
t.printStackTrace();
}
doAfterProcessing(request, response);
if (problem != null) {
if (problem instanceof ServletException) {
throw (ServletException) problem;
}
if (problem instanceof IOException) {
throw (IOException) problem;
}
sendProcessingError(problem, response);
}
}
public FilterConfig getFilterConfig(){
return (this.filterConfig);
}
public void setFilterConfig(FilterConfig filterConfig)
{
this.filterConfig = filterConfig;
}
public void destroy(){}
public void init(FilterConfig filterConfig){
this.filterConfig = filterConfig;
if (filterConfig != null) {
if (DEBUG) {
log("RequestLoggingFilter:Initializing filter");
}
}
}
@Override
public String toString()
{
if (filterConfig == null) {
return ("RequestLoggingFilter()");
}
StringBuffer sb = new StringBuffer("RequestLoggingFilter()");
sb.append(filterConfig);
sb.append(")");
return (sb.toString());
}
private void sendProcessingError(Throwable t, ServletResponse response)
{
String stackTrace = getStackTrace(t);
if (stackTrace != null && !stackTrace.equals("")) {
try {
response.setContentType("text/html");
PrintStream ps = new PrintStream(response.getOutputStream());
PrintWriter pw = new PrintWriter(ps);
pw.print("\n\nError \n\n\n");
pw.print("
The resource did not process correctly
\n\n");
pw.print(stackTrace);
pw.print("
\n");
pw.close();
ps.close();
response.getOutputStream().close();
}catch(Exception ex){}
} else {
try {
PrintStream ps = new PrintStream(response.getOutputStream());
t.printStackTrace(ps);
ps.close();
response.getOutputStream().close();
} catch (Exception ex){}
}
}
public static String getStackTrace(Throwable t){
String stackTrace = null;
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
pw.close();
sw.close();
stackTrace = sw.getBuffer().toString();
} catch (Exception ex){}
return stackTrace;
}
public void log(String msg){
filterConfig.getServletContext().log(msg);
}
}

No comments:
Post a Comment