使用Okta的身份管理平台轻松部署您的应用程序 使用Okta的API在几分钟之内即可对任何应用程序中的用户进行身份验证,管理和保护。 今天尝试Okta。
JavaServer Faces(JSF)是用于构建Web应用程序的Java框架,其中心是作为用户界面构建块的组件。 JSF受益于丰富的工具和供应商生态系统,以及开箱即用的组件和库,它们增加了更多的功能。
为什么使用JSF代替JavaServer Pages(JSP)? 主要有两个原因:首先,JSF具有更多的模板功能,因为它遇到标签时不会直接编写视图。 相反,您可以将视图构建为XML,然后可以对其进行预处理,然后再将其输出为HTML。 这意味着您可以随着应用程序的增长重新使用并更好地组织代码。 其次,JSF为您提供了完整的MVC架构,而JSP只是一种脚本语言,它抽象了手工编写Servlet的过程。
在此背景下,让我们创建一个简单的应用程序,以展示JSF的强大功能。 在本教程中,我们将构建一个简单的Web应用程序,以管理由数据库支持的您喜欢的书籍的列表,并使用Okta安全地访问您的应用程序。
使用JSF创建CRUD应用程序
首先,我们将使用TomEE Maven原型生成项目:
$ mvn archetype:generate \-DarchetypeGroupId=org.apache.openejb.maven \-DarchetypeArtifactId=tomee-webapp-archetype \-DarchetypeVersion=1.7.1
遵循交互式生成过程,使用以下参数生成应用程序:
Define value for property 'groupId': com.okta.developer
Define value for property 'artifactId': jsf-crud
Define value for property 'version' 1.0-SNAPSHOT: : 1.0-SNAPSHOT
Define value for property 'package' com.okta.developer: : com.okta.developer
Confirm properties configuration:
groupId: com.okta.developer
artifactId: jsf-crud
version: 1.0-SNAPSHOT
package: com.okta.developer
Y: : Y
然后cd
转化项目,构建和运行,看到它在行动:
$ cd jsf-crud # or the artifactId you used to generate the project
$ mvn package
$ mvn tomee:run
在您的JSF应用程序中创建一本书
现在,将您的首选浏览器指向http://localhost:8080/
。 您应该看到用于创建书籍的表单。
要添加书籍,只需输入书名,然后点击添加即可 。 您将进入成功页面,并能够查看数据库中的书籍列表。 此表单页面由src/main/webapp/book.xhtml
生成,结果页面由src/main/webapp/result.xhtml
。
book.xhtml
是一个简单的表单,将其字段连接到com.okta.developer.presentation.BookBean
类。 例如:
<h:inputText value='#{bookBean.bookTitle}'/>
对于操作,例如提交表单,我们直接绑定到“ bean”类中的方法。 该特定形式将触发类中的add()
方法:
<h:commandButton action="#{bookBean.add}" value="Add"/>
BookBean.add()
方法创建一个新的Book
实例,并将其标题设置为我们存储在bookTitle
字段中的bookTitle
(请记住,它已绑定到表单的输入字段):
public String add() {Book book = new Book();book.setBookTitle(bookTitle);bookService.addBook(book);return "success";
}
然后,它要求bookService
将图书持久bookService
到数据库中,就像我们在com.okta.developer.application.BookService
类中看到的com.okta.developer.application.BookService
:
public void addBook(Book book) {entityManager.persist(book);
}
但是返回的"success"
字符串呢? 它在文件src/main/webapp/WEB-INF/faces-config.xml
:
<navigation-rule><from-view-id>/book.xhtml</from-view-id><navigation-case><from-outcome>success</from-outcome><to-view-id>/result.xhtml</to-view-id></navigation-case>
</navigation-rule>
这意味着当/book.xhtml
文件success
时,JSF会将用户发送到视图/result.xhtml
。 在result.xhtml
文件中,我们还看到一个绑定到Bean中的方法的按钮:
<h:commandButton action="#{bookBean.fetchBooks}" value="View books present"/>
这将执行类中的方法fetchBooks()
。 在src/main/java/com/okta/developer/presentation/BookBean.java
文件中,我们看到fetchBooks()
委托给bookService
的方法,该方法将结果存储到booksAvailable
字段中,然后返回字符串“ success” 。
public String fetchBooks() {booksAvailable=bookService.getAllBooks();return "success";
}
阅读您的JSF应用程序中的书
在getAllBooks()
方法中, com.okta.developer.application.BookService
类查询数据库,以获取所有不带过滤器的Book
实例:
public List<Book> getAllBooks() {CriteriaQuery<Book> cq = entityManager.getCriteriaBuilder().createQuery(Book.class);cq.select(cq.from(Book.class));return entityManager.createQuery(cq).getResultList();
}
凉。 但是页面实际上如何显示图书信息? 在result.xhtml
文件中,找到ui:repeat
标签:
<ui:repeat value="#{bookBean.booksAvailable}" var="book">#{book.bookTitle} <br/>
</ui:repeat>
<ui:repeat>
标记迭代每个value
,在这种情况下, #{bookBean.booksAvailable}
是我们刚刚从fetchBooks()
方法分配的字段。 集合的每个元素都可以通过标签的var
属性中的名称来引用(在本例中为book
)。
<ui:repeat>
标记内的所有内容都将对集合中的每个元素重复。 在这里,它只使用插值符号#{book.bookTitle}
和换行符( <br/>
)输出书名。
我们只介绍了CRUD应用程序的C reate和R ead方法。 太棒了! 现在让我们尝试与U PDATE一本书。
更新记录
在src/main/webapp
文件夹中创建一个edit.xhtml
文件,以包含用于更新数据库中Book
的表单。 它看起来与“创建”表单非常相似:
<?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:f="http://java.sun.com/jsf/core"xmlns:h="http://java.sun.com/jsf/html"><h:body bgcolor="white"><f:view><h1>Update book</h1><h:form><h:panelGrid columns="2"><h:outputText value='Enter book title'/><h:inputText value='#{bookBean.bookTitle}'/><h:outputText value='Update'/><h:commandButton action="#{bookBean.update}" value="Update"/></h:panelGrid><input type="hidden" name="bookId" value='#{param.bookId}'/></h:form></f:view>
</h:body>
</html>
现在,通过更改<ui:repeat>
标记的内容,从文件src/main/webapp/result.xhtml
的书籍列表中添加指向此页面的链接:
<ui:repeat value="#{bookBean.booksAvailable}" var="book"><h:link value="#{book.bookTitle}" outcome="edit"><f:param name="bookId" value="#{book.bookId}"/></h:link><br/>
</ui:repeat>
现在,列表中的每本书都是该书编辑页面的链接。
但是,如果您尝试单击该链接,则会看到该表单在页面加载时显示为空。 让我们解决这个问题,并在表单呈现之前加载书名。 要从我们的bean中的URL获取bookId
,请在pom.xml
文件中包括以下依赖项:
<dependencies>...<dependency><groupId>javax</groupId><artifactId>javaee-web-api</artifactId><version>6.0</version><scope>provided</scope></dependency>...
</dependencies>
编辑src/main/java/com/okta/developer/application/BookService.java
文件,并将以下方法添加到BookService
类以从数据库中加载书籍:
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Root;...public Book getBook(Integer bookId) {CriteriaBuilder cb = entityManager.getCriteriaBuilder();CriteriaQuery<Book> cq = cb.createQuery(Book.class);Root<Book> book = cq.from(Book.class);cq.select(book);cq.where(cb.equal(book.get("bookId"), bookId));return entityManager.createQuery(cq).getSingleResult();
}
并将以下逻辑添加到BookBean
以在页面渲染之前加载书籍:
import javax.annotation.PostConstruct;
import javax.faces.context.FacesContext;...private Integer bookId;
private Book book;@PostConstruct
public void postConstruct() {String bookIdParam = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("bookId");if (bookIdParam != null) {bookId = Integer.parseInt(bookIdParam);book = bookService.getBook(bookId);bookTitle = book.getBookTitle();}
}
现在,让我们创建一个将更改保存到数据库的方法,在BookService
类中使用以下方法:
public void update(Book book) {entityManager.merge(book);
}
另外,将update
方法添加到BookBean
类中:
public String update() {book.setBookTitle(bookTitle);bookService.update(book);return "success";
}
为了正确地将用户重定向到列表页面,请将以下导航规则添加到文件src/main/webapp/faces-config.xml
:
<navigation-rule><from-view-id>/edit.xhtml</from-view-id><navigation-case><from-outcome>success</from-outcome><to-view-id>/result.xhtml</to-view-id></navigation-case>
</navigation-rule>
现在我们已经完成了书的更新,让我们继续进行“删除”部分。
删除记录
上一节介绍了最困难的部分-在bean中装入一本书。 添加删除按钮将更加容易。
将列表中每个条目的删除链接添加到文件src/main/webapp/result.xhtml
的编辑页面:
<ui:repeat value="#{bookBean.booksAvailable}" var="book"><h:link value="#{book.bookTitle}" outcome="edit"><f:param name="bookId" value="#{book.bookId}"/></h:link><!-- Delete link: --><h:outputText value=" ("/><h:link value="Delete" outcome="delete"><f:param name="bookId" value="#{book.bookId}"/></h:link><h:outputText value=")"/><br/>
</ui:repeat>
现在,在src/main/webapp/delete.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:f="http://java.sun.com/jsf/core"xmlns:h="http://java.sun.com/jsf/html"><h:body bgcolor="white"><f:view><h1>Delete book?</h1><h:form><h:panelGrid columns="2"><h:outputText value='Book title'/><h:inputText value='#{bookBean.bookTitle}' readonly="true"/><h:outputText value='Delete'/><h:commandButton action="#{bookBean.delete}" value="Confirm Delete"/></h:panelGrid><input type="hidden" name="bookId" value='#{param.bookId}'/></h:form></f:view>
</h:body>
</html>
并在BookBean
类中添加适当的删除处理程序:
public String delete() {bookService.delete(book);return "success";
}
接下来,在BookService
类中处理删除:
import javax.persistence.Query;...public void delete(Book book) {Query query = entityManager.createQuery("DELETE FROM Book b WHERE b.bookId = :bookId");query.setParameter("bookId", book.getBookId());query.executeUpdate();
}
并且不要忘记在删除后通过将以下内容添加到src/main/webapp/faces-config.xml
将您的用户重定向回列表:
<navigation-rule><from-view-id>/delete.xhtml</from-view-id><navigation-case><from-outcome>success</from-outcome><to-view-id>/result.xhtml</to-view-id></navigation-case>
</navigation-rule>
做完了! 我告诉你删除会更容易。
所以,现在我们可以在c reate,U PDATE,R EAD和d elete我们的书籍的CRUD应用程序。
改善用户界面
CRUD应用程序工作正常,但该应用程序看起来不太好。 让我们通过PrimeFaces改善我们的应用程序用户界面。
首先,将其作为依赖项添加到我们的pom.xml
:
<dependencies>...<dependency><groupId>org.primefaces</groupId><artifactId>primefaces</artifactId><version>7.0</version></dependency>...
</dependencies>
现在,我们可以在视图中使用任何PrimeFaces组件,方法是将其命名空间声明为html
标记,如下所示:
<html xmlns="http://www.w3.org/1999/xhtml"xmlns:f="http://java.sun.com/jsf/core"xmlns:h="http://java.sun.com/jsf/html"xmlns:p="http://primefaces.org/ui">
有关更深入的概述,请阅读其站点中的每个PrimeFaces组件 。
首先,让我们从BookBean
类中删除图书清单,然后创建一个BookList
类。 页面加载后,这将立即加载书单。 使用以下内容创建文件src/main/java/com/okta/developer/presentation/BookList.java
:
package com.okta.developer.presentation;import com.okta.developer.application.BookService;
import com.okta.developer.entities.Book;import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Named;
import java.util.List;@Named
public class BookList {@Injectprivate BookService bookService;private List<Book> booksAvailable;@PostConstructpublic void postConstruct() {booksAvailable = bookService.getAllBooks();}public List<Book> getBooksAvailable() {return booksAvailable;}
}
从BookBean
类中删除以下与booksAvailable
字段相关的代码块:
private List<Book> booksAvailable;public List<Book> getBooksAvailable() {return booksAvailable;
}public void setBooksAvailable(List<Book> booksAvailable) {this.booksAvailable = booksAvailable;
}public String fetchBooks() {booksAvailable=bookService.getAllBooks();return "success";
}
我们还要更改目标网页。 让我们提供书单,而不是通过表单添加一本书。 为此,编辑index.jsp
以将重定向更改为result.jsf
:
<%@ page session="false" %>
<%response.sendRedirect("result.jsf");
%>
这是我的文件现在的样子。 浏览PrimeFaces组件库时 ,请随时进行调整。
文件: src/main/webapp/book.xhtml
使用p:panel
和p:panelGrid
:
<?xml version="1.0" encoding="UTF-8"?>
<!-- File: book.xhtml -->
<!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"xmlns:p="http://primefaces.org/ui">
<h:head></h:head>
<h:body><h:form><p:panel header="Create Book"><p:panelGrid columns="1" layout="grid"><p:outputLabel for="book-title" value="Enter book title"/><p:inputText id="book-title" value='#{bookBean.bookTitle}'/><p:commandButton value="Create" action="#{bookBean.add}" ajax="false"/></p:panelGrid><!-- We will use this later<input type="hidden" value="${_csrf.token}" name="${_csrf.parameterName}"/>--></p:panel></h:form>
</h:body>
</html>
文件: src/main/webapp/delete.xhtml
使用p:panel
和p:panelGrid
:
<?xml version="1.0" encoding="UTF-8"?>
<!-- File: delete.xhtml -->
<!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"xmlns:p="http://primefaces.org/ui">
<h:head></h:head>
<h:body><h:form><p:panel header="Delete Book?"><p:panelGrid columns="1" layout="grid"><p:outputLabel for="book-title" value="Book title"/><p:inputText id="book-title" value='#{bookBean.bookTitle}' readonly="true"/><p:commandButton value="Confirm Delete" action="#{bookBean.delete}" ajax="false"/></p:panelGrid><input type="hidden" name="bookId" value='#{param.bookId}'/><!-- We will use this later<input type="hidden" value="${_csrf.token}" name="${_csrf.parameterName}"/>--></p:panel></h:form>
</h:body>
</html>
文件: src/main/webapp/edit.xhtml
使用p:panel
和p:panelGrid
:
<?xml version="1.0" encoding="UTF-8"?>
<!-- File: edit.xhtml -->
<!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"xmlns:p="http://primefaces.org/ui">
<h:head></h:head>
<h:body><h:form><p:panel header="Update Book"><p:panelGrid columns="1" layout="grid"><p:outputLabel for="book-title" value="Enter new book title"/><p:inputText id="book-title" value='#{bookBean.bookTitle}'/><p:commandButton value="Update" action="#{bookBean.update}" ajax="false"/></p:panelGrid><input type="hidden" name="bookId" value='#{param.bookId}'/><!-- We will use this later<input type="hidden" value="${_csrf.token}" name="${_csrf.parameterName}"/>--></p:panel></h:form>
</h:body>
</html>
文件: src/main/webapp/result.xhtml
使用p:dataList
而不是ui:repeat
:
<?xml version="1.0" encoding="UTF-8"?>
<!-- File: result.xhtml -->
<!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:f="http://java.sun.com/jsf/core"xmlns:h="http://java.sun.com/jsf/html"xmlns:p="http://primefaces.org/ui">
<h:head></h:head>
<h:body><h:link outcome="book" value="Create Book"/><p:dataList value="#{bookList.booksAvailable}" var="book" type="ordered"><f:facet name="header">Book List</f:facet>#{book.bookTitle}<h:outputText value=" ("/><p:link value="Edit" outcome="edit"><f:param name="bookId" value="#{book.bookId}"/></p:link><h:outputText value=" | "/><p:link value="Delete" outcome="delete"><f:param name="bookId" value="#{book.bookId}"/></p:link><h:outputText value=")"/></p:dataList>
</h:body>
</html>
在启用PrimeFaces的情况下运行应用程序
使用mvn package tomee:run
重新启动应用程序。 该应用现在看起来会更好一些! 查看书籍清单:
使用Okta保护您的应用程序
目前,任何人都可以访问我们出色的Book应用程序并更改数据库。 为避免这种情况,让我们使用Spring Security库在应用程序中添加一个安全层,并通过Okta对用户进行身份验证。
首先,立即注册一个永久免费的开发者帐户! 完成后,请完成以下步骤以创建OIDC应用程序。
- 登录到您的开发者帐户在developer.okta.com
- 导航到应用程序 ,然后单击添加应用程序
- 选择网站 ,然后单击下一步。
- 为应用程序命名(例如
Java JSF Secure CRUD
) - 添加以下内容作为“登录”重定向URI:
-
http://localhost:8080/login/oauth2/code/okta
-
- 点击完成
现在,使用您的Client ID和Client Secret创建文件src/main/resources/application.properties
,您可以在刚创建的应用程序的General选项卡上找到它们。
okta.client-id={clientId}
okta.client-secret={clientSecret}
okta.issuer-uri=https://{yourOktaDomain}/oauth2/default
让我们在您的pom.xml
文件中添加Spring Security作为依赖项:
<properties>...<spring-security.version>5.1.6.RELEASE</spring-security.version><spring.version>5.1.6.RELEASE</spring.version>
</properties><dependencyManagement><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-framework-bom</artifactId><version>${spring.version}</version><scope>import</scope><type>pom</type></dependency><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-bom</artifactId><version>${spring-security.version}</version><scope>import</scope><type>pom</type></dependency></dependencies>
</dependencyManagement><dependencies>...<dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId></dependency><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-web</artifactId></dependency><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-config</artifactId></dependency><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-oauth2-client</artifactId></dependency><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-oauth2-resource-server</artifactId></dependency><dependency><groupId>org.springframework.security</groupId><artifactId>spring-security-oauth2-jose</artifactId></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>2.9.9</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.9.9.3</version></dependency>
</dependencies>
为了让Spring Security正确地控制您的应用程序安全,它需要知道哪些请求需要身份验证。 为此,我们将创建文件src/main/java/com/okta/developer/SecurityConfiguration.java
来告诉Spring Security保护所有URL并使用CSRF令牌保护表单:
public SecurityConfiguration(@Value("${okta.issuer-uri}") String issuerUri,@Value("${okta.client-id}") String clientId,@Value("${okta.client-secret}") String clientSecret) {this.issuerUri = issuerUri;this.clientId = clientId;this.clientSecret = clientSecret;}@Overrideprotected void configure(HttpSecurity http) throws Exception {http.sessionManagement() // Always create a session.sessionCreationPolicy(SessionCreationPolicy.ALWAYS)
接下来,创建文件src/main/java/com/okta/developer/SecurityWebApplicationInitializer.java
类以在应用程序中启用Spring Security:
package com.okta.developer;import org.springframework.security.web.context.*;public class SecurityWebApplicationInitializerextends AbstractSecurityWebApplicationInitializer {public SecurityWebApplicationInitializer() {super(SecurityConfiguration.class);}
}
由于已启用CSRF保护,因此需要将令牌添加到每个<h:form>
标签。 只需在表单中添加该行(我在使用PrimeFaces的文件中将那些注释掉了):
<input type="hidden" value="${_csrf.token}" name="${_csrf.parameterName}"/>
做完了! 转到http://localhost:8080
,您将被重定向到Okta登录表单,并且仅在成功通过身份验证后才能使用该应用程序。
想要与朋友分享应用程序? 太酷了,转到Okta开发人员控制台页面,转到“ 用户”并为其创建一个帐户。 现在,您还具有功能齐全的安全管理工具,您可以在其中启用/禁用用户,检查用户何时登录到您的应用程序,重置其密码等。
享受您的全新安全书本应用程序吧!
了解有关Java,JSF和用户身份验证的更多信息!
如果您想使用Okta学习有关Java,JSF和用户身份验证的更多信息,我们还有其他很棒的文章供您继续阅读:
- 使用Java EE和OIDC构建Java REST API
- 您应该使用哪个Java SDK?
- 教程:用Java创建和验证JWT
- 以第一语言学习Java
有什么问题吗 要求未来的职位? 将它们放入评论中! 并且不要忘记在Twitter上关注@oktadev并在Youtube 上进行订阅 。
该应用程序的完整源代码可在GitHub上找到: oktadeveloper / okta-java-jsf-crud-example 。
使用Okta的身份管理平台轻松部署您的应用程序 使用Okta的API在几分钟之内即可对任何应用程序中的用户进行身份验证,管理和保护。 今天尝试Okta。
翻译自: https://www.javacodegeeks.com/2019/11/build-a-simple-crud-app-with-java-and-jsf.html