jsf如何与数据库连接

Authentication mechanism allows users to have secure access to the application by validating the username and password. We will be using JSF view for login, DAO object ,HttpSession for session management, JSF managed bean and mysql database.

身份验证机制允许用户通过验证用户名和密码来安全访问应用程序。 我们将使用JSF视图进行登录,使用DAO对象,使用HttpSession进行会话管理,使用JSF管理的bean和mysql数据库。

Lets now look in detail as how to create a JSF login logout authentication mechanism in JSF application.

现在让我们详细介绍如何在JSF应用程序中创建JSF登录注销身份验证机制。

Step 1: Create the table Users in mysql database as

步骤1 :在mysql数据库中创建表Users为

CREATE TABLE Users(
uid int(20) NOT NULL AUTO_INCREMENT,
uname VARCHAR(60) NOT NULL,
password VARCHAR(60) NOT NULL,
PRIMARY KEY(uid));

Here we create user table with uid as the primary key, username and password fields with not null constraints.

在这里,我们以uid作为主键,用户名和密码字段创建用户表,且不存在空约束。

Step 2: Insert data into the table Users as;

步骤2 :将数据插入表Users as;

INSERT INTO Users VALUES(1,'adam','adam');

Before we move on to our project related code, below image shows the project structure in Eclipse. Just create a dynamic web project and convert it to maven to get the project stub and then keep on adding different components.

在继续进行与项目相关的代码之前,下图显示了Eclipse中的项目结构。 只需创建一个动态Web项目并将其转换为Maven即可获得项目存根,然后继续添加其他组件。

Step 3: Create the JSF login page login.xhtml as;

步骤3 :创建JSF登录页面login.xhtml为;

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml"xmlns:h="https://java.sun.com/jsf/html">
<h:head><title>login</title>
</h:head>
<h:body><h:form><h3>JSF Login Logout</h3><h:outputText value="Username" /><h:inputText id="username" value="#{login.user}"></h:inputText><h:message for="username"></h:message><br></br><br></br><h:outputText value="Password" /><h:inputSecret id="password" value="#{login.pwd}"></h:inputSecret><h:message for="password"></h:message><br></br><br></br><h:commandButton action="#{login.validateUsernamePassword}"value="Login"></h:commandButton></h:form>
</h:body>
</html>

Here we are creating a JSF login view page with username and password fields and set values for these fields through the login managed bean. We invoke the validateUsernamePassword method on click of Login button to validate the username and password.

在这里,我们将创建一个包含用户名和密码字段的JSF登录视图页面,并通过登录托管bean为这些字段设置值。 单击登录按钮时,我们将调用validateUsernamePassword方法以验证用户名和密码。

Step 4: Create the managed bean Login.java as;

步骤4 :创建托管bean Login.java为;

package com.journaldev.jsf.beans;import java.io.Serializable;import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;import com.journaldev.jsf.dao.LoginDAO;
import com.journaldev.jsf.util.SessionUtils;@ManagedBean
@SessionScoped
public class Login implements Serializable {private static final long serialVersionUID = 1094801825228386363L;private String pwd;private String msg;private String user;public String getPwd() {return pwd;}public void setPwd(String pwd) {this.pwd = pwd;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}public String getUser() {return user;}public void setUser(String user) {this.user = user;}//validate loginpublic String validateUsernamePassword() {boolean valid = LoginDAO.validate(user, pwd);if (valid) {HttpSession session = SessionUtils.getSession();session.setAttribute("username", user);return "admin";} else {FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_WARN,"Incorrect Username and Passowrd","Please enter correct username and Password"));return "login";}}//logout event, invalidate sessionpublic String logout() {HttpSession session = SessionUtils.getSession();session.invalidate();return "login";}
}

We declare three String variables user, pwd and msg for username, password and error message fields along with the getter and setter methods. We write a method validateUsernamePassword() for validating the username and password field by invoking the LoginDAO class to fetch the username and password from the database and compare it with the front end values passed. If the username and password does not match an error message is displayed as “Incorrect username and password” . Also a logout() method is written to perform logout by invalidating HTTPSession attached.

我们为用户名,密码和错误消息字段以及getter和setter方法声明三个String变量user,pwd和msg。 我们通过调用LoginDAO类以从数据库中获取用户名和密码并将其与传递的前端值进行比较,来编写方法validateUsernamePassword()来验证用户名和密码字段。 如果用户名和密码不匹配,则会显示一条错误消息“错误的用户名和密码”。 此外, logout()写入logout()方法以通过使附加的HTTPSession无效来执行注销。

Step 5: Now create the LoginDAO java class as below. Note that database operations code is not optimized to be used in a real project, I wrote it as quickly as possible because the idea is to learn authentication in JSF applications.

步骤5 :现在创建如下所示的LoginDAO Java类。 请注意,数据库操作代码并未针对在实际项目中使用而进行优化,因此我之所以尽快编写它是因为其思想是在JSF应用程序中学习身份验证。

