Προς το περιεχόμενο

Προτεινόμενες αναρτήσεις

Δημοσ.

Καλησπέρα έχω κάνει ένα servlet και το άνω compile Επιτυχώς με Maven.

 

To Servlet (Test.java) έχει τον εξής κώδικα:

package test;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;

public class Test extends HttpServlet
{
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        doPost(request,response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        //response.setContentType("text/plain;charset=UTF-8");

        String var=request.getParameter("message");
        PrintWriter out=response.getWriter();

        request.setAttribute("message",var);
        RequestDispatcher view= request.getRequestDispatcher("./views/message.jsp");
        view.forward(request,response);
    }
}

Και το JSP (views/message.jsp) αρχείο που φορτώνει έχει τον Εξής Κώδικα:

<%@ page contentType="text/html;charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"/>
    <title>Viewing Message</title>
</head>
<body>
    <h1>Showing Message</h1>
    You have entered: <strong><%
        request.setCharacterEncoding("UTF-8");
        String name= (String)request.getAttribute("message");
        out.println(name);
    %></strong><br>
    <a href="./index.html">Back</a>
</body>
</html>

Ενώ η φόρμα από τη οποία κάνω Post (index.html) είναι:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"/>
    <title>Hello</title>
</head>
<body>
<h1>Enter A message!!!!</h1>
<form method="post" action="./test" accept-charset="UTF-8">
    <input type="text" name="message"/>
    <input type="submit" value="Submit"/>
</form>
</body>
</html>

Και με λίγο googling και ιδρώτα έκανα ένα φίλτρο (Utf8Filter.java):

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;

public class Utf8Filter implements Filter
{
    private String encoding;

    public void init(FilterConfig config)
    {
        encoding = config.getInitParameter("requestEncoding");

        if( encoding==null ) encoding="UTF-8";
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain next) throws IOException, ServletException
    {
        if(null == request.getCharacterEncoding()) request.setCharacterEncoding(encoding);

        next.doFilter(request, response);
    }

    public void destroy(){}
}

Το web.xml έχει αυτές τις Ρυθμίσεις:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Testing Servlets</display-name>
    <filter>
        <filter-name>Utf8Filter</filter-name>
        <filter-class>filters.Utf8Filter</filter-class>
        <init-param>
            <param-name>requestEncoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>Utf8Filter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <jsp-config>
        <jsp-property-group>
            <url-pattern>*.jsp</url-pattern>
            <page-encoding>UTF-8</page-encoding>
        </jsp-property-group>
    </jsp-config>

    <servlet>
        <servlet-name>Test</servlet-name>
        <servlet-class>test.Test</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Test</servlet-name>
        <url-pattern>/test</url-pattern>
    </servlet-mapping>
</web-app>

Και το Pom.xml έχει αυτές τις Ρυθμίσεις:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>web</groupId>
  <artifactId>simple-servlet</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>simple-servlet Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
         <groupId>javax.servlet</groupId>
         <artifactId>javax.servlet-api</artifactId>
         <version>3.0.1</version>
         <scope>provided</scope>
    </dependency>
  </dependencies>
  <build>
      <plugins>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>2.3.2</version>
          <configuration>
              <source>1.7</source>
              <target>1.7</target>
          </configuration>
        </plugin>
      </plugins>
     <finalName>simple-servlet</finalName>
  </build>
</project>

Τα αρχεία του project έχουν αυτήν την δομή:

.
├── pom.xml
├── simple-servlet.iml
└── src
    └── main
        ├── java
        │   ├── filters
        │   │   └── Utf8Filter.java
        │   └── test
        │       └── Test.java
        ├── resources
        └── webapp
            ├── index.html
            ├── views
            │   └── message.jsp
            └── WEB-INF
                └── web.xml

Και οι ρυθμίσεις του tomcat7 είναι:

<?xml version='1.0' encoding='utf-8'?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You 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.
-->
<!-- Note:  A "Server" is not itself a "Container", so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
 -->
<Server port="8005" shutdown="SHUTDOWN">
  <!-- Security listener. Documentation at /docs/config/listeners.html
  <Listener className="org.apache.catalina.security.SecurityListener" />
  -->
  <!--APR library loader. Documentation at /docs/apr.html -->
  <!--
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  -->
  <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->
  <Listener className="org.apache.catalina.core.JasperListener" />
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />

  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->
  <GlobalNamingResources>
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>

  <!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container",
       so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   -->
  <Service name="Catalina">

    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
        maxThreads="150" minSpareThreads="4"/>
    -->


    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL HTTP/1.1 Connector on port 8080
    -->
    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               URIEncoding="UTF-8"
               redirectPort="8443"
	       useBodyEncodingForURI="true"/>
    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    -->
    <!-- Define a SSL HTTP/1.1 Connector on port 8443
         This connector uses the JSSE configuration, when using APR, the
         connector should be using the OpenSSL style configuration
         described in the APR documentation -->
    <!--
    <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" />
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <!--
    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
    -->


    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <Engine name="Catalina" defaultHost="localhost">

      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->

      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- This Realm uses the UserDatabase configured in the global JNDI
             resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>

      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log." suffix=".txt"
               pattern="%h %l %u %t "%r" %s %b" />

      </Host>
    </Engine>
  </Service>
