如何使用<s:select>标签和hibernate填充下拉列表?

时间:2016-12-16 18:36:30

标签: java hibernate jsp drop-down-menu struts2

我正在使用Struts2和Hibernate开发一个项目。员工成功登录后,他们将被带到显示事件列表的新页面。此列表将是下拉列表选择列表。我已经成功编写并测试了我的代码用于登录部分,但是当我添加带有标记的第二个jsp页面时,它们会向我显示以下异常:

message tag 'select', field 'list', name 'yourEvent': The requested list key 'events' could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name} - [unknown location] 

description The server encountered an internal error that prevented it from fulfilling this request. 

exception

org.apache.jasper.JasperException: tag 'select', field 'list', name 'yourEvent': The requested list key 'events' could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name} - [unknown location]
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:555)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:476)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
org.apache.struts2.dispatcher.ServletDispatcherResult.doExecute(ServletDispatcherResult.java:164)
org.apache.struts2.dispatcher.StrutsResultSupport.execute(StrutsResultSupport.java:186)
com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:371)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:275)
org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:256)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:167)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:265)
org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:138)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:239)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:239)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:191)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:73)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:91)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:252)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:100)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:141)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:145)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:171)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:98)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:161)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:193)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:189)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:246)
org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:54)
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:563)
org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77)
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:99)

以下是我的MemberScreen.jsp,其中包含<s:select>标记:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Field Passes</title>
        <style>            
            .errorMessage {
                color: red;
            }
        </style>
    </head>
    <body>
        <h1>Field Passes</h1>
        <p align="center">Welcome <s:property value="#session['employee'].first_name"/>!</p><br>        
        <s:form action="FieldPassInput" method="post">
            <s:select label="Event" headerKey="-1" headerValue="Select an event:" name="yourEvent" list="events" listKey="evt_dt" listValue="evt_desc" />
        </s:form> 
    </body>
</html>

以下是我的行动代码:

package actions;

import business.Event;
import business.EventDB;
import com.opensymphony.xwork2.ActionSupport;
import java.util.List;

public class FieldPass extends ActionSupport {

    private List<Event> events;
    private String yourEvent;

    public List<Event> getEventStrings() {
        return events;
    }

    public void setEventStrings(List<Event> events) {
        this.events = events;
    }

    public String getYourEvent() {
        return yourEvent;
    }

    public void setYourEvent(String yourEvent) {
        this.yourEvent = yourEvent;
    }

    public FieldPass() {
        events = EventDB.getEvents();
    }

    @Override
    public String execute() throws Exception {
        //throw new UnsupportedOperationException("Not supported yet.");
        return SUCCESS;
    }    
}

以下是我的活动实体代码:

package business;

import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
@Table(name = "Events")
public class Event {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long evt_id;
    @Temporal(TemporalType.DATE)
    private Date evt_date;
    private String day_of_week;
    private String evt_desc;
    private String evt_notes;
    private String closed;
    private int pass_limit;
    private String lg_area;
    private String lg_area_name;

    public Event() {
        evt_date = null;
        day_of_week = "";
        evt_desc = "";
        evt_notes = "";
        closed = "";
        pass_limit = 0;
        lg_area = "";
        lg_area_name = "";
    }

    public long getEvt_id() {
        return evt_id;
    }

    public void setEvt_id(long evt_id) {
        this.evt_id = evt_id;
    }

    public Date getEvt_date() {
        return evt_date;
    }

    public void setEvt_date(Date evt_date) {
        this.evt_date = evt_date;
    }

    public String getDay_of_week() {
        return day_of_week;
    }

    public void setDay_of_week(String day_of_week) {
        this.day_of_week = day_of_week;
    }

    public String getEvt_desc() {
        return evt_desc;
    }

    public void setEvt_desc(String evt_desc) {
        this.evt_desc = evt_desc;
    }

    public String getEvt_notes() {
        return evt_notes;
    }

    public void setEvt_notes(String evt_notes) {
        this.evt_notes = evt_notes;
    }

    public String getClosed() {
        return closed;
    }

    public void setClosed(String closed) {
        this.closed = closed;
    }

    public int getPass_limit() {
        return pass_limit;
    }

    public void setPass_limit(int pass_limit) {
        this.pass_limit = pass_limit;
    }

    public String getLg_area() {
        return lg_area;
    }

    public void setLg_area(String lg_area) {
        this.lg_area = lg_area;
    }

    public String getLg_area_name() {
        return lg_area_name;
    }

    public void setLg_area_name(String lg_area_name) {
        this.lg_area_name = lg_area_name;
    }    
}

以下是我的Hibernate数据处理代码:

package business;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import utility.HibernateUtil;

public class EventDB {

    public static List<Event> getEvents() {
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        Session session = null;
        List<Event> events = null;

        try {
            session = sessionFactory.openSession(); 
            String qS = "from Event";
            Query q = session.createQuery(qS);
            events = q.list();
        } catch (Exception e) {
            events = null;
        } finally {
            if (session != null) {
                session.close();
            }            
        }

        return events;
    }

}

以下代码是我的struts.xml:

<struts>
    <!-- Configuration for the default package. -->
    <package name="default" extends="struts-default">
        <action name="EmployeeLogon" class="actions.Logon">
            <result name="success">/MemberScreen.jsp</result>
            <result name="error">/Error.jsp</result>
            <result name="input">/Logon.jsp</result>
        </action>
        <action name="FieldPassInput" class="actions.FieldPass">
            <result name="success">/MemberScreen.jsp</result>
            <result name="input">/MemberScreen.jsp</result>
        </action>
    </package>
