防止用户直接访问jsp文件 [英] prevent from a user to access directly to a jsp file
问题描述
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屋!