powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / Java [игнор отключен] [закрыт для гостей] / Tomcat и кракозябры
3 сообщений из 3, страница 1 из 1
Tomcat и кракозябры
    #38452330
moongloom
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
Добрый вечер.
Начал изучать jsp. Почему-то Tomcat не хочет правильно передавать русский текст в сервлет. Полголовы сломал уже, но так и не могу понять что я делаю не так. Пробовал фильтры, пробовал ставить URIEncoding="UTF-8" в server.xml - ничего не помогает.

Код jsp (здесь русский текст отображается нормально)
Код: html
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
<%@page contentType="text/html;charset=UTF-8" %>
<%@page pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
	"http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
		<title> My first JSP   </title>
	</head>	
	<body>		
		<form action="HelloServlet">			
			 Введите цвет <br>
			<input type="text" name="color"size="20px">
			<input type="submit" value="submit">						
		</form>		
	</body>	
</html>




Код SetCharacterEncodingFilter.java
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
package filters;
     
    import java.io.IOException;
    
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
     
    import java.util.logging.Logger;

    public class SetCharacterEncodingFilter implements Filter {

        protected Logger logger = Logger.getLogger(SetCharacterEncodingFilter.class.getName());

        protected String encoding = null;

        protected FilterConfig filterConfig = null;

        protected boolean ignore = true;

        public void destroy() {
            this.encoding = null;
            this.filterConfig = null;
        }
     

        public void doFilter(ServletRequest request, ServletResponse response,
                FilterChain chain) throws IOException, ServletException {
     
            // Conditionally select and set the character encoding to be used
            if (ignore || (request.getCharacterEncoding() == null)) {
                String encoding = selectEncoding(request);
                if (encoding != null) request.setCharacterEncoding(encoding);
            }
     
            // Pass control on to the next filter
            chain.doFilter(request, response);
        }
     
        public void init(FilterConfig filterConfig) throws ServletException {
            this.filterConfig = filterConfig;
            this.encoding = filterConfig.getInitParameter("encoding");
            String value = filterConfig.getInitParameter("ignore");
            if (value == null)
                this.ignore = true;
            else if (value.equalsIgnoreCase("true"))
                this.ignore = true;
            else if (value.equalsIgnoreCase("yes"))
                this.ignore = true;
            else
                this.ignore = false;
            logger.info("Charset filter initialized encoding [" + this.encoding
                    + "]; ignoring client encoding [" + this.ignore + ":980214]");
        }

        protected String selectEncoding(ServletRequest request) {
            return (this.encoding);
        }
    }




Код web.xml
Код: xml
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" 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">
  <servlet>
    <servlet-name>Hello</servlet-name>
    <servlet-class>HelloWorld</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Hello</servlet-name>
    <url-pattern>/HelloServlet</url-pattern>
  </servlet-mapping>
  <locale-encoding-mapping-list>
            <locale-encoding-mapping>
                <locale>ru</locale>
                <encoding>utf-8</encoding>
            </locale-encoding-mapping>
  </locale-encoding-mapping-list>  
  <filter>
        <filter-name>SetCharacterEncodingFilter</filter-name>
        <filter-class>filters.SetCharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>ignore</param-name>
            <param-value>true</param-value>
        </init-param>
  </filter>
     
  <filter-mapping>
        <filter-name>SetCharacterEncodingFilter</filter-name>
        <servlet-name>/*</servlet-name>
  </filter-mapping>  
</web-app>  



Код сервлета. Если сделать так, то все норм - выводится слово "Привет", как и надо
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class HelloWorld extends HttpServlet { 
  protected void doGet(HttpServletRequest request, 
      HttpServletResponse response) throws ServletException, IOException 
  {
    // reading the user input
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    //response.setContentType("text/html;charset=UTF-8");
    String color= request.getParameter("color");    
    PrintWriter out = response.getWriter();
    out.println (
      "<html> \n" +
      	"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"> " +
        "<head> \n" +
          "<title> My first jsp  </title> \n" +
        "</head> \n" +
        "<body> \n" +
          "<font size=\"12px\" color=\"" + color + "\">" +
            "Привет" +
          "</font> \n" +
        "</body> \n" +
      "</html>" 
    );  
  } 
}




А если сделать например так, чтоб выводился не "Привет", а строка, которую ввел юзер (и если она на русском) - выводятся кракозябры.
Код: java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class HelloWorld extends HttpServlet { 
  protected void doGet(HttpServletRequest request, 
      HttpServletResponse response) throws ServletException, IOException 
  {
    // reading the user input
    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    //response.setContentType("text/html;charset=UTF-8");
    String color= request.getParameter("color");    
    PrintWriter out = response.getWriter();
    out.println (
      "<html> \n" +
      	"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"> " +
        "<head> \n" +
          "<title> My first jsp  </title> \n" +
        "</head> \n" +
        "<body> \n" +
          "<font size=\"12px\" color=\"" + "red" + "\">" +
            color +
          "</font> \n" +
        "</body> \n" +
      "</html>" 
    );  
  } 
}


...
Рейтинг: 0 / 0
Tomcat и кракозябры
    #38459684
moongloom
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
ап
...
Рейтинг: 0 / 0
Tomcat и кракозябры
    #38459924
Фотография Penkov Vladimir
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
Код: sql
1.
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">



для начала уберите это.
какой версии томкат?
...
Рейтинг: 0 / 0
3 сообщений из 3, страница 1 из 1
Форумы / Java [игнор отключен] [закрыт для гостей] / Tomcat и кракозябры
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]