如何禁止从jl页面的url直接访问页面

时间:2015-11-03 12:24:19

标签: java jsp servlets filter servlet-filters

我创建了一个Web应用程序。一切正常。但是,如果用户还没有登录,他们可以通过URL访问其他jsp页面。我想停止访问网址。我看到一些例子,它显示了过滤器的用法。我是过滤器的新手,我不知道如何实现它。我正在使用servlets,dao和jsp页面。

请建议我怎么做。我想为所有jsp或servlets页面创建一个过滤器。

的web.xml

<?xml version="1.0" encoding="UTF-8"?>

    <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
        <filter>
            <filter-name>MyFilter</filter-name>
            <filter-class>com.eis.servlet.MyFilter</filter-class>
        </filter>
        <filter-mapping>
            <filter-name>MyFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
        <servlet>
            <servlet-name>login</servlet-name>
            <servlet-class>com.eis.servlet.LoginServlet</servlet-class>
        </servlet>
        <servlet>
            <servlet-name>DayWiseServlet</servlet-name>
            <servlet-class>com.eis.servlet.DayWiseServlet</servlet-class>
        </servlet>
        <servlet>
            <servlet-name>RegisterServlet</servlet-name>
            <servlet-class>com.eis.servlet.RegisterServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>login</servlet-name>
            <url-pattern>/LoginServlet</url-pattern>
        </servlet-mapping>
        <servlet>
            <servlet-name>RetrieveServlet</servlet-name>
            <servlet-class>com.eis.servlet.RetrieveServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>RetrieveServlet</servlet-name>
            <url-pattern>/RetrieveServlet</url-pattern>
        </servlet-mapping>
        <servlet>
            <servlet-name>TimeSheet</servlet-name>
            <servlet-class>com.eis.servlet.TimeSheet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>TimeSheet</servlet-name>
            <url-pattern>/TimeSheet</url-pattern>
        </servlet-mapping>
        <servlet-mapping>
            <servlet-name>DayWiseServlet</servlet-name>
            <url-pattern>/DayWiseServlet</url-pattern>
        </servlet-mapping>
        <servlet-mapping>
            <servlet-name>RegisterServlet</servlet-name>
            <url-pattern>/RegisterServlet</url-pattern>
        </servlet-mapping>
        <welcome-file-list>
            <welcome-file>/index.jsp</welcome-file>
        </welcome-file-list>
        <session-config>
            <session-timeout>15</session-timeout>
        </session-config>
    </web-app>

loginservlet.java

public class LoginServlet extends HttpServlet{  

    private static final long serialVersionUID = 1L;  

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)    
            throws ServletException, IOException {    


        response.setContentType("text/html");    
        PrintWriter out = response.getWriter();    

        String n=request.getParameter("Emp_id");    
        String p=request.getParameter("Pwd");   
        String Usertype=request.getParameter("usertype"); 


        HttpSession session = request.getSession(false);  
        if(session!=null){
        session.setAttribute("name", n);  
        session.setAttribute("usertype", Usertype);
        }
        if(LoginDao.validate(n,p)){    
            RequestDispatcher rd=request.getRequestDispatcher("/daywise.jsp");    
            rd.forward(request,response);    
        }    
        else{    
            out.print("<p style=\"color:red\">Sorry Employee ID or password error</p>");    
            RequestDispatcher rd=request.getRequestDispatcher("/index.jsp");    
            rd.include(request,response);  

        }    

        out.close();    
    }
     protected void doPost(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }


}   

myfilter:

public class MyFilter implements Filter{  

@Override
public void init(FilterConfig config) throws ServletException {}  

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {  

    HttpServletRequest req = (HttpServletRequest)request;
    HttpServletResponse resp = (HttpServletResponse)response;

        if(null==((String) req.getSession().getAttribute("empid")) || ((String) req.getSession().getAttribute("empid")).equals("")){
            chain.doFilter(req, resp);
    } else {
      resp.sendRedirect("/WebTimeSheet/index.jsp");
  }
    }  
@Override
    public void destroy() {}  
}  