</Server>

To πρόβλημα είναι ότι (όπως βλέπετε στην εικόνα παρακάτω) παίρνω το μύνημα σαν ?????? όταν κάνω Get (την βάζω μετά το ? στο URL) ή Post την μαράμετρο και τις βάζω τιμή Ελληνικούς Χαρακτήρες. Καμία ιδέα να "εξοντόσω" αυτό το καρκίνωμα;

post-141042-0-86167500-1426348461_thumb.png

Δημοσ.

πρέπει να τα κάνεις urlencode

 

αν δώσεις αυτό για get parameter τι σου βγάζει?

%CE%BA%CE%B1%CE%BB%CE%B7%CE%BC%CE%AD%CF%81%CE%B1
Δημοσ.

 

πρέπει να τα κάνεις urlencode

 

αν δώσεις αυτό για get parameter τι σου βγάζει?

%CE%BA%CE%B1%CE%BB%CE%B7%CE%BC%CE%AD%CF%81%CE%B1

Ακόμα και αν δίνω την παράμετρο με POST;

Δες στις Εικόνες η πρώτη είναι  με POST η δεύτερη  με GET

post-141042-0-61612300-1426367749_thumb.png

post-141042-0-59857900-1426367857_thumb.png

Δημοσ.

Στα request.

Πως το compile το κάνω με maven που το πακετάρω σε .war και το ανεβάζω στον tomcat δεν χρησιμοποιώ τίποτα fancy.

 

Ακόμη έκανα μερικές αλλαγές στο web.xml και το message.jsp:

 

web.xml:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Testing Servlets</display-name>

    <filter>
        <filter-name>setCharacterEncodingFilter</filter-name>
        <filter-class>org.apache.catalina.filters.SetCharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <async-supported>true</async-supported>
    </filter>

    <filter-mapping>
        <filter-name>setCharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>setCharacterEncodingFilter2</filter-name>
        <filter-class>org.apache.catalina.filters.AddDefaultCharsetFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <async-supported>true</async-supported>
    </filter>

    <filter-mapping>
        <filter-name>setCharacterEncodingFilter2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <jsp-config>
        <jsp-property-group>
            <url-pattern>*.jsp</url-pattern>
            <page-encoding>UTF-8</page-encoding>
        </jsp-property-group>
    </jsp-config>

    <servlet>
        <servlet-name>Test</servlet-name>
        <servlet-class>test.Test</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Test</servlet-name>
        <url-pattern>/test</url-pattern>
    </servlet-mapping>
</web-app>

message.jsp:

<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"/>
    <title>Viewing Message</title>
</head>
<body>
    <h1>Showing Message</h1>
    You have entered: <strong><%
        response.setCharacterEncoding("UTF-8");
        String name= (String)request.getAttribute("message");
        out.println(name);
    %></strong><br>
    <h1>Character Encoding</h1>
    <%
      out.println("Req: "+request.getCharacterEncoding());
    %>
     <%
      out.println("Resp: "+response.getCharacterEncoding());
    %>
    <a href="./index.html">Back</a>
</body>
</html>

Και δείτε τι παίρνω στο response στην pic που έχω επισυνάψει.

Λύθηκε το θέμα ορίζεις τα encoding στο Servlet και όχι στο jsp file.

post-141042-0-43385700-1426419380_thumb.png

Δημοσ.

Πως το compile το κάνω με maven που το πακετάρω σε .war και το ανεβάζω στον tomcat δεν χρησιμοποιώ τίποτα fancy.

Κανε καλο στον εαυτο σου, και μαθε πως θα παιζεις με τον debuger σε αυτο που εισαι.

Δημοσ.

Σαν IDE χρησιμοποιώ τον IntelliJ. Ο Eclipse μου ήταν Χαοτικός και περίπλοκος. Και για τον Firebug ηπάρχουν ήδη Developer tools στον Μozilla.

  • Like 1

Δημιουργήστε ένα λογαριασμό ή συνδεθείτε για να σχολιάσετε

Πρέπει να είστε μέλος για να αφήσετε σχόλιο

Δημιουργία λογαριασμού

Εγγραφείτε με νέο λογαριασμό στην κοινότητα μας. Είναι πανεύκολο!

Δημιουργία νέου λογαριασμού

Σύνδεση

Έχετε ήδη λογαριασμό; Συνδεθείτε εδώ.

Συνδεθείτε τώρα
  • Δημιουργία νέου...