JSF实验

作者: Ramsey16k | 来源:发表于2019-11-02 17:15 被阅读0次

    前天晚上的上机课,老师布置作业用JSF写几个网站的功能,顺便加验证器和转换器。

    JSF这个破框架已经过时很多年了,基本也没公司在用,上Stack Overflow搜问题还都是5年前的回答……然后我的IDEA还一直连不上GlassFish服务器,报404。不过晚上也把功能都写出来了,虽然不知道对不对。。。算是有点收获。

    当时完全靠肉眼看功能是不是正常。唉,想着第二天再想想办法让代码在服务器上跑起来吧。然后放上代码,毕竟这可能是我这辈子最后一次写JSF了哈哈哈哈

    昨天晚上,借用同学的笔记本运行了代码,总算是跑起来了,改了一些bug,感谢我的同学。。。

    实验要求如下:

    利用Java EE相关技术实现一个简单的学生管理系统,具体要求如下。
    (1) 使用JSF相关技术,如UI组件、ManagedBean、导航规则、转换器等实现
    (2) 编写一个登录页面,登录信息为用户名和密码,用按钮来提交登录信息。(此用户名和密码设置为admin和admin123,直接固化在代码中即可,不需要保存在数据库)
    (3) 登录后具有学生建立和信息添加功能。
    (4) 编写一个ManagedBean,用来处理学生的相关操作。
    (5) 学生建立和信息添加页面,共3个输入框
    1.学号和姓名用一个输入框,以[学号:姓名]格式输入,如(2015214123:张三),使用JSF 转换器来完成拆分
    2.其他两个输入框分别用来添加性别和年龄,其中性别输入为F或者M,年龄15-30,使用JSF验证器进行验证。
    (6) 学生建立和添加成功后,转到一个页面显示出相关的学生信息(学号、姓名、性别、年龄),格式方式不限
    以下功能选做:
    (1) 使用JSF事件处理,实现操作日志记录(如登录、新建、删除等操作),记录内容格式保存方式等自定。(2) 学生信息保存在数据库,学生信息包含学号、姓名、性别、年龄

    项目结构如下:

    image

    好了,直接上代码

    StudentBean:

    import java.sql.*;
    
    public class StudentBean {
        private String stuNo;
        private String name;
        private String sex;
        private int age;
    
        public String getStuNo() {
            return stuNo;
        }
    
        public void setStuNo(String stuNo) {
            this.stuNo = stuNo;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getSex() {
            return sex;
        }
    
        public void setSex(String sex) {
            this.sex = sex;
        }
    
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public String AddUser() {
            Connection con;
    
            String driver = "com.mysql.jdbc.Driver";
            String url = "jdbc:mysql://localhost:3306/student?useUnicode=true&useSSL=false";
            String user = "root";
            String password = "password";
    
            try {
                Class.forName(driver);
                con = DriverManager.getConnection(url, user, password);
    
                if (!con.isClosed()) {
                    System.out.println("数据库连接成功!");
                }
    
                //与数据库连接后,使用statement发送SQL语句
                Statement statement = con.createStatement();
    
                //具体的操作语句
                String sql = "INSERT INTO stu VALUES ( '" + stuNo + "' , '" + name + "' , '" + sex + "', " + age
                        + ");";
                //ResultSet(结果集)是数据查询返回的一种对象
                ResultSet resultSet = statement.executeQuery(sql);
    
                resultSet.close();
                con.close();
    
                return "success";
            } catch (SQLException e) {
                System.out.println("数据库连接失败!");
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                System.out.println("数据库驱动没有安装!");
            }
            return "error";
        }
    
    }
    
    

    UserBean:

    public class UserBean {
        private String name;
        private String password;
    
        public String getName() {
            return name;
        }
    
        public void setName(String newValue) {
            name = newValue;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String newValue) {
            password = newValue;
        }
    
        public String Verify() {
            if ("admin".equals(name) && "admin123".equals(password)) {
                return "success";
            } else {
                return "error";
            }
        }
    }
     
    

    UserConverter:

    import javax.faces.component.UIComponent;
    import javax.faces.context.FacesContext;
    import javax.faces.convert.Converter;
    import javax.faces.convert.FacesConverter;
    
    public class UserConverter implements Converter {
        public Object getAsObject(FacesContext context, UIComponent component, String value) {
            String[] array = value.split("\\:");
            StudentBean student = new StudentBean();
            student.setStuNo(array[0]);
            student.setName(array[1]);
    
            return student;
        }
    
        @Override
        public String getAsString(FacesContext context, UIComponent component, Object value) {
            return value.toString();
        }
    
    }
    
    

    ValidateAge:

    import javax.faces.application.FacesMessage;
    import javax.faces.component.UIComponent;
    import javax.faces.context.FacesContext;
    import javax.faces.validator.FacesValidator;
    import javax.faces.validator.Validator;
    import javax.faces.validator.ValidatorException;
    
    
    public class ValidateAge implements Validator {
    
        @Override
        public void validate(FacesContext context, UIComponent component, Object value)
                throws ValidatorException {
            int tmp = (Integer) value;
            if (!(tmp >= 15 && tmp <= 30)) {
                FacesMessage msg =
                        new FacesMessage("年龄不合格!",
                                "年龄必须在15-30之间");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                throw new ValidatorException(msg);
            }
        }
    }
    
    

    ValidateSex:

    import javax.faces.application.FacesMessage;
    import javax.faces.component.UIComponent;
    import javax.faces.context.FacesContext;
    import javax.faces.validator.FacesValidator;
    import javax.faces.validator.Validator;
    import javax.faces.validator.ValidatorException;
    
    
    public class ValidateSex implements Validator {
        @Override
        public void validate(FacesContext facesContext, UIComponent uiComponent, Object value)
                throws ValidatorException {
            String sex = (String) value;
            if (!("M".equals(sex) || "F".equals(sex))) {
                FacesMessage msg =
                        new FacesMessage("性别格式有误!",
                                "性别只能填 F/M");
                msg.setSeverity(FacesMessage.SEVERITY_ERROR);
                throw new ValidatorException(msg);
            }
        }
    }
    

    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:h="http://xmlns.jcp.org/jsf/html"
          xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
          xmlns:f="http://xmlns.jcp.org/jsf/core">
       <f:view>
    
             <h:form>
                <h3>请输入用户名和密码</h3>
                用户名: <h:inputText value="#{user.name}"/><br/>
                密码: <h:inputSecret value="#{user.password}"/><br/>
                <h:commandButton value="Login" action="#{user.Verify}"/><br/>
             </h:form>
          </f:view>
    
    </html>
    

    List.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://xmlns.jcp.org/jsf/html"
          xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
          xmlns:f="http://xmlns.jcp.org/jsf/core">
    <f:view>
        <h:form>
            姓名:<h:outputText value="#{student.name}"/><br/>
            学号:<h:outputText value="#{student.stuNo}"/><br/>
            性别:<h:outputText value="#{student.sex}"/><br/>
            年龄:<h:outputText value="#{student.age}"/><br/>
            <br/>
            <h:commandLink action="welcome" value="返回"/>
        </h:form>
    </f:view>
    </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:h="http://xmlns.jcp.org/jsf/html"
          xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
          xmlns:f="http://xmlns.jcp.org/jsf/core">
    <f:view>
        <h:form>
            <tr>
                <td>以[学号:姓名]格式输入学号和姓名(注意:冒号是英文的!)</td>
            </tr>
            <h:inputText value="#{student}" converter="converter"/><br/>
            <td>请输入性别:</td>
            <h:inputText id="sex" value="#{student.sex}">
                <f:validator validatorId="Sex"/>
            </h:inputText><br/>
            <h:message for="sex"></h:message>
    
            <td>请输入年龄:</td>
            <h:inputText id="age" value="#{student.age}">
                <f:validator validatorId="Age"/>
            </h:inputText><br/>
            <h:message for="age"></h:message>
            <br></br>
            <h:commandButton action="#{student.AddUser}" value="提交"/>
        </h:form>
    </f:view>
    </html>
    
    

    在WEB-INF里的配置文件如下:
    beans.xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans
        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/beans_1_1.xsd"
        bean-discovery-mode="all">
    </beans>
    

    faces-config.xml:

    <?xml version='1.0' encoding='UTF-8'?>
    <faces-config version="2.2" 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">
        <navigation-rule>
            <from-view-id>/index.xhtml</from-view-id>
            <navigation-case>
                <from-outcome>success</from-outcome>
                <to-view-id>/welcome.xhtml</to-view-id>
                <redirect/>
            </navigation-case>
            <navigation-case>
                <from-outcome>error</from-outcome>
                <to-view-id>/index.xhtml</to-view-id>
                <redirect/>
            </navigation-case>
        </navigation-rule>
        <navigation-rule>
            <from-view-id>/welcome.xhtml</from-view-id>
            <navigation-case>
                <from-outcome>success</from-outcome>
                <to-view-id>/List.xhtml</to-view-id>
            </navigation-case>
        </navigation-rule>
    
        <navigation-rule>
            <from-view-id>/List.xhtml</from-view-id>
            <navigation-case>
                <from-outcome>welcome</from-outcome>
                <to-view-id>/welcome.xhtml</to-view-id>
            </navigation-case>
        </navigation-rule>
        <managed-bean>
            <managed-bean-name>student</managed-bean-name>
            <managed-bean-class>StudentBean</managed-bean-class>
            <managed-bean-scope>session</managed-bean-scope>
        </managed-bean>
    
        <managed-bean>
            <managed-bean-name>user</managed-bean-name>
            <managed-bean-class>UserBean</managed-bean-class>
            <managed-bean-scope>session</managed-bean-scope>
        </managed-bean>
    
        <!-- 注册转换器 -->
       <converter>
           <converter-id>converter</converter-id>
           <converter-class>UserConverter</converter-class>
       </converter>
        <validator>
            <validator-id>Age</validator-id>
            <validator-class>ValidateAge</validator-class>
        </validator>
        <validator>
            <validator-id>Sex</validator-id>
            <validator-class>ValidateSex</validator-class>
        </validator>
    </faces-config>
    

    web.xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app 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-app_4_0.xsd"
             version="4.0">
        <servlet>
            <servlet-name>Faces Servlet</servlet-name>
            <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>Faces Servlet</servlet-name>
            <url-pattern>*.xhtml</url-pattern>
        </servlet-mapping>
    </web-app>
    

    相关文章

      网友评论

          本文标题:JSF实验

          本文链接:https://www.haomeiwen.com/subject/fdhlbctx.html