防止用户直接访问jsp页面的几种办法:
 

1.把JSP页面放在WEB-INF目录下,存放在此目录或者它的子目录里的任何东西都受到了保护。

不过,不太推荐,因为并非所有的容器都具有这种保护机制,例如WebLogic就做不到这一点。


 2.使用servlet过滤器或者struts过过滤器来过滤对jsp页面的请求。

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;


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.HttpServletRequestWrapper;

public class CharsetFilter implements Filter {


	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		try{
			HttpServletRequest httpRequest = (HttpServletRequest)request;
			HttpServletResponse httpResponse = (HttpServletResponse)response;
			//过滤直接访问jsp的页面
			String uri = httpRequest.getRequestURI();
			if(uri.endsWith(".jsp")){
				httpResponse.sendRedirect(request.getServletContext().getContextPath()+"/login/preLoginAction.jspx");
				return;
			}
				
			String method = httpRequest.getMethod().toLowerCase();
			/*System.out.println("### method is "+ method);*/
			if(method.equals("post")){
				//如果 是post,即表单方法,直接设置charset即可
				request.setCharacterEncoding("UTF-8");
			}else if(method.equals("get")){
				request.setCharacterEncoding("UTF-8");
				request = new HttpServletRequestWrapper(httpRequest){
					@Override
					public Map<String, String[]> getParameterMap() {
						Map<String,String[]> map = super.getParameterMap();
						Set<Entry<String,String[]>> set = map.entrySet();
						Iterator<Entry<String,String[]>> it = set.iterator();
						Map<String,String[]> newmap = new HashMap<String, String[]>();  
						while(it.hasNext()){
							Entry<String,String[]> entry = it.next();
							
							String[] values = entry.getValue();
							String name = entry.getKey();
							//System.out.println("KEY:"+entry.getKey()+"VALUE: "+entry.getValue());
								{
								String newvalues[] = new String[values.length];
								for(int i=0; i<values.length;i++){
									String value = values[i];
									try {
										value = new String(value.getBytes("iso8859-1"),"UTF-8");
									} catch (UnsupportedEncodingException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
									newvalues[i] = value; //解决乱码后封装到Map中
								}


								newmap.put(name, newvalues);
								
							}
						}
						return newmap;
					}
					@Override
					public String[] getParameterValues(String name) {
						// TODO Auto-generated method stub
						return super.getParameterValues(name);
					}
					@Override
					public String getParameter(String str){
						try{
							String strTr = new String(super.getParameter(str).getBytes("ISO-8859-1"),"UTF-8");
							return strTr;
						}catch(Exception e){
							return null;
						}
					}
				};
			}
			chain.doFilter(request, response);
		}catch(Exception e){
			
		}
		
	}


	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}


}

或者

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.Writer;

/**
 * Created by a on 2016/3/17.
 */
public class AdminSessionFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();

        String uri = request.getRequestURI();
        if (uri.indexOf("/img/") < 0
                && uri.indexOf("/css/") < 0
                && uri.indexOf("/login/") < 0
                && uri.indexOf("/zhiboapi/") < 0
                && session.getAttribute("admin") == null) {//在没有登陆的情况下,除了这几个不能直接访问其他的目录
            Writer writer = null;
            try {
                writer = response.getWriter();
                writer.write("<script>top.location.href=\"" + request.getContextPath() + "/login/loginAction.jspx\"</script>");//framesetbug,直播跳转到首页
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    writer.flush();
                    writer.close();
                } catch (IOException e) {
                }
            }

        } else {
            try {
                filterChain.doFilter(servletRequest, servletResponse);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void destroy() {

    }
}



 3.在部署文件web.xml中使用安全限制.这个比过滤器容易,不用另外编写一个过滤器了.配置如下:

<span style="margin: 0px; padding: 0px; border: 0px; font-size: 18px; background: transparent;"><security-constraint>
   <web-resource-collection>
       <web-resource-name>JSPs</web-resource-name>
       <url-pattern>/web/*</url-pattern><!-- 拒绝直接访问web文件夹下的所有页面 -->
   </web-resource-collection>
   <auth-constraint/>
</security-constraint>
 
<login-config>
   <auth-method>BASIC</auth-method><!-- 验证方式(BASIC/FORM) -->
</login-config></span>


<span style="margin: 0px; padding: 0px; border: 0px; font-size: 18px; background: transparent;"> <web-resource-name>QNJYZXT</web-resource-name><!--<span style="margin: 0px; padding: 0px; border: 0px; font-family: Arial, Helvetica, sans-serif; background: transparent;">QNJYZXT为</span><span style="margin: 0px; padding: 0px; border: 0px; font-family: Arial, Helvetica, sans-serif; background: transparent;">包含资源的文件名(可以使项目名称)</span>--></span>
<span style="margin: 0px; padding: 0px; border: 0px; font-size: 18px; background: transparent;"><url-pattern>/web/*</url-pattern><!-- 拒绝直接访问web文件夹下的所有页面 --></span>


还可以设置限制访问角色

JSP页面中限制对 Web 资源的访问》这篇文章中有介绍

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