package com.journaldev.jsf.dao;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;import com.journaldev.jsf.util.DataConnect;public class LoginDAO {public static boolean validate(String user, String password) {Connection con = null;PreparedStatement ps = null;try {con = DataConnect.getConnection();ps = con.prepareStatement("Select uname, password from Users where uname = ? and password = ?");ps.setString(1, user);ps.setString(2, password);ResultSet rs = ps.executeQuery();if (rs.next()) {//result found, means valid inputsreturn true;}} catch (SQLException ex) {System.out.println("Login error -->" + ex.getMessage());return false;} finally {DataConnect.close(con);}return false;}
}

In the validate() method we first establish connection to the database by invoking the DataConnect class getConnection method. We use PreparedStatement to build the query to fetch the data from the database with the user entered values. If we get any data in result set, it means input is valid and we return true, else false.

validate()方法中,我们首先通过调用DataConnect类的getConnection方法建立与数据库的连接。 我们使用PreparedStatement构建查询以使用用户输入的值从数据库中获取数据。 如果在结果集中获得任何数据,则表示输入有效,并且返回true,否则返回false。

Step 6: Create the DataConnect.java class as;

步骤6 :将DataConnect.java类创建为;

package com.journaldev.jsf.util;import java.sql.Connection;
import java.sql.DriverManager;public class DataConnect {public static Connection getConnection() {try {Class.forName("com.mysql.jdbc.Driver");Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/cardb", "pankaj", "pankaj123");return con;} catch (Exception ex) {System.out.println("Database.getConnection() Error -->"+ ex.getMessage());return null;}}public static void close(Connection con) {try {con.close();} catch (Exception ex) {}}
}

We load the JDBC driver using Class.forName method and use DriverManager.getConnection method passing the url, username and password to connect to the database.

我们使用Class.forName方法加载JDBC驱动程序,并使用DriverManager.getConnection方法传递url,用户名和密码来连接数据库。

Step 7: Create SessionUtils.java to obtain and manage session related user information.

步骤7 :创建SessionUtils.java以获取和管理与会话相关的用户信息。

package com.journaldev.jsf.beans;import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;public class SessionUtils {public static HttpSession getSession() {return (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);}public static HttpServletRequest getRequest() {return (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();}public static String getUserName() {HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);return session.getAttribute("username").toString();}public static String getUserId() {HttpSession session = getSession();if (session != null)return (String) session.getAttribute("userid");elsereturn null;}
}

Here we obtain a session for each user logged through the getUserId method thereby associating a session id to a particular user id.

在这里,我们为通过getUserId方法登录的每个用户获得一个会话,从而将会话ID与特定用户ID相关联。

Step 8: Create the authorization filter class as;

步骤8 :将授权过滤器类创建为;

package com.journaldev.jsf.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.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;@WebFilter(filterName = "AuthFilter", urlPatterns = { "*.xhtml" })
public class AuthorizationFilter implements Filter {public AuthorizationFilter() {}@Overridepublic void init(FilterConfig filterConfig) throws ServletException {}@Overridepublic void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {try {HttpServletRequest reqt = (HttpServletRequest) request;HttpServletResponse resp = (HttpServletResponse) response;HttpSession ses = reqt.getSession(false);String reqURI = reqt.getRequestURI();if (reqURI.indexOf("/login.xhtml") >= 0|| (ses != null && ses.getAttribute("username") != null)|| reqURI.indexOf("/public/") >= 0|| reqURI.contains("javax.faces.resource"))chain.doFilter(request, response);elseresp.sendRedirect(reqt.getContextPath() + "/faces/login.xhtml");} catch (Exception e) {System.out.println(e.getMessage());}}@Overridepublic void destroy() {}
}

We implement the standard filter class by overriding the destroy and doFilter methods. In the doFilter method we will redirect user to login page if he tries to access other page without logging in.

我们通过覆盖destroy和doFilter方法来实现标准过滤器类。 如果用户尝试不登录而访问其他页面,则在doFilter方法中,我们会将用户重定向到登录页面。

Step 9: Create admin.xhtml as;

步骤9 :将admin.xhtml创建为;

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml"xmlns:h="https://java.sun.com/jsf/html">
<h:head><title>Facelet Title</title>
</h:head>
<h:body><h:form><p>Welcome #{login.user}</p><h:commandLink action="#{login.logout}" value="Logout"></h:commandLink></h:form>
</h:body>
</html>

This page is rendered when the user logs in successfully. Logout functionality is implemented by calling the logout method of the Login.java class.

用户成功登录后将显示此页面。 通过调用Login.java类的logout方法来实现logout功能。

Step 10: Create faces-config.xml file as;

步骤10 :创建faces-config.xml文件;

<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.2" xmlns="https://xmlns.jcp.org/xml/ns/javaee"xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="https://xmlns.jcp.org/xml/ns/javaee https://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"><navigation-rule><from-view-id>/login.xhtml</from-view-id><navigation-case><from-outcome>admin</from-outcome><to-view-id>/admin.xhtml</to-view-id></navigation-case></navigation-rule></faces-config>

Once done with all the steps specified above run the application and see the following output in the browser.

完成上面指定的所有步骤后,运行应用程序,然后在浏览器中查看以下输出。

Login Page

登录页面

Authentication Error Page

验证错误页面

Login Success Page

登录成功页面

Accessing admin.xhtml while logged in

登录时访问admin.xhtml

Just click on the Logout link and the session will be invalidated, after that try to access admin.xhtml page and you will be redirected to the login page, go ahead and download the project from below link and try it out.

只需单击Logout链接,会话将失效,然后尝试访问admin.xhtml页面,您将被重定向到登录页面,继续并从下面的链接下载项目并进行尝试。

Download JSF Authentication Login Logout Project下载JSF身份验证登录注销项目

翻译自: https://www.journaldev.com/7252/jsf-authentication-login-logout-database-example

jsf如何与数据库连接

jsf如何与数据库连接_JSF身份验证登录注销数据库示例相关推荐

  1. Sql Server身份验证登录配置

    Sql Server身份验证登录配置 1.服务器名称点开下拉框,选择浏览更多 选择本地服务器,展开数据库引擎,选择里面的服务器点击确认 然后选择window登录 接下来需要设置server身份登录 右 ...

  2. SQL Server身份验证 登录失败解决方案

    连接数据库,身份验证使用 Windows身份验证,可以进去,但是使用SQL Server身份验证登录,会失败. 解决办法 方法一:打开控制面板 → 管理工具 → 服务 → SQL Server(MSS ...

  3. SQL Server 2014 windows身份验证登录失败解决办法

    网上大部分安装SQL Server教程里都默认选择的windows身份验证登录,没有设置sql server账号,因此初次登录时只能通过这一种方式登录,若windows身份验证也不通过,该如何解决呢. ...

  4. Spring MVC定制用户登录注销实现示例

    这篇文章描述了如何实现对Spring MVC Web应用程序的自定义用户访问(登录注销). 作为前提,建议读者阅读这篇文章 ,其中介绍了一些Spring Security概念. 该代码示例可从Spri ...

  5. 出现身份验证错误 要求的函数不受支持_学习使用Kotlin创建Android应用程序第3部分:身份验证登录...

    在上一篇文章中,我们讨论了学习Kotlin制作Android应用程序的初学者第2部分:创建登录表单.这次我们来学习创建登录表单后,我们将尝试对上一篇创建的登录表单使用Firebase身份验证.因此,我 ...

  6. 数据库 SQL Server错误18456,window身份验证登录失败解决办法

    解决办法: 使用sa进入,新建查询,输入 CREATE LOGIN [Data-PC\zy] FROM WINDOWS 执行查询语句,再次登录成功. 身份验证名可以先使用widows验证,就可以看到名 ...

  7. sqlserver设置身份验证登录

    首先,以默认的windows验证方式打开并登录SQL Server 2008 第二步:登录后定位到"\安全性\登录名",选择要使用sql server登录验证方式的用户(例如sa) ...

  8. 使用windows身份验证登录sqlserver问题记录

    sqlserver使用windows身份连接 前言 1.TCP/IP链接错误 2.用户 'NT AUTHORITY\ANONYMOUS LOGON' 登录失败. 2.1 windows服务器新增用户如 ...

  9. jsf如何与数据库连接_JSF数据库示例– MySQL JDBC

    jsf如何与数据库连接 Welcome to JSF Database example. We will use JSF with MySQL database and use JDBC for ou ...

最新文章

  1. 交换机配置软件crt安装_非常详细的锐捷二层交换机配置教程,适合新手小白
  2. 测试在强电磁场下基于HALL的电流传感器 ACS712-5A是否会有到影响?
  3. JanusGraph 安装
  4. java按照商品价格排序_按照指定的类型排序
  5. delphi播放wav声音
  6. 迅捷fw325r虚拟服务器设置,迅捷FAST FW325R路由器无线桥接设置方法
  7. [一本通]题解 1031
  8. 粉象生活日记1:系统化打磨
  9. 服务器503网页报错,网页为什么出现503错误?网页503错误的解决方法
  10. html中颜色打字机效果,Css打字机效果
  11. 由己及人,由人及“机”
  12. 【C++】单例模式(懒汉、饿汉)
  13. 不写一行代码就能开发?是真的,试试应用魔方吧
  14. 百度地图查询周围建筑
  15. 《九》微信小程序中的自定义组件
  16. Python玩耍:一个小小的爬虫,在一堆公司列表里筛选出总部位于中国的公司
  17. 博客园去除个人博客页面广告
  18. 小程序scroll-view实现左右联动
  19. BCrypt加密方式
  20. 毕业设计-一种基于 MATLAB 的指纹识别方法

热门文章

  1. CSS教程--CSS 属性选择器
  2. [转载] python选择排序二元选择_选择排序:简单选择排序(Simple Selection Sort)
  3. [转载] Java中final关键字
  4. CF1041E Tree Reconstruction_构造_思维题
  5. Masonry 控件详解
  6. CSS从零开始(1)--CSS基础语法
  7. python模块整理12-pdb调试模块
  8. 反卷积可视化工具--deconv-deep-vis-toolbox
  9. 数据结构上机实践第七周项目4 - 队列数组
  10. 【ROS学习笔记】(九)参数的使用与编程方法