my first JSF

1. Project directory structure


2. First create a new javaBean

package bean;

public class UserBean {
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

3. Create index.xhtml and welcome.xhtml files

index.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:ui="http://java.sun.com/jsf/facelets"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:h="http://java.sun.com/jsf/html">

<h:head>
<title>index</title>
</h:head>
<h:body>
	<h2>This is the home page! </h2>
	<h:form>
		<h:inputText value="#{userBean.name}"></h:inputText>	
		<h:commandButton value="跳转" action="welcome"></h:commandButton>
	</h:form>
</h:body>
</html>

welcome.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:ui="http://java.sun.com/jsf/facelets"
	xmlns:f="http://java.sun.com/jsf/core"
	xmlns:h="http://java.sun.com/jsf/html">

<head>
<title>welcome</title>
</head>
<body>
	<h2>This is the welcome page! </h2>
	<h:outputText value="#{userBean.name}"></h:outputText>
</body>
</html>

4. Configure the faces-config.xml file

<?xml version="1.0" encoding="UTF-8"?>
<faces-config
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
    version="2.2">

    <managed-bean>
        <managed-bean-name>userBean</managed-bean-name><!-- set the name of the bean object -->
        <managed-bean-class>bean.UserBean</managed-bean-class><!-- Set the class of the bean object -->
        <managed-bean-scope>session</managed-bean-scope><!-- set scope -->
    </managed-bean>
    
    <navigation-rule>
        <display-name>index.xhtml</display-name>
        <from-view-id>index.xhtml</from-view-id><!-- 目标源 -->
        <navigation-case>
            <to-view-id>welcome.xhtml</to-view-id><!-- 目的页面 -->
        </navigation-case>
    </navigation-rule>
</faces-config>

5. Test



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325641943&siteId=291194637
jsf