Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Java EE (J2EE) и Spring > <h:inputText> и русские буквы?


Автор: unkis 28.3.2007, 21:57
Ребята у меня следующая проблема.
когда я вычитываю значение из <h:inputText> то получаю вместо русских символов, символы такого содержания ав и так далее.
по этому значения я должен буду делать поиск по базе, но так как я получаю непонятно что, то естественно поиск по базе не происходит.
причём если закодировать русское слово руками то поиск происходит без проблем.

что делать?

Код

<h:inputText value="#{tableBean.query}" /> 
<h:coomandButton value="Search" action="a" actionListener="#{tableBean.searchResult}" />


Код


        public String getQuery() {        
        return query;
    }

    public void setQuery(String query) {
        this.query = query;
    }
    
    public void searchResult(ActionEvent e){
        System.out.println("Poneslas': " + query);
        setTorrenstList(Controller.getInstance().getSearchResult(getQuery()));
    }



Автор: powerOn 28.3.2007, 22:36
Цитата(unkis @  28.3.2007,  22:57 Найти цитируемый пост)
когда я вычитываю значение из <h:inputText> то получаю вместо русских символов, символы такого содержания ав и так далее.

не понял. Какого "содержания" символы получаешь?

Автор: unkis 28.3.2007, 22:44
не заметил винград их перекодировал
вот такого содержания в unicode
Код

& # 1072; & # 1074; и так далее

пишу через пробел специально ибо винград их перекодирует в русские буквы

Автор: unkis 29.3.2007, 11:38
народ, что ни кто не знает как мне помочь ?

Автор: unkis 29.3.2007, 16:42
я не знаю туда я копаю или не туда, но где-то я прочитал что в моём случаи может помочь какой-то фильтр. 

Вопрос что за фильтр, как он мне может помочь, если вообще может, и как его писать? 

Автор: powerOn 29.3.2007, 18:59
Не знаю точно в чем у тебя проблема, у меня все работает нормально: русские символы приходят. 
Выкладывай исходник страницы, и файлы конфигурации.

Автор: unkis 29.3.2007, 21:59
вот моя страничка
Код

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@ taglib uri="http://myfaces.apache.org/tomahawk" prefix="t"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<h1>Test</h1>
<f:view>
    <h:form>
        <h:panelGroup id="q">
            <h:inputText value="#{tableBean.query}" />
            <h:commandButton id="we" value="Search" action="a"
                actionListener="#{tableBean.searchResult}" />
        </h:panelGroup>
        <h:dataTable value="#{tableBean.torrenstList}" var="list">
            <h:column>
                <f:facet name="header">
                    <h:outputText value="Name" />
                </f:facet>

                <h:outputLink value="#{list.trekersList[0].url}">
                    <h:outputText value="#{list.name}" />
                </h:outputLink>

            </h:column>
            <h:column>
                <f:facet name="header">
                    <h:outputText value="Ezruegungs Datum" />
                </f:facet>
                <h:outputText value="#{list.erzeugungsDatum}" />
            </h:column>
            <f:facet name="footer">
                <h:panelGroup>
                    <h:commandButton value="<< " action="forward"
                        actionListener="#{tableBean.firstPage}" />
                    <h:commandButton value="< " action="backward"
                        actionListener="#{tableBean.backward}" />
                    <h:commandButton value="> " action="forward"
                        actionListener="#{tableBean.forward}" />
                    <h:commandButton value=">> " action="forward"
                        actionListener="#{tableBean.lastPage}" />
                </h:panelGroup>
            </f:facet>
        </h:dataTable>
    </h:form>
</f:view>
</body>
</html>


вот мой bean
Код

package de.beans;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import javax.faces.event.ActionEvent;

import de.controler.Controller;
import de.torrents.Torrents;

public class TableBean {

    private int count = 0;
    private int maxResult = 10;
    private String query;
    private ArrayList<Torrents> torrenstList;
    
    public ArrayList<Torrents> getTorrenstList() {
        return torrenstList;
    }

    public void setTorrenstList(ArrayList<Torrents> torrenstList) {
        this.torrenstList = torrenstList;
    }

    public TableBean() {
        System.out.println("Init");
        Controller.getInstance();
        init();
    }

    private void init() {
        torrenstList = Controller.getInstance().getTorrents(0,maxResult);
        
    }
    
    public void backward(ActionEvent e) {
        count-=10;
        if (count<0) 
            count = 0;        
        setTorrenstList(Controller.getInstance().getTorrents(count, maxResult));        

    }
    
    public void forward(ActionEvent e){
        System.out.println("Forward count do "+ count);
        count+=10;
        setTorrenstList(Controller.getInstance().getTorrents(count, maxResult));
        
        System.out.println("Forward count posle "+ count);
    }
    
    public void firstPage(ActionEvent e){
        setTorrenstList(Controller.getInstance().getTorrents(0, maxResult));
        
    }
    
    public void lastPage(ActionEvent e){
        int count = Controller.getInstance().getSizeOfTorrents();
        setTorrenstList(Controller.getInstance().getTorrents((count-maxResult), maxResult));
        
    }

    public String getQuery() {
        
        return query;
    }

