У меня есть следующая форма в качестве страницы входа:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:body>
<p:dialog visible="true" width="400" height="500"
header="Acessar o Sistema" showHeader="false" modal="true" resizable="false"
rendered="#{login.verificaSessaoAtiva() == false}">
<h:panelGrid style="margin: 0 auto;">
<h:outputText styleClass="fa fa-lock fa-5x"/>
</h:panelGrid>
<h:form id="formLogin">
<h:panelGrid cellspacing="10" style="text-align: center">
<h:graphicImage library="images" name="logo-home.png" />
<h1>Portal RH</h1>
<h:messages id="messagesLogin" globalOnly="true" style="color:red;margin:8px;" />
<!-- <h:outputText value="Username: " /> -->
<p:inputText placeholder="Usuário" label="Username" value="#{login.username}" size="40" required="true" requiredMessage="Campo Login é obrigatório" />
<!-- <h:outputText value="Password: " /> -->
<p:password placeholder="Senha" value="#{login.password}" size="40" required="true" requiredMessage="Campo Senha é obrigatório"/>
<p:commandButton id="loginBtn" value="login" action="#{login.login}" update="messagesLogin"/>
</h:panelGrid>
<p:defaultCommand target="loginBtn" />
</h:form>
</p:dialog>
</h:body>
</html>
Она работает почти идеально, если не маленькая проблема.Если я захожу на страницу впервые, при вводе логина и пароля форма не работает.Даже если я нажму кнопку входа или нажму ENTER, ничего не произойдет.Но если я обновлю страницу (F5), форма будет работать отлично.Я не знаю, как решить проблему.
Я не знаю, может ли это быть причиной, но эта ошибка появляется в консоли со ссылкой на источник jquery.js в отладчике:
"Синхронный запрос XMLHttpRequest в главном потоке устарел из-за его пагубных последствий для конечного пользователя. Для получения дополнительной помощи, проверьте http://xhr.spec.whatwg.org/."
Спасибо за любую помощь.
По запросу я редактирую с дополнительной информацией.
Я использую WildFly 14, Java 1.8 и Maven. Мой проект был сгенерирован из архетипа jboss-javaee6-webapp.
Это мой pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>br.com.graficasantamarta</groupId>
<artifactId>PortalRHGSM</artifactId>
<version>0.3.1-PRE-RELEASE</version>
<packaging>war</packaging>
<name>WildFly Quickstarts: PortalRHGSM6</name>
<description>A starter Java EE 7 webapp project for use on JBoss WildFly / WildFly, generated from the jboss-javaee6-webapp archetype</description>
<url>http://wildfly.org</url>
<licenses>
<license>
<name>Apache License, Version 2.0</name>
<distribution>repo</distribution>
<url>http://www.apache.org/licenses/LICENSE-2.0.html</url>
</license>
</licenses>
<properties>
<!-- Explicitly declaring the source encoding eliminates the following
message: -->
<!-- [WARNING] Using platform encoding (UTF-8 actually) to copy filtered
resources, i.e. build is platform dependent! -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- JBoss dependency versions -->
<version.wildfly.maven.plugin>1.0.2.Final</version.wildfly.maven.plugin>
<!-- Define the version of the JBoss BOMs we want to import to specify
tested stacks. -->
<version.jboss.bom>8.2.1.Final</version.jboss.bom>
<!-- other plugin versions -->
<version.compiler.plugin>3.1</version.compiler.plugin>
<version.surefire.plugin>2.16</version.surefire.plugin>
<version.war.plugin>2.5</version.war.plugin>
<!-- maven-compiler-plugin -->
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
<dependencyManagement>
<dependencies>
<!-- JBoss distributes a complete set of Java EE 7 APIs including a Bill
of Materials (BOM). A BOM specifies the versions of a "stack" (or a collection)
of artifacts. We use this here so that we always get the correct versions
of artifacts. Here we use the jboss-javaee-7.0-with-tools stack (you can
read this as the JBoss stack of the Java EE 7 APIs, with some extras tools
for your project, such as Arquillian for testing) and the jboss-javaee-7.0-with-hibernate
stack you can read this as the JBoss stack of the Java EE 7 APIs, with extras
from the Hibernate family of projects) -->
<dependency>
<groupId>org.wildfly.bom</groupId>
<artifactId>jboss-javaee-7.0-with-tools</artifactId>
<version>${version.jboss.bom}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.wildfly.bom</groupId>
<artifactId>jboss-javaee-7.0-with-hibernate</artifactId>
<version>${version.jboss.bom}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<repositories>
<repository>
<id>prime-repo</id>
<name>PrimeFaces Maven Repository</name>
<url>http://repository.primefaces.org</url>
<layout>default</layout>
</repository>
</repositories>
<dependencies>
<!-- First declare the APIs we depend on and need for compilation. All
of them are provided by JBoss WildFly -->
<!-- Import the CDI API, we use provided scope as the API is included in
JBoss WildFly -->
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<scope>provided</scope>
</dependency>
<!-- Import the Common Annotations API (JSR-250), we use provided scope
as the API is included in JBoss WildFly -->
<dependency>
<groupId>org.jboss.spec.javax.annotation</groupId>
<artifactId>jboss-annotations-api_1.2_spec</artifactId>
<scope>provided</scope>
</dependency>
<!-- Import the JAX-RS API, we use provided scope as the API is included
in JBoss WildFly -->
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>jaxrs-api</artifactId>
<scope>provided</scope>
</dependency>
<!-- Import the JPA API, we use provided scope as the API is included in
JBoss WildFly -->
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<scope>provided</scope>
</dependency>
<!-- Import the EJB API, we use provided scope as the API is included in
JBoss WildFly -->
<dependency>
<groupId>org.jboss.spec.javax.ejb</groupId>
<artifactId>jboss-ejb-api_3.2_spec</artifactId>
<scope>provided</scope>
</dependency>
<!-- JSR-303 (Bean Validation) Implementation -->
<!-- Provides portable constraints such as @Email -->
<!-- Hibernate Validator is shipped in JBoss WildFly -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Import the JSF API, we use provided scope as the API is included in
JBoss WildFly -->
<dependency>
<groupId>org.jboss.spec.javax.faces</groupId>
<artifactId>jboss-jsf-api_2.2_spec</artifactId>
<scope>provided</scope>
</dependency>
<!-- Now we declare any tools needed -->
<!-- Annotation processor to generate the JPA 2.0 metamodel classes for
typesafe criteria queries -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>
<scope>provided</scope>
</dependency>
<!-- Annotation processor that raising compilation errors whenever constraint
annotations are incorrectly used. -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator-annotation-processor</artifactId>
<scope>provided</scope>
</dependency>
<!-- Needed for running tests (you may also use TestNG) -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<!-- Optional, but highly recommended -->
<!-- Arquillian allows you to test enterprise code such as EJBs and Transactional(JTA)
JPA from JUnit/TestNG -->
<dependency>
<groupId>org.jboss.arquillian.junit</groupId>
<artifactId>arquillian-junit-container</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.arquillian.protocol</groupId>
<artifactId>arquillian-protocol-servlet</artifactId>
<scope>test</scope>
</dependency>
<!-- damyhonn.santos code start -->
<!-- https://mvnrepository.com/artifact/com.sun.faces/jsf-impl -->
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.2.18</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.faces/jsf-api -->
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.18</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.primefaces/primefaces -->
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>6.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.microsoft.sqlserver/mssql-jdbc -->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>7.0.0.jre8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.11.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.11.1</version>
</dependency>
<!-- Meu tema personalizado -->
<dependency>
<groupId>br.com.graficasantamarta</groupId>
<artifactId>jquery-ui.custom</artifactId>
<version>1.12.4</version>
</dependency>
<dependency>
<groupId>br.com.graficasantamarta</groupId>
<artifactId>PortalRHRelatFont</artifactId>
<version>1.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.webjars/font-awesome -->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>font-awesome</artifactId>
<version>4.7.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.omnifaces/omnifaces -->
<dependency>
<groupId>org.omnifaces</groupId>
<artifactId>omnifaces</artifactId>
<version>3.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.primefaces.themes/all-themes -->
<dependency>
<groupId>org.primefaces.themes</groupId>
<artifactId>all-themes</artifactId>
<version>1.0.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sf.jasperreports/jasperreports -->
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>6.7.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.1.3.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.3.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-email -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.1.3.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!-- damyhonn.santos code end -->
</dependencies>
<build>
<!-- Maven will append the version to the finalName (which is the name
given to the generated war, and hence the context root) -->
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>${version.war.plugin}</version>
<configuration>
<!-- Java EE 7 doesn't require web.xml, Maven needs to catch up! -->
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<!-- The WildFly plugin deploys your war to a local WildFly container -->
<!-- To use, run: mvn package wildfly:deploy -->
<plugin>
<groupId>org.wildfly.plugins</groupId>
<artifactId>wildfly-maven-plugin</artifactId>
<version>${version.wildfly.maven.plugin}</version>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
<profiles>
<profile>
<!-- The default profile skips all tests, though you can tune it to run
just unit tests based on a custom pattern -->
<!-- Seperate profiles are provided for running all tests, including Arquillian
tests that execute in the specified container -->
<id>default</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${version.surefire.plugin}</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profile>
<!-- An optional Arquillian testing profile that executes tests
in your WildFly instance -->
<!-- This profile will start a new WildFly instance, and execute the
test, shutting it down when done -->
<!-- Run with: mvn clean test -Parq-wildfly-managed -->
<id>arq-wildfly-managed</id>
<dependencies>
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-arquillian-container-managed</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</profile>
<profile>
<!-- An optional Arquillian testing profile that executes tests
in a remote WildFly instance -->
<!-- Run with: mvn clean test -Parq-wildfly-remote -->
<id>arq-wildfly-remote</id>
<dependencies>
<dependency>
<groupId>org.wildfly</groupId>
<artifactId>wildfly-arquillian-container-remote</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</profile>
<profile>
<!-- When built in OpenShift the 'openshift' profile will be used when
invoking mvn. -->
<!-- Use this profile for any OpenShift specific customization your app
will need. -->
<!-- By default that is to put the resulting archive into the 'deployments'
folder. -->
<!-- http://maven.apache.org/guides/mini/guide-building-for-different-environments.html -->
<id>openshift</id>
<build>
<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>${version.war.plugin}</version>
<configuration>
<outputDirectory>deployments</outputDirectory>
<warName>ROOT</warName>
</configuration>
</plugin>
</plugins>
</build>
</profile>
</profiles>
Полагаю, это связано с jquery.js, возникающим при создании проекта. Потому что проблема с синхронностью.
Этот снимок показывает проблему синхронного режима, которая появляется в консоли, когда я пытаюсь войти в систему при первой загрузке: Предупреждение в консоли, когда я нажимаю кнопку ENTER или кнопку входа в систему
Это мой логин SessionScoped ManagedBean:
public class Login implements Serializable {
/**
*
*/
private static final long serialVersionUID = -2524582729413244598L;
private String username;
private String password;
private String senhaAlterada1;
private String senhaAlterada2;
private final static ResourceBundle PROPERTIES = ResourceBundle
.getBundle("gsm");
private static final Logger logger = LogManager.getLogger();
public void login() {
Conexao.abrirConexaoDB();
FacesContext context = FacesContext.getCurrentInstance();
UsuarioBOImpl uBO = new UsuarioBOImpl();
Usuario u = null;
try {
u = uBO.isUsuarioReadyToLogin(username, password);
} catch (NoResultException e1) {
String msg = "Credenciais inválidas.";
logger.error(msg);
context.addMessage(null, new FacesMessage(msg));
} catch (PersistenceException e2) {
String msg = "Falha no login, usuário pode não ter acesso ao sistema do Portal RH";
context.addMessage(null, new FacesMessage(msg));
logger.error(msg, e2);
} catch (GsmException e3) {
logger.error(e3.getMessage(), e3);
context.addMessage(null, new FacesMessage(e3.getMessage()));
} catch (Exception e) {
String msg = "Falha ao verificar o login: ";
logger.error(msg, e);
context.addMessage(null, new FacesMessage(msg));
}
if(null != u){
if (u.getAltSenhaProx() == 1) {
PrimeFaces current = PrimeFaces.current();
current.executeScript("PF('alteraSenhaVar').show();");
} else {
context.getExternalContext().getSessionMap().put("user", username);
context.getExternalContext().getSessionMap().put("userId", u.getId());
context.getExternalContext().getSessionMap().put("nomeUsuario", u.getNome());
context.getExternalContext().getSessionMap().put("matriculaUsuario", u.getMatricula());
context.getExternalContext().getSessionMap().put("valorRegraAcesso", u.getValorRegraAcesso());
context.getExternalContext().getSessionMap().put("codEmpUser", u.getCodEmp());
context.getExternalContext().getSessionMap().put("plantasUser", u.getPlantas());
context.getExternalContext().getSessionMap().put("versao", PROPERTIES.getString("versao"));
try {
context.getExternalContext().redirect(context.getExternalContext().getRequestContextPath()
+ "/auth/home.xhtml");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public boolean verificaSessaoAtiva() {
FacesContext context = null;
String user = null;
try {
context = FacesContext.getCurrentInstance();
user = context.getExternalContext().getSessionMap().get("user").toString();
} catch (Exception e1) {
return false;
}
if (null != user) {
try {
context.getExternalContext().redirect(context.getExternalContext().getRequestContextPath()
+ "/auth/home.xhtml");
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
return false;
}
public void logout() {
FacesContext context = FacesContext.getCurrentInstance();
context.getExternalContext().getSessionMap().clear();
context.getExternalContext().invalidateSession();
try {
context.getExternalContext().redirect("login.xhtml?faces-redirect=true");
} catch (IOException e) {
logger.error("Erro ao efetuar logout.", e);
}
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSenhaAlterada1() {
return senhaAlterada1;
}
public void setSenhaAlterada1(String senhaAlterada1) {
this.senhaAlterada1 = senhaAlterada1;
}
public String getSenhaAlterada2() {
return senhaAlterada2;
}
public void setSenhaAlterada2(String senhaAlterada2) {
this.senhaAlterada2 = senhaAlterada2;
}
}