BAEL-325: Implemented various filter examples.

This commit is contained in:
Christian Rädel 2016-09-04 12:07:13 +02:00 committed by slavisa-baeldung
parent 11440cd673
commit 2b9470eed0
24 changed files with 588 additions and 0 deletions

View File

@ -0,0 +1,49 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>intercepting-filter-pattern</artifactId>
<packaging>war</packaging>
<parent>
<artifactId>enterprise-patterns-parent</artifactId>
<groupId>com.baeldung.enterprise.patterns</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.21</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.3.11.v20160721</version>
<configuration>
<webApp>
<contextPath>/intercepting-filter</contextPath>
</webApp>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,55 @@
package com.baeldung.enterprise.patterns.front.controller;
import com.baeldung.enterprise.patterns.front.controller.commands.FrontCommand;
import com.baeldung.enterprise.patterns.front.controller.commands.UnknownCommand;
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 java.io.IOException;
@WebServlet(name = "front-controller", urlPatterns = "/")
public class FrontControllerServlet extends HttpServlet {
@Override
protected void doGet(
HttpServletRequest request,
HttpServletResponse response
) throws ServletException, IOException {
doCommand(request, response);
}
@Override
protected void doPost(
HttpServletRequest request,
HttpServletResponse response
) throws ServletException, IOException {
doCommand(request, response);
}
private void doCommand(
HttpServletRequest request,
HttpServletResponse response
) throws ServletException, IOException {
FrontCommand command = getCommand(request);
command.init(request, response);
command.process();
}
private FrontCommand getCommand(HttpServletRequest request) {
try {
Class type = Class.forName(
String.format(
"com.baeldung.enterprise.patterns.front.controller.commands.%sCommand",
request.getParameter("command")
)
);
return (FrontCommand) type
.asSubclass(FrontCommand.class)
.newInstance();
} catch (Exception e) {
return new UnknownCommand();
}
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung.enterprise.patterns.front.controller.commands;
import com.baeldung.enterprise.patterns.front.controller.filters.FilterManager;
import com.baeldung.enterprise.patterns.front.controller.filters.OnIntercept;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public abstract class FrontCommand implements OnIntercept {
protected HttpServletRequest request;
protected HttpServletResponse response;
private boolean intercept;
public FrontCommand() {
}
public void init(HttpServletRequest request, HttpServletResponse response) {
this.request = request;
this.response = response;
}
public void process() throws ServletException, IOException {
FilterManager.process(request, response, this);
}
public void forward(String target) throws ServletException, IOException {
if (intercept) {
return;
}
String path = String.format("/WEB-INF/jsp/%s.jsp", target);
RequestDispatcher dispatcher = request.getServletContext()
.getRequestDispatcher(path);
dispatcher.forward(request, response);
}
@Override
public void intercept() {
intercept = true;
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.enterprise.patterns.front.controller.commands;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class LoginCommand extends FrontCommand {
@Override
public void process() throws ServletException, IOException {
if (request.getMethod().equals("GET")) {
request.setAttribute("redirect", request.getRequestURL()
.append("?").append(request.getQueryString()).toString());
forward("login");
} else {
HttpSession session = request.getSession(true);
session.setAttribute("username", request.getParameter("username"));
response.sendRedirect(request.getParameter("redirect"));
}
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.enterprise.patterns.front.controller.commands;
import com.baeldung.enterprise.patterns.front.controller.data.Book;
import com.baeldung.enterprise.patterns.front.controller.data.BookshelfImpl;
import javax.servlet.ServletException;
import java.io.IOException;
public class SearchCommand extends FrontCommand {
@Override
public void process() throws ServletException, IOException {
super.process();
Book book = new BookshelfImpl().getInstance()
.findByTitle(request.getParameter("title"));
if (book != null) {
request.setAttribute("book", book);
forward("book-found");
} else {
forward("book-notfound");
}
}
}

View File

@ -0,0 +1,11 @@
package com.baeldung.enterprise.patterns.front.controller.commands;
import javax.servlet.ServletException;
import java.io.IOException;
public class UnknownCommand extends FrontCommand {
@Override
public void process() throws ServletException, IOException {
forward("unknown");
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.enterprise.patterns.front.controller.data;
public interface Book {
String getAuthor();
void setAuthor(String author);
String getTitle();
void setTitle(String title);
Double getPrice();
void setPrice(Double price);
}

View File

@ -0,0 +1,46 @@
package com.baeldung.enterprise.patterns.front.controller.data;
public class BookImpl implements Book {
private String author;
private String title;
private Double price;
public BookImpl() {
}
public BookImpl(String author, String title, Double price) {
this.author = author;
this.title = title;
this.price = price;
}
@Override
public String getAuthor() {
return author;
}
@Override
public void setAuthor(String author) {
this.author = author;
}
@Override
public String getTitle() {
return title;
}
@Override
public void setTitle(String title) {
this.title = title;
}
@Override
public Double getPrice() {
return price;
}
@Override
public void setPrice(Double price) {
this.price = price;
}
}

View File

@ -0,0 +1,16 @@
package com.baeldung.enterprise.patterns.front.controller.data;
public interface Bookshelf {
default void init() {
add(new BookImpl("Wilson, Robert Anton & Shea, Robert", "Illuminati", 9.99));
add(new BookImpl("Fowler, Martin", "Patterns of Enterprise Application Architecture", 27.88));
add(new BookImpl("Unknown", "Something about German Umlauts (äüö) and ß", 5.49));
}
Bookshelf getInstance();
<E extends Book> boolean add(E book);
Book findByTitle(String title);
}

View File

@ -0,0 +1,24 @@
package com.baeldung.enterprise.patterns.front.controller.data;
import java.util.ArrayList;
public class BookshelfImpl extends ArrayList<Book> implements Bookshelf {
private static Bookshelf INSTANCE;
@Override
public Bookshelf getInstance() {
if (INSTANCE == null) {
INSTANCE = new BookshelfImpl();
INSTANCE.init();
}
return INSTANCE;
}
@Override
public Book findByTitle(String title) {
return this.stream()
.filter(book -> book.getTitle().toLowerCase().contains(title.toLowerCase()))
.findFirst()
.orElse(null);
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.enterprise.patterns.front.controller.filters;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class AuditFilter extends BaseFilter {
@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain
) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpSession session = httpServletRequest.getSession(false);
if (session != null && session.getAttribute("username") != null) {
request.setAttribute("username", session.getAttribute("username"));
}
chain.doFilter(request, response);
}
}

View File

@ -0,0 +1,40 @@
package com.baeldung.enterprise.patterns.front.controller.filters;
import com.baeldung.enterprise.patterns.front.controller.commands.FrontCommand;
import com.baeldung.enterprise.patterns.front.controller.commands.LoginCommand;
import javax.servlet.FilterChain;
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;
import java.io.IOException;
public class AuthenticationFilter extends BaseFilter {
private OnIntercept callback;
public AuthenticationFilter(OnIntercept callback) {
this.callback = callback;
}
@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain
) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
HttpSession session = httpServletRequest.getSession(false);
if (session == null || session.getAttribute("username") == null) {
FrontCommand command = new LoginCommand();
command.init(httpServletRequest, httpServletResponse);
command.process();
callback.intercept();
} else {
chain.doFilter(request, response);
}
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.enterprise.patterns.front.controller.filters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
public abstract class BaseFilter implements Filter {
private static final Logger log = LoggerFactory.getLogger(BaseFilter.class);
protected FilterConfig filterConfig;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
log.info("Initialize filter: {}", getClass().getSimpleName());
this.filterConfig = filterConfig;
}
@Override
public void destroy() {
log.info("Destroy filter: {}", getClass().getSimpleName());
}
}

View File

@ -0,0 +1,30 @@
package com.baeldung.enterprise.patterns.front.controller.filters;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter(servletNames = "front-controller")
public class EncodingFilter extends BaseFilter {
private String encoding;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
super.init(filterConfig);
this.encoding = filterConfig.getInitParameter("encoding");
}
@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain
) throws IOException, ServletException {
String encoding = request.getParameter("encoding");
if (encoding == null) {
encoding = this.encoding;
}
response.setCharacterEncoding(encoding);
chain.doFilter(request, response);
}
}

View File

@ -0,0 +1,28 @@
package com.baeldung.enterprise.patterns.front.controller.filters;
import javax.servlet.Filter;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
public class FilterChainImpl implements javax.servlet.FilterChain {
private Iterator<Filter> filters;
public FilterChainImpl(Filter... filters) {
this.filters = Arrays.asList(filters).iterator();
}
@Override
public void doFilter(
ServletRequest request,
ServletResponse response
) throws IOException, ServletException {
if (filters.hasNext()) {
Filter filter = filters.next();
filter.doFilter(request, response, this);
}
}
}

View File

@ -0,0 +1,21 @@
package com.baeldung.enterprise.patterns.front.controller.filters;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class FilterManager {
public static void process(
HttpServletRequest request,
HttpServletResponse response,
OnIntercept callback
) throws ServletException, IOException {
FilterChain filterChain = new FilterChainImpl(
new AuthenticationFilter(callback),
new AuditFilter()
);
filterChain.doFilter(request, response);
}
}

View File

@ -0,0 +1,39 @@
package com.baeldung.enterprise.patterns.front.controller.filters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@WebFilter(servletNames = "front-controller")
public class LoggingFilter extends BaseFilter {
private static final Logger log = LoggerFactory.getLogger(LoggingFilter.class);
@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain
) throws IOException, ServletException {
chain.doFilter(request, response);
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
String username = (String) httpServletRequest.getAttribute("username");
if (username != null && username.length() > 0) {
username = username.concat("@");
} else {
username = "";
}
String intro = "Request";
if (username.length() > 0) {
intro = "Authenticated request";
}
log.info("{} from '{}{}': {}?{}", intro, username, request.getRemoteAddr(),
httpServletRequest.getRequestURI(), request.getParameterMap());
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.enterprise.patterns.front.controller.filters;
public interface OnIntercept {
void intercept();
}

View File

@ -0,0 +1,23 @@
package com.baeldung.enterprise.patterns.front.controller.filters;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter(servletNames = "front-controller")
public class VisitorCounterFilter extends BaseFilter {
private int counter;
@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain
) throws IOException, ServletException {
request.setAttribute("counter", ++counter);
chain.doFilter(request, response);
}
}

View File

@ -0,0 +1,13 @@
<!DOCTYPE html>
<html>
<head>
<title>Bookshelf: Title found</title>
</head>
<body>
<p>Our Bookshelf contains this title:</p>
<h2>${book.getTitle()}</h2>
<p>Author: ${book.getAuthor()}</p>
<input type="submit" value="Buy it: ${book.getPrice()}$">
<%@include file="visitor-counter.jsp"%>
</body>
</html>

View File

@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>Bookshelf: Title not found</title>
</head>
<body>
<p>Our Bookshelf doesn't contains this title:</p>
<h2>${param.get("title")}</h2>
<%@include file="visitor-counter.jsp"%>
</body>
</html>

View File

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html>
<head>
<title>Bookshelf: Login</title>
</head>
<body>
<p>Please input a username:</p>
<h2>Login</h2>
<form action="/intercepting-filter/?command=Login" method="POST">
<input type="text" name="username" placeholder="Username">
<input type="hidden" name="redirect" value="${redirect}">
<input type="submit" value="Proceed">
</form>
</body>
</html>

View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<title>Bookshelf: Command unknown</title>
</head>
<body>
<p>Sorry, this command is not known!</p>
<%@include file="visitor-counter.jsp"%>
</body>
</html>

View File

@ -0,0 +1,2 @@
<hr/>
<p>You are visitor #${counter}!</p>