JSF сеанс или проблема конфигурации - PullRequest
0 голосов
/ 28 июля 2011

Это пример с mkyong.com, который я немного модифицировал. Я добавил текст ввода и команду отправить следующее смещение для подкачки в MySQL. Первая страница автоматически загружается со смещением 0, как ожидалось. Если я введу 5 во входном тексте, это на самом деле работает, и на следующей странице отображаются следующие 5 записей. Однако, если я сейчас введу 10, он перестает работать, и страница просто пытается загрузить. Я ждал 5 минут, ничего. Еще одна попытка, сначала 0 при загрузке, введите 15 только для проверки, все заработало. Но пытаясь заставить его работать после первого использования команды Button, он просто останавливается.

В URL отображается текущий идентификатор сеанса. Это проблема сеанса или проблема конфигурации?

Я новичок в jsf и пытаюсь научиться правильно отправлять запросы, чтобы страница отображала что-то. Я получил идею inputText и commandButton непосредственно из javaeetutorial6 на сайте оракулов, пример предположения / герцога.

 package model;

    //import java.util.Date;

    public class Customer{

        public String petid;
        public String petname;
            public String tmpvar;
        private String offset;
        //public String address;
        //public Date created_date;
            //private String searchText;
            //public String getSearchText() { return searchText; }
            //public void setSearchText(String s) { searchText = s; }
        public String getpetid() {
            return petid;
        }
        public void setpetid(String petid) {
            this.petid = petid;
        }
        public String getpetname() {
            return petname;
        }
        public void setpetname(String petname) {
            this.petname = petname;
        }
        /*public String getAddress() {
            return address;
        }
        public void setAddress(String address) {
            this.address = address;
        }
        public Date getCreated_date() {
            return created_date;
        }
        public void setCreated_date(Date created_date) {
            this.created_date = created_date;
        }*/
            public String gettmpvar() {
            return tmpvar;
        }
        public void settmpvar(String tmpvar) {
            this.tmpvar = tmpvar;
        }



    }

package cust;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;

import model.Customer;

@ManagedBean(name="Customer")
//@SessionScoped

public class CustomerBean implements Serializable{
int userNumber;
String offset;
//String SearchText;
    //resource injection
    @Resource(name="jdbc/petback2")
    private DataSource ds;

    //if resource injection is not support, you still can get it manually.
    /*public CustomerBean(){
        try {
            Context ctx = new InitialContext();
            ds = (DataSource)ctx.lookup("jdbc/petback2");
        } catch (NamingException e) {
        }

    }*/

    //connect to DB and get customer list

        public String searchText;
    //private String offset;
        public String getSearchText() { return searchText; }
        public void setSearchText(String s) { searchText = s; }


        public List<Customer> getCustomerList() throws SQLException{
int rowsperpage = 5;
//String offset;
//HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
//offset = request.getParameter("offset");
//if (    offset == null ? "" == null : offset.equals(""))
//if (offset null ? "" == null : offset.equals("0")
//{
//getoffset();
//String voffset;
//voffset = offset;

if (offset == null)
    {
    offset = "0";
    }
System.out.println(offset);
//}
//int pageno = 0;
//int offset = 5;

//offset = "5";
//offset = CustomerBean.this.searchText;
//offset = getResponse();
        if(ds==null)
            throw new SQLException("Can't get data source");

        //get database connection
        Connection con = ds.getConnection();

        if(con==null)
            throw new SQLException("Can't get database connection");

        PreparedStatement ps
            = con.prepareStatement(
               "select petid, petname from pets LIMIT "+ offset + ", " + rowsperpage);
                //"select petid, petname from pets LIMIT "+ offset + ", " + rowsperpage);
        //get customer data from database
        ResultSet result =  ps.executeQuery();

        List<Customer> list = new ArrayList<Customer>();
                //Customer cust2 = new Customer();
        while(result.next()){
            Customer cust2 = new Customer();

            cust2.setpetid(result.getString("petid"));
            cust2.setpetname(result.getString("petname"));
            //cust2.setAddress(result.getString("address"));
            //cust2.setCreated_date(result.getDate("created_date"));

            //store all data into a List
            list.add(cust2);
        }
                //List<Customer> list1 = new ArrayList<Customer>();
                //Customer cust3 = new Customer();
                Customer cust2 = new Customer();
                cust2.settmpvar("hello");
                list.add(cust2);
        return list;




    }

    public void setoffset(String user_number) {
        this.offset = user_number;
        System.out.println(offset);
    }

    public String getoffset() {
        return offset;
    }






}

newjsf.html

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


    <h:head>
        <h:outputStylesheet library="css" name="table-style.css"  />
        <script type="text/javascript" src="include/jquery.js"></script>
<script type="text/javascript" src="include/myjq.js"></script>



    </h:head>

    <h:body>
        <h:form>



        <h:dataTable id="myTable" value="#{Customer.customerList}" var="c" border="1"
                styleClass="order-table"
                headerClass="order-table-header"
                rowClasses="order-table-odd-row,order-table-even-row"
            >

            <h:column>
                <f:facet name="header">
                    petid
                </f:facet>
                    #{c.petid}
            </h:column>

            <h:column>
                <f:facet name="header">
                    petname
                </f:facet>
                    #{c.petname}
            </h:column>



        </h:dataTable>
            <h:inputText
                    id="userNo"
                    value="#{Customer.offset}">

                </h:inputText>
<h:commandButton id="submit" value="Submit"
                                 action="newjsf.xhtml"/>
        </h:form>
    </h:body>

</html>

конфигурация:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>
    <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>
        <!--<url-pattern>/faces/*</url-pattern>
        <url-pattern>/faces/*</url-pattern>-->
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>faces/newjsf.xhtml</welcome-file>
    </welcome-file-list>
</web-app>

1 Ответ

0 голосов
/ 01 августа 2011

Получил работу, изменил на пользовательский интерфейс: повторить, и использовал ниже для отправки получает вместо поста:

<h:outputLink id="link1" value="newui.xhtml?voffset=#{Customer.offset - 5}">
    <h:outputText value="prev" />
</h:outputLink>

<h:outputLink id="link2" value="newui.xhtml?voffset=#{Customer.offset + 5}">
    <h:outputText value="next" />
</h:outputLink>

А в бобе:

HttpServletRequest req = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
            offset = req.getParameter("voffset");
            if (offset == null) {
                offset = "0";
            }

и

public void setoffset(String voffset) {
        this.offset = voffset;
        //System.out.println(offset);
    }

    public String getoffset() {
        return offset;
    }

Я не знаю как, но set / get работает без вызова, возможно, с автоматической обработкой. В любом случае, теперь пейджинг работает как чемпион, и больше контроля, чем данных.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...