如何从WEB-INF加载图像?

时间:2015-02-12 06:32:27

标签: java-ee servlets servlet-filters servlet-3.0 web-inf

只要图像在web中,这就可以正常工作;如何在WEB-INF

中加载图片
NetBeansProjects/WebApplication/
├── build.xml
├── nbproject
│   ├── ant-deploy.xml
│   ├── build-impl.xml
│   ├── genfiles.properties
│   ├── private
│   ├── project.properties
│   └── project.xml
├── README.md
├── src
│   ├── conf
│   └── java
└── web
    ├── duke.gif
    ├── index.html
    └── WEB-INF

7 directories, 9 files

HTML:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>login</title>
    </head>
    <body>
        <img src="http://localhost:8080/WebApplication/duke.gif"> 

        my name is thufir, bjfdkl34363fjsl, what's yours?
        <form name="user_name_form" action="controller" method="POST">
            login: <input type="text" name="login" value="" size='20' />
            <p>
                <input type="submit">
            </p>
        </form>

    </body>
</html>

JSP:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>login</title>
    </head>
    <body>
        <img src="${sessionScope.authorization.duke}"> 
        my name is ${requestScope.controller.myName}, ${requestScope.controller.myId}, what's yours?
        <form name="user_name_form" action="controller" method="POST">
            login: <input type="text" name="login" value="" size='20' />
            <p>
                <input type="submit">
            </p>
        </form>
        ${sessionScope.authorization.greeting}
    </body>
</html>

过滤器:

package net.bounceme.dur.webapp.filter;

import net.bounceme.dur.webapp.tokens.AuthenticationToken;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
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.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@WebFilter(
        filterName = "authenticationFilter",
        description = "authentication",
        urlPatterns = "/*",
        initParams = {
            @WebInitParam(name = "1", value = "bart"),
            @WebInitParam(name = "2", value = "homer")})

public class AuthenticationFilter implements Filter {

    private static final Logger log = Logger.getLogger(AuthenticationFilter.class.getName());
    private FilterConfig filterConfig = null;
    private final Map<String, String> mapOfUsers = new HashMap<>();
    private final AuthenticationToken token = new AuthenticationToken();
    private final String className = AuthenticationFilter.class.getName();
    private Map<String, String> parameters = new HashMap<>();
    private Map<String, String> users = new HashMap<>();
    private boolean auth = false;
    private String contextPath;

    public AuthenticationFilter() {
    }

    private void doBeforeProcessing(ServletRequest request, ServletResponse response) throws IOException, ServletException {
        log.fine("do before processing..");  //init?
    }

    private void doAfterProcessing(ServletRequest request, ServletResponse response) throws IOException, ServletException {
        log.fine("do after processing");  //add image here?
    }

    private void initFilterParams() {
        log.info(className + "\tinitFilterParams..");
        Enumeration parameterNames = filterConfig.getInitParameterNames();
        users = new HashMap<>();  //?
        String name = null;
        String val = null;
        while (parameterNames.hasMoreElements()) {
            name = parameterNames.nextElement().toString();
            val = filterConfig.getInitParameter(name);
            users.put(name, val);
        }
        log.info(className + "\n" + users);
        log.info(className + "\t..initFilterParams");
    }

    private void initParams(HttpServletRequest request) {
        log.info(className + "\tinitParams..");
        parameters = new HashMap<>();  //?
        Enumeration<String> params = request.getParameterNames();
        String name = null;
        String val = null;
        while (params.hasMoreElements()) {
            name = params.nextElement();
            val = request.getParameter(name);
            parameters.put(name, val);
        }
        log.info(className + "\n" + parameters);
        log.info(className + "\t..initParams");
    }

    private void setToken(HttpServletRequest request) {
        initParams(request);
        String login = null;
        if (parameters.containsKey("login")) {
            login = parameters.get("login").toLowerCase();
            token.setLogin(login);
            if (users.containsValue(login)) {
                auth = true;
                token.setGreeting("welcome " + login + " you've been authorized.");
            } else {
                auth = false;
                token.setGreeting("welcome " + login);
            }
        } else {
            auth = false;
        }
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.setAttribute("authorization", token);
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        log.info(className + "do filter..");
        setToken((HttpServletRequest) request);
        chain.doFilter(request, response);
        log.info(className + "..do filter");
    }

    public FilterConfig getFilterConfig() {
        return (this.filterConfig);
    }

    public void setFilterConfig(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
    }

    @Override
    public void destroy() {
    }

    @Override
    public void init(FilterConfig filterConfig) {
        log.info(className + "\tinit..");
        this.filterConfig = filterConfig;
        if (filterConfig != null) {
            log.fine("SessionCheckFilter:Initializing filter");
        } else {
            log.warning("null filterConfig");
        }
        String context = filterConfig.getServletContext().getServletContextName();
        String path = filterConfig.getServletContext().getContextPath();
        contextPath = "http://localhost:8080" + context + path;
        String duke = contextPath + "/duke.gif";
        token.setDuke(duke);
        initFilterParams();
        log.info(token.toString());
        log.info(className + "\t..init");
    }

    @Override
    public String toString() {
        return token.toString();
    }

    private void sendProcessingError(Throwable t, ServletResponse response) {
        log.fine("send processing error");
        String stackTrace = getStackTrace(t);

        if (stackTrace != null && !stackTrace.equals("")) {
            try {
                response.setContentType("text/html");
                try (PrintStream ps = new PrintStream(response.getOutputStream()); PrintWriter pw = new PrintWriter(ps)) {
                    pw.print("<html>\n<head>\n<title>Error</title>\n</head>\n<body>\n"); //NOI18N
                    pw.print("<h1>The resource did not process correctly</h1>\n<pre>\n");
                    pw.print(stackTrace);
                    pw.print("</pre></body>\n</html>"); //NOI18N
                }
                response.getOutputStream().close();
            } catch (Exception ex) {
            }
        } else {
            try {
                try (PrintStream ps = new PrintStream(response.getOutputStream())) {
                    t.printStackTrace(ps);
                }
                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) {
        }
        log.warning(stackTrace);
        return stackTrace;
    }

}

我在Linux上使用Glassfish;用Netbeans构建WAR。使用Eclipse时它是否有所不同?我可以看到它可能会有所不同,具体取决于容器(Jboss v glassfish v等),但这肯定与IDE无关?

0 个答案:

没有答案