JSF Login with HttpServletRequest

五迷三道 提交于 2019-12-08 13:11:09

问题


i found a solution in stackoverflow how to code a login in JSF using HttpServletRequest. First things first, the login.xhtml:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html">

<h:head>
    <title>Login</title>
</h:head>
<h:body>
    <h3>Login here</h3>
    <h:form id="loginForm">
        <h:outputLabel for="username" value="Username:" />
        <h:inputText value="#{loginService.userName}" id="username" requried="true" />
        <br/>
        <h:outputLabel for="password" value="Password:" />
        <h:inputSecret value="#{loginService.password}" id="password" requried="true" />
        <br/>
        <h:commandButton id="button" value="Login" action="#{loginService.doLogin}" />
        <br/>
        <h:commandLink action="#{navigationService.redirectToIndex}" value="Home" />
        <br/>
        <h:messages />
        <br/>
    </h:form>
</h:body>

The loginService:

@Named
@SessionScoped
public class LoginService implements Serializable {

private String userName = "";
private String password = "";
@Inject
private NavigationService navigationService = null;
@Inject
private String originalURL = "";

/**
 * 
 */
@PostConstruct
public void init() {
    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();

    this.originalURL = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_REQUEST_URI);

    if(this.originalURL == null) {
        this.originalURL = externalContext.getRequestContextPath() + navigationService.toIndex();
    } else {
        String originalQuery = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_QUERY_STRING);

        if(originalQuery != null) {
            this.originalURL += "?" + originalQuery;
        }
    }
}

/**
 * 
 * @return
 * @throws IOException 
 */
public void doLogin() throws IOException {
    FacesContext context = FacesContext.getCurrentInstance();
    ExternalContext externalContext = context.getExternalContext();
    HttpServletRequest request = (HttpServletRequest)externalContext.getRequest();

    try {
        request.login(this.userName, this.password);

        User user = dao.findUserByUserName(userName);

        externalContext.getSessionMap().put("user", user);
        externalContext.redirect(this.originalURL);
    } catch(ServletException e) {
        context.addMessage(null, new FacesMessage("Unknown login"));
    } catch (NoSuchUserException e) {
        context.addMessage(null, new FacesMessage(e.getMessage()));
    }
}

/**
 * 
 * @return
 * @throws IOException 
 */
public void doLogout() throws IOException {
    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();

    externalContext.invalidateSession();
    externalContext.redirect(externalContext.getRequestContextPath() + navigationService.toLogin());
}

// Getters and Setters
}

The only thing i still need to know is now:

Where can i define for which pages login is needed?


回答1:


A suggested solution is: putting all the pages requiring logging under one place (folder, ex: "private_section"), and the pages that don't need it (public access) are to be put wherever in the project context except under the folder "private_section". Then you can use a simple filter to control accessing to the private region (to our folder), and through this pattern (first annotation) you can specify the region to be controlled :

// imports    

@WebFilter("/private_section/*")
public class LoggingFilter implements Filter {


@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest)request;
    HttpServletResponse res = (HttpServletResponse)response;
    UserBean user = (UserBean) req.getSession().getAttribute("user");         
    if (user != null && user.isLoggedIn()){
            chain.doFilter(request,response);
    }  
    else res.sendRedirect(req.getContextPath()+"/index.xhtml");
}

// other overriden methods


来源:https://stackoverflow.com/questions/20050355/jsf-login-with-httpservletrequest

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!