    public void setQuery(String query) {
        String newQuery="";
        try {
            newQuery = new String(query.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
        this.query = newQuery;
    }
    
    public void searchResult(ActionEvent e){
        System.out.println("Poneslas': " + query);
        setTorrenstList(Controller.getInstance().getSearchResult(getQuery()));
    }
}

    


вот мой faces-config.xml
Код

<?xml version="1.0"?>
<!DOCTYPE faces-config PUBLIC "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.0//EN"
                              "http://java.sun.com/dtd/web-facesconfig_1_0.dtd">
<faces-config>
 <managed-bean>
  <managed-bean-name>tableBean</managed-bean-name>
  <managed-bean-class>de.beans.TableBean</managed-bean-class>
  <managed-bean-scope>session</managed-bean-scope>
 </managed-bean>
</faces-config>


вот мой web.xml
Код

<?xml version="1.0"?>
<!--
 * Copyright 2004 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
-->
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 <display-name>SuperPoisk_Web</display-name>
 <context-param>
  <description>State saving method: "client" or "server" (= default)
            See JSF Specification 2.5.2</description>
  <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
  <param-value>server</param-value>
 </context-param>
 <context-param>
  <description>This parameter tells MyFaces if javascript code should be allowed in the
            rendered HTML output.
            If javascript is allowed, command_link anchors will have javascript code
            that submits the corresponding form.
            If javascript is not allowed, the state saving info and nested parameters
            will be added as url parameters.
            Default: "true"</description>
  <param-name>org.apache.myfaces.ALLOW_JAVASCRIPT</param-name>
  <param-value>true</param-value>
 </context-param>
 <context-param>
  <description>This parameter tells MyFaces if javascript code should be allowed in the
            rendered HTML output.
            If javascript is allowed, command_link anchors will have javascript code
            that submits the corresponding form.
            If javascript is not allowed, the state saving info and nested parameters
            will be added as url parameters.
            Default: "false"

            Setting this param to true should be combined with STATE_SAVING_METHOD "server" for
            best results.

            This is an EXPERIMENTAL feature. You also have to enable the detector filter/filter mapping below to get
            JavaScript detection working.</description>
  <param-name>org.apache.myfaces.DETECT_JAVASCRIPT</param-name>
  <param-value>false</param-value>
 </context-param>
 <context-param>
  <description>If true, rendered HTML code will be formatted, so that it is "human readable".
            i.e. additional line separators and whitespace will be written, that do not
            influence the HTML code.
            Default: "true"</description>
  <param-name>org.apache.myfaces.PRETTY_HTML</param-name>
  <param-value>true</param-value>
 </context-param>
 <context-param>
  <description>If true, a javascript function will be rendered that is able to restore the
            former vertical scroll on every request. Convenient feature if you have pages
            with long lists and you do not want the browser page to always jump to the top
            if you trigger a link or button action that stays on the same page.
            Default: "false"</description>
  <param-name>org.apache.myfaces.AUTO_SCROLL</param-name>
  <param-value>true</param-value>
 </context-param>
 <!-- Extensions Filter -->
 <filter>
  <filter-name>MyFacesExtensionsFilter</filter-name>
  <filter-class>org.apache.myfaces.webapp.filter.ExtensionsFilter</filter-class>
  <init-param>
   <description>Set the size limit for uploaded files.
                Format: 10 - 10 bytes
                        10k - 10 KB
                        10m - 10 MB
                        1g - 1 GB</description>
   <param-name>maxFileSize</param-name>
   <param-value>20m</param-value>
  </init-param>
 </filter>
 <filter-mapping>
  <filter-name>MyFacesExtensionsFilter</filter-name>
  <!-- servlet-name must match the name of your javax.faces.webapp.FacesServlet entry -->
  <servlet-name>Faces Servlet</servlet-name>
 </filter-mapping>
 <!-- extension mapping for serving page-independent resources (javascript, stylesheets, images, etc.)  -->
 <filter-mapping>
  <filter-name>MyFacesExtensionsFilter</filter-name>
  <url-pattern>/faces/myFacesExtensionResource/*</url-pattern>
 </filter-mapping>
 <filter-mapping>
  <filter-name>MyFacesExtensionsFilter</filter-name>
  <url-pattern>*.jsp</url-pattern>
 </filter-mapping>
 <!-- Listener, that does all the startup work (configuration, init). -->
 <listener>
  <listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class>
 </listener>
 <!-- Faces Servlet -->
 <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>*.jsf</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
  <servlet-name>Faces Servlet</servlet-name>
  <url-pattern>/faces/*</url-pattern>
 </servlet-mapping>
 <login-config>
  <auth-method>BASIC</auth-method>
 </login-config>
</web-app>



вроди бы всё, в чём же проблема?

Автор: powerOn 29.3.2007, 22:29
Поставь в начале jsp страницы:
Код

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>



Автор: Predator83 30.3.2007, 00:38
Код

<%@ page contentType="text/html; charset=windows-1251" %>

Автор: unkis 30.3.2007, 08:33
Цитата(powerOn @ 29.3.2007,  20:29)
Поставь в начале jsp страницы:
Код

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>

поставил, но теперь он передаёт вот такие символы

Ñ?ер

Добавлено через 4 минуты и 18 секунд
Цитата(Predator83 @  29.3.2007,  22:38 Найти цитируемый пост)
    
<%@ page contentType="text/html; charset=windows-1251" %>


при этой строчки, тот же результат. в consol выдаёт Ñ?ер 

Автор: yaldygin 4.5.2007, 05:32
Привет, ты решил проблему?
Как я понимаю, это проблема не с inputText, а вообще с JSF.
Суть проблемы: когда на страницу помещаешь, например, <h:outputText value="Текст">, при том, что кодировка windows-1251 и JSF должен выдавать страницу, в которой приходится 1 байт на символ, JSF почему-то выдает результат, где каждый символ представляется в виде & # ...; Мало того, что этот код не очень приятно смотреть (гораздо проще было бы, представляйся каждый символ одним байтом), так еще и весит такая страница на порядок больше!
Кто-нибудь встречался с этой проблемой и решал ее?
Очень необходимо....
Простые указания кодировки, например, в faces-config.xml не помогают.....

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)