Loginpage:

<form action="LoginServlet" method="post">  
    <fieldset style="width: 300px">  
        <legend> Login to App </legend>   
        <table>  
            <tr>  
                <td>User ID</td>  
                <td><input type="text" name="Emp_id" required="required" /></td>  
            </tr>  
            <tr>  
                <td>Password</td>  
                <td><input type="password" name="Pwd" required="required" /></td>  
            </tr> 
           <tr>  
                <td>User Type</td>  
                <td> <select name="usertype">
                <option>Employee</option>
                <option>Manager</option>
                <option>Admin</option>
            </select></td>   
            </tr>
            <tr>  
                <td><input type="submit" value="Login" /></td>  
            </tr>  
        </table>  
    </fieldset>  
</form>  
</body>  
<%@include file="/footer.jsp" %>
</html>  

我所有的jsp页面都在Web-inf文件夹之外的网页文件夹中。 Web-inf文件夹只有web.xml init

header.jsp中

 <c:choose>
             <c:when test="${usertype eq 'Employee'}">
        <div class="nav">      
            <ul><li class="container"><img src="${pageContext.request.contextPath}/images/enabling.jpg" /></li>
            <li class="current"><a href="WEB-INF/daywise.jsp">DayWise TimeSheet</a></li>
            <li><a href="WEB-INF/timesheet.jsp">Weekly TimeSheet</a></li>
            </ul>
        </div>
     </c:when>
     <c:when test="${usertype eq 'Manager'}">
        <div class="nav">      
            <ul><li class="container"><img src="${pageContext.request.contextPath}/images/enabling.jpg" /></li>
            <li class="current"><a href="/WEB-INF/daywise.jsp">DayWise TimeSheet</a></li>
            <li><a href="WEB-INF/timesheet.jsp">Weekly TimeSheet</a></li>
            <li><a href="WEB-INF/newemployee.jsp">Add New Employeer</a></li>
            <li><a href="WEB-INF/retrieve.jsp">Retrieve TimeSheet</a></li>
            </ul>
        </div>
     </c:when>

3 个答案:

答案 0 :(得分:4)

首先,JSP不应该用于提供请求,它们应该用于呈现视图。 Servlet应该用于提供请求,然后转发给JSP。

以下是一个例子:

basename()

在web.xml中:

pathinfo()

在此示例中,servlet转发到WEB-INF目录中的JSP。通过将所有JSP放在WEB-INF目录中,这意味着无法直接请求它们。

现在你有一个Servlet,你可以设置一个Servlet过滤器:

public class HelloWorld extends HttpServlet {

  public void doGet(HttpServletRequest request,
                HttpServletResponse response)
        throws ServletException, IOException
  {
     //do some stuff

     //forward to JSP to show result
     String nextJSP = "/WEB_INF/result.jsp";
     RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
     dispatcher.forward(request,response);
  }
}

在web.xml中:

<servlet>
  <servlet-name>HelloWorldServlet</servlet-name>
  <servlet-class>your.package.HelloWorld</servlet-class>
</servlet>

<servlet-mapping>
  <servlet-name>HelloWorldServlet</servlet-name>
  <url-pattern>/someurl</url-pattern>
</servlet-mapping>

这样,任何符合模式public class MyFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { if (isLoggedIn) { //if user is logged in, complete request chain.doFilter(req, res); } else { //not logged in, go to login page res.sendRedirect("/login"); } } 的网址都会被过滤,以便需要登录。

答案 1 :(得分:1)

您需要使用servlet过滤器并匹配所有请求。

在该过滤器中,您需要检查授权。

以下是official docs with example

答案 2 :(得分:0)

您可以在响应标头中设置身份验证Cookie

Cookie someCookie = new Cookie("cookie_name","some_value" );

response.addCookie(someCookie)

然后,在您的过滤器中,您可以决定根据Cookie值调用chain.doFilter(req, res)

您可以通过cookie.setMaxAge();来控制Cookie年龄。将最大年龄设置为&#39; 0&#39;退出。