</struts>

以下是hibernate配置:

<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/FIELDPASS?zeroDateTimeBehavior=convertToNull</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">sesame</property>
    <mapping class="business.Employee"/>
    <mapping class="business.Event"/>
  </session-factory>
</hibernate-configuration>

为了完整性,我还在这里发布了我的logon.jsp及其操作代码:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Employee Logon</title>
        <style>            
            .errorMessage {
                color: red;
            }
        </style>
    </head>
    <body>
        <h1>Welcome to the Field Pass - Please Logon</h1>
        <s:form action="EmployeeLogon" method="post">
            <table>
                <tr>
                    <s:textfield name="employeeid" id="employeeid" label="Employee ID" required="true"/>
                </tr>
                <tr>
                    <s:password name="pattempt" id="pattempt" label="Password" required="true"/>
                </tr>
                <tr>
                    <s:submit value="Logon"/>
                </tr>                
            </table>                    
        </s:form>
        ${msg}
    </body>
</html>


package actions;

import business.Employee;
import business.EmployeeDB;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;

public class Logon extends ActionSupport implements SessionAware {

    private Employee employee;
    private String employeeid;
    private String pattempt;
    private Map session;

    public String getEmployeeid() {
        return employeeid;
    }

    public void setEmployeeid(String employeeid) {
        this.employeeid = employeeid;
    }

    public String getPattempt() {
        return pattempt;
    }

    public void setPattempt(String pattempt) {
        this.pattempt = pattempt;
    }

    @Override
    public void setSession(Map session) {
        this.session = session;
    }

    public Logon() {
    }

    @Override
    public String execute() throws Exception {
        //throw new UnsupportedOperationException("Not supported yet.");
        String rval = ERROR, msg = "";
        Map request = (Map)ActionContext.getContext().get("request");
        employee = EmployeeDB.getEmployee(Integer.parseInt(employeeid));
        if (employee != null) {
            employee.setPassAttempt(Integer.parseInt(this.pattempt));
            if (employee.isAuthenticated()) {
                session.put("employee", employee);
                msg = "Member authenticated";
                rval = SUCCESS;
            } else if (!employee.getMsg().isEmpty()) {
                msg = employee.getMsg();
                rval = INPUT;           
            }
        } else {
            msg = "Hibernate returned null member.";
            rval = INPUT;
        }
        request.put("msg", msg);        
        return rval;
    }

    @Override
    public void validate() {
        try {
            int pat = Integer.parseInt(this.pattempt);
            if (pat <= 0) {
                throw new Exception("Bad password");
            }
        } catch (Exception e) {
            addFieldError("pattempt", "Password issue: " + e.getMessage());
        }
    }
}

package business;

import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;

@Entity
public class Employee {

    @Id
    private int emp_id;    
    private String last_name;
    private String first_name;
    private String middle_initial;
    @Temporal(TemporalType.DATE)
    private Date hire_date;
    private int dept_id;
    private int password;
    private String admin;
    @Transient
    private int passattempt;
    @Transient
    private String msg;

    public Employee() {
        emp_id = 0;
        last_name = "";
        first_name = "";
        middle_initial = "";
        hire_date = null;
        dept_id = 0;
        password = 0;
        passattempt = -1;
        msg = "";
    }

    public int getEmp_id() {
        return emp_id;
    }

    public void setEmp_id(int emp_id) {
        this.emp_id = emp_id;
    }

    public String getLast_name() {
        return last_name;
    }

    public void setLast_name(String last_name) {
        this.last_name = last_name;
    }

    public String getFirst_name() {
        return first_name;
    }

    public void setFirst_name(String first_name) {
        this.first_name = first_name;
    }

    public String getMiddle_initial() {
        return middle_initial;
    }

    public void setMiddle_initial(String middle_initial) {
        this.middle_initial = middle_initial;
    }

    public Date getHire_date() {
        return hire_date;
    }

    public void setHire_date(Date hire_date) {
        this.hire_date = hire_date;
    }

    public int getDept_id() {
        return dept_id;
    }

    public void setDept_id(int dept_id) {
        this.dept_id = dept_id;
    }

    public int getPassword() {
        return password;
    }

    public void setPassword(int password) {
        this.password = password;
    }

    public String getAdmin() {
        return admin;
    }

    public void setAdmin(String admin) {
        this.admin = admin;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public void setPassAttempt(int patt) {
        this.passattempt = patt;
    }

    public boolean isAuthenticated() {
        if (this.password > 0) {
            if (this.password == this.passattempt) {
                return true;
            } else {
                msg = "Member not authenticated";
            }
        }
        return false;
    }

}

package business;

import javax.persistence.NoResultException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import utility.HibernateUtil;

public class EmployeeDB {

    public static Employee getEmployee(int emp_id) {
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        Session session = null;
        Employee e = null;
        try {
            String qS = "from Employee e where e.emp_id = :emp_id";
            session = sessionFactory.openSession();
            Query q = session.createQuery(qS);
            q.setParameter("emp_id", emp_id);
            e = (Employee)q.uniqueResult();
        } catch (NoResultException ex) {
            return null;
        } finally {
            session.close();
        }
        return e;
    }
}

任何Struts2专家都可以告诉我我的代码有什么问题,这样我就无法将数据从数据库填充到MemberScreen.jsp中的select下拉列表中吗?感谢您的时间和帮助。

0 个答案:

没有答案