JSP:如何检查用户是否已登录?

son*_*nya 11 java jsp authorization servlets servlet-filters

我正在学习Java Web,但我遇到了一些问题,需要帮助.我使用了template.jsp,其中包括header.jsp,footer.jsp,login.jsp(模板的左侧)和${param.content}.jsp.对于名为X.jsp的每个页面,我创建了另一个具有以下内容的jsp,因为我希望每个页面具有相同的布局:

<jsp:include page="template.jsp">
    <jsp:param name="content" value="X"/>
    <jsp:param name="title" value="Start navigate"/>`enter code here`
</jsp:include>
Run Code Online (Sandbox Code Playgroud)

例如,当我点击Review链接时,我想重定向到Review.jsp,但是我遇到了一些问题.在footer.jsp我有这样的事情:

(...)
< a href =" Review.jsp "> Review </a>
(...)
Run Code Online (Sandbox Code Playgroud)

登录后,我尝试单击Review,它将我发送到Review.jsp,但它告诉我我没有登录.我使用Spring Framework,Tomcat 7,Eclipse,MySQL.当我登录时,我创建了一个cookie:

String timestamp = new Date().toString();
String sessionId = DigestUtils.md5Hex(timestamp);
db.addSession(sessionId, username, timestamp);
Cookie sid = new Cookie("sid", sessionId);
response.addCookie(sid);
Run Code Online (Sandbox Code Playgroud)

对于每种方法,我都有类似的东西(我在教程中看到过):

@RequestMapping(value = "/writeReview", method = RequestMethod.GET)
public String nameMethod(@CookieValue("sid") String sid,...)
Run Code Online (Sandbox Code Playgroud)

使用sid,我可以找出谁是用户.我有一个包含用户帐户和其他一些表的数据库.问题是,当我点击评论或其他任何内容时,它会告诉我我没有登录.我该怎么办?

更新:
我将JavaBean用于user和login.jsp.具有登录文本框的JSP,当我单击按钮登录时,我有一个GET方法.

@RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView createCookie(
  @RequestParam("username") String username, @RequestParam("password") String password,
  HttpServletRequest request, HttpServletResponse response) throws SQLException {
      //code for creating the cookie here, after testing if the user is in my database
}
Run Code Online (Sandbox Code Playgroud)

对于每个页面,我发送sid,我有一个模型的属性,用户名:

public String methodName(@CookieValue(required = false) String sid, Model model) {
    if (sid != null) {
        User user = getUserBySid(sid);
        model.addAttribute("user", user);
    }
    (..other data.)
    return "nameJSP.jsp";
}
Run Code Online (Sandbox Code Playgroud)

我在每个JSP中检查用户名是否为空,这样我就可以看到用户是否已登录.应用程序运行良好,如果我没有点击页眉或页脚中的链接,它会传递参数.问题是我必须传递一个JSP中的参数,该参数是布局的实际内容到页脚引用的JSP,这个JSP将是我布局的下一个内容.布局仅识别内容和标题:

<title>${param.title}</title>
(I didn't paste all the code, I use a table <table>....)
<%@ include file="header.jsp"%>
<%@ include file="login.jsp"%>  
<jsp:include page="${param.content}.jsp"/> 
<%@ include file="footer.jsp"%>
Run Code Online (Sandbox Code Playgroud)

那么如何在这个JSP中包含一个参数,该参数将从另一个JSP接收?此外,它必须由layout.jsp访问并发送到页脚或标题?

<jsp:include page="layout.jsp">
    <jsp:param name="content" value="X"/>
    <jsp:param name="title" value="Start navigate"/>
</jsp:include>
Run Code Online (Sandbox Code Playgroud)

inf*_*k01 13

要将一些参数传递给包含的JSP:

<jsp:include page="somePage.jsp" >
    <jsp:param name="param1" value="someValue" />
    <jsp:param name="param2" value="anotherParam"/>
    ....
</jsp:include>
Run Code Online (Sandbox Code Playgroud)

你已经在做了.

好的,问题的细节不是很清楚,但我明白了.
其中一个解决方案可能如下.

在" 登录"操作中,如果身份验证成功,请创建HttpSession并为经过身份验证的用户设置属性:

if (/* authentication was successfull */) {
    request.getSession().setAttribute("loggedInUser", user);
    ...
}
Run Code Online (Sandbox Code Playgroud)

在您控制的代码中,如果用户已登录,只需检查是否存在相应的HttpSession属性:

HttpSession session = request.getSession(false);
if (session == null || session.getAttribute("loggedInUser") == null) {
    // user is not logged in, do something about it
} else {
    // user IS logged in, do something: set model or do whatever you need
}
Run Code Online (Sandbox Code Playgroud)


或在你的JSP页面,您可以检查用户是否使用登录JSTL标签作为例子说明了通过BalusC 这里:

...
<c:if test="${not empty loggedInUser}">
    <p>You're still logged in.</p>
</c:if>
<c:if test="${empty loggedInUser}">
    <p>You're not logged in!</p>
</c:if>
...
Run Code Online (Sandbox Code Playgroud)

过滤救援

但通常,您检查用户是否已登录以限制对某些页面的访问(因此只有经过身份验证的用户才能访问它们).你编写了一些实现javax.servlet.Filter的类 .

以下是我的一个项目的LoginFilter示例:

package com.example.webapp.filter;

import java.io.IOException;

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

/**
 * The purpose of this filter is to prevent users who are not logged in
 * from accessing confidential website areas. 
 */
public class LoginFilter implements Filter {

    /**
     * @see Filter#init(FilterConfig)
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    /**
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("loggedInUser") == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
        } else {
            chain.doFilter(request, response);
        }
    }


    /**
     * @see Filter#destroy()
     */
    @Override
    public void destroy() {}

}
Run Code Online (Sandbox Code Playgroud)

在这个项目中,我使用普通的servlet和没有Spring的JSP,但你会明白这个想法.

当然,您必须配置web.xml才能使用此过滤器:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    ...
    <filter>
        <filter-name>Login Filter</filter-name>
        <filter-class>com.example.webapp.filter.LoginFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>Login Filter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    ...
</web-app>
Run Code Online (Sandbox Code Playgroud)


注意:
如果您使用的是支持Servlet 3.0及更高版本的Web容器Application Server,则可以使用@WebFilter批注对过滤器类进行批注,在这种情况下,无需在部署描述符中配置过滤器(web.xml) .请参阅此处使用@WebFilter注释和更多过滤器相关信息的示例.

希望这会帮助你.