防止用户直接访问jsp文件 [英] prevent from a user to access directly to a jsp file

查看:128
本文介绍了防止用户直接访问jsp文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个Servlet,它将请求转发到包含产品列表的jsp文件. 例如,Login.java是一个将请求(成功登录后)转发到Products.jsp的servlet. 现在,在Products.jsp中,我必须首先检查该用户确实已登录:

<% if (request.getSession().getAttribute("username") == null) {
    response.sendRedirect("/store/login");
    return;
} %>

这是为了防止用户仅通过编写localhost:8080/store/Products.jsp即可看到产品. 我在这里阅读了一些帖子,最好避免在jsp文件中编写Java代码. 所以我的问题是,有没有更优雅的方法来解决这个问题?

解决方案

是-将所有JSP文件放入WEB-INF/(例如-WEB-INF/jsp),并且仅从servlet转发给它们.例如,如果一个servlet映射到/foo,则它的doGet()方法可以执行您编写的逻辑,并转发到product.jsp.

尽管对于裸露的servlet来说,它可能变得太冗长,所以像Spring MVC这样的框架可能会非常有帮助.

通常,身份验证检查由Filter执行-您放置了一个过滤器来检查每个请求,如果用户未通过身份验证,则过滤器会重定向.

let's say i have a servlet that forwards a request to a jsp file that contains a list of products. for example, Login.java is a servlet that forwards a request (upon successful login) to Products.jsp. now, in Products.jsp i have to check first that user is indeed logged in:

<% if (request.getSession().getAttribute("username") == null) {
    response.sendRedirect("/store/login");
    return;
} %>

this is in order to prevent the user from seeing the products just by writing localhost:8080/store/Products.jsp. I read here some posts that it is best to avoid writing java code in jsp files. so my question is, is there a more elegant way to solve this problem?

解决方案

Yes - put all JSP files in WEB-INF/ (for example - WEB-INF/jsp), and only forward to them from servlets. For example, if a servlet is mapped to /foo, then its doGet() method can perform the logic you've written, and do the forward to product.jsp.

It might become too verbose with bare servlets though, so a framework like Spring MVC can be very helpful.

Generally, authentication checks are preformed by a Filter though - you put a filter which checks each request and if a user is not authenticated, the filter redirects.

这篇关于防止用户直接访问jsp文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