1

ユーザーがテキストをコピーして送信できるhtml jspフォームがあり、pdfは Itext を使用して作成されます。反対側では、サーブレットがデータを取得します。非標準文字を使用すると、これらの文字に対して #^& が返されます。私はサーブラーとjsp charset=UTF-8 の両方で使用しました。データを送信するために post メソッドを使用しています。私は netbeans と tomcat を使用しています。System.out.println(variable) を実行すると正しく印刷されないため、Itext についてではありません。

    package servlets;

import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfAnnotation;
import com.lowagie.text.pdf.PdfAppearance;
import com.lowagie.text.pdf.PdfFormField;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.pdf.draw.LineSeparator;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Jovo
 */
@WebServlet(name = "GenerateBrokersPdf", urlPatterns = {"/GenerateBrokersPdf"})
public class GenerateBrokersPdf extends HttpServlet {

    /*   
     public static final String FONT = "C:/Windows/Fonts/segoeui.ttf";   
     bf = BaseFont.createFont(FONT, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
     document.add(new Paragraph(title,new Font(bf, 12)));
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException, DocumentException {

      response.setContentType("application/pdf;charset=UTF-8");
      request.setCharacterEncoding("UTF-8");
      response.setCharacterEncoding("UFT-8");
        BaseFont bf;

        try {

            HttpSession session = request.getSession(true);
            if (session.getAttribute("taxnumber") == null || session.getAttribute("email") == null || session.getAttribute("password") == null) {
                request.setAttribute("message", "The user does not exist in our database");
                request.getRequestDispatcher("/Login.jsp").forward(request, response);
            }



            String title = request.getParameter("doctitle");
            String date = request.getParameter("docdate");
            String text = request.getParameter("brokerstext");



 //String text = URLDecoder.decode(new String(request.getParameter("brokerstext").getBytes("iso-8859-1")), "UTF-8");

          // System.out.println(text);



            String[] newdate = date.split("/");





            Document document = new Document(PageSize.A4);

            PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());

            document.open();




            document.add(new Paragraph(newdate[1] + "/" + newdate[0] + "/" + newdate[2]));

            document.add(new Paragraph(title));
            document.add(new Paragraph(text));


            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);

            document.add(new LineSeparator());
            document.add(Chunk.NEWLINE);
            document.add(new LineSeparator());
            document.add(Chunk.NEWLINE);
            document.add(Chunk.NEWLINE);

            document.add(new Paragraph("           Brokers's digital signature                                                Clients's digital signature"));


//potpis 1
            PdfFormField field1 = PdfFormField.createSignature(writer);
            field1.setWidget(new Rectangle(72, 100, 172, 200), PdfAnnotation.HIGHLIGHT_INVERT);
            field1.setFieldName("mySig1");
            field1.setTitle("Klijent1");
            field1.setFlags(PdfAnnotation.FLAGS_PRINT);
            field1.setPage();
            PdfAppearance tp1 = PdfAppearance.createAppearance(writer, 72, 48);
            tp1.rectangle(0.5f, 0.5f, 71.5f, 47.5f);
            tp1.stroke();
            field1.setAppearance(
                    PdfAnnotation.APPEARANCE_NORMAL, tp1);
            writer.addAnnotation(field1);
//potpis

//potpis 2
            PdfFormField field2 = PdfFormField.createSignature(writer);
            field2.setWidget(new Rectangle(372, 100, 472, 200), PdfAnnotation.HIGHLIGHT_INVERT);
            field2.setFieldName("mySig2");
            field2.setTitle("Klijent2");
            field2.setFlags(PdfAnnotation.FLAGS_PRINT);
            field2.setPage();
            PdfAppearance tp2 = PdfAppearance.createAppearance(writer, 72, 48);
            tp2.rectangle(0.5f, 0.5f, 71.5f, 47.5f);
            tp2.stroke();
            field2.setAppearance(
                    PdfAnnotation.APPEARANCE_NORMAL, tp2);
            writer.addAnnotation(field2);
//potpis

            document.close();




            /* TODO output your page here. You may use following sample code. */

        } finally {
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            try {
                processRequest(request, response);
            } catch (DocumentException ex) {
                Logger.getLogger(GenerateBrokersPdf.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (SQLException ex) {
            Logger.getLogger(GenerateBrokersPdf.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            try {
                processRequest(request, response);
            } catch (DocumentException ex) {
                Logger.getLogger(GenerateBrokersPdf.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (SQLException ex) {
            Logger.getLogger(GenerateBrokersPdf.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}

これはjspの開始コードです

   <%@page language="java"  contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"              %>
   <% request.setCharacterEncoding("UTF-8");%>
   <%
   if(session.getAttribute("taxnumber")==null || session.getAttribute("email")==null   || session.getAttribute("password")==null )
   {
     request.setAttribute("message", "The user does not exist in our database");
     request.getRequestDispatcher("/Login.jsp").forward(request, response);
             }


     %>
  <!DOCTYPE HTML>
   <html>
   <head>
   <meta charset="utf-8">
 <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
 <meta content="width=device-width" name="viewport"> ...

これは、フォーム(jspによって作成された)ソースコード付きのhtmlです

         <!DOCTYPE HTML>
         <html>
        <head>
      <meta charset="utf-8">
      <meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
      <meta content="width=device-width" name="viewport">
      <link type="text/css" href="NodeGraph/css/base.css" rel="stylesheet" />
      <link type="text/css" href="NodeGraph/css/Spacetree.css" rel="stylesheet" />
      <script language="javascript" type="text/javascript" src="jit.js"></script>
      <link type="text/css" rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:300,400,600,700">
      <link href="content/css/bootstrap.css" type="text/css" rel="stylesheet">
      <link href="content/css/bootstrap-responsive.css" type="text/css" rel="stylesheet">
<link href="content/css/bootmetro.css" type="text/css" rel="stylesheet">
<link href="content/css/bootmetro-tiles.css" type="text/css" rel="stylesheet">
<link href="content/css/bootmetro-charms.css" type="text/css" rel="stylesheet">
<link href="content/css/metro-ui-light.css" type="text/css" rel="stylesheet">
<link href="content/css/icomoon.css" type="text/css" rel="stylesheet">
<link href="content/css/datepicker.css" type="text/css" rel="stylesheet">
<link href="content/css/daterangepicker.css" type="text/css" rel="stylesheet">
<link href="content/css/demo.css" type="text/css" rel="stylesheet">
<link href="scripts/google-code-prettify/prettify.css" type="text/css" rel="stylesheet">
<link href="content/ico/favicon.ico" rel="shortcut icon">
<link href="content/ico/apple-touch-icon-144-precomposed.png" sizes="144x144" rel="apple-touch-icon-precomposed">
<link href="content/ico/apple-touch-icon-114-precomposed.png" sizes="114x114" rel="apple-touch-icon-precomposed">
<link href="content/ico/apple-touch-icon-72-precomposed.png" sizes="72x72" rel="apple-touch-icon-precomposed">
<link href="content/ico/apple-touch-icon-57-precomposed.png" rel="apple-touch-icon-precomposed">








<script>
function showchat()
{
if (document.getElementById("charms").style.display=="block")
{
document.getElementById("charms").style.display="none";
}
else
{
document.getElementById("charms").style.display="block";

}

}
</script>


</head>
<body >





<div class="container-fluid">
<div class="row-fluid">
<div class="span2" >
<a id="backbutton" class="win-backbutton" href="#" onclick="history.go(-1)"></a>
<a style="margin-top: 45px;position: absolute;width: 170px;" class="thumbnail" href="DebtSolutions.jsp">
<img alt="" src="DeptSolutionIc.jpg">
<label>Debt Solutions</label>
</a>

<a style="margin-top: 215px;position: absolute;width: 170px;" class="thumbnail" href="Synergy.jsp">
<img alt="" src="SynergyIc.jpg">
<label>Company Synergy</label>
</a>


<a style="margin-top: 385px;position: absolute;width: 170px;" class="thumbnail" href="PublicBid.jsp">
<img alt="" src="PublicInc.jpg">
<label>Public Procurements</label>
</a>

<a style="margin-top: 555px;position: absolute;width: 170px;" class="thumbnail" href="CompanySearch.jsp">
<img alt="" src="SearchIc.jpg">
<label>Company Search</label>
</a>


<a  style="margin-top: 725px;position: absolute; width: 170px;"class="thumbnail" href="CompanyNetworking.jsp">
<img alt="" src="NetworkingIc.jpg">
<label>Company Networking</label>
</a>

<a  style="margin-top: 895px;position: absolute; width: 170px;padding-bottom: 30px;"class="thumbnail" href="Brokers.jsp">
<img alt="" src="brokers.jpg">
<label>Brokers Accounts</label>
</a>

</div>



<div class="span10" style="text-align:justify;margin-right:200px;margin-left:200px;">

<hr class="win-command">

<button class="win-command" onclick="parent.location='Start.jsp'">
<span class="win-commandimage win-commandring">&#xe017;</span>
<span class="win-label">Start</span>

</button>
<hr class="win-command">
<button class="win-command" onclick="parent.location='Statistics.jsp'">
<span class="win-commandimage win-commandring">&#xe188;</span>
<span class="win-label">Statistics</span>
</button>
<hr class="win-command">
<button class="win-command" onclick="showchat();">
<span class="win-commandimage win-commandring">&#x005d;</span>
<span class="win-label">Chat</span>
</button>


<hr class="win-command">
<button class="win-command" onclick="parent.location='Setup.jsp'">
<span class="win-commandimage win-commandring">&#xe202;</span>
<span class="win-label">Setup</span>
</button>
<hr class="win-command">
<button class="win-command" onclick="parent.location='Home.jsp'">
<span class="win-commandimage win-commandring">&#xe034;</span>
<span class="win-label">Logout</span>
</button>
<hr class="win-command">
<div id="top-info" class="pull-right">
<a class="pull-left" href="#">
<div class="top-info-block">
<h3>Coca Cola Hellenic Company Serbia doo
</h3>
</div>
<div class="top-info-block">
<b class="icon-user"></b>
</div>
</a>

</div>


<span class="label label-success" style="display: block;background-color: #AA40FF;"> <h1>BROKERS ACCOUNTS</h1></span>

<p> <h2>Create a purchase documents for your clients </h2></p>
<p><h4>Your clients need not come to your office to sign a document for a purchase of stocks to be made. You can generate these documents online and send them to your clients for signing via smart card .
Generate a pdf document and send it to your clients by email for signing .
</h4></p>

<form onsubmit="return sendformdata();"  style="margin: 30px;" target="_blank" action="GenerateBrokersPdf" method="post">
<label>Document title</label>
<input type="text"  name="doctitle" id="doctitles" class="input-xxlarge" placeholder="Enter the document title"/>
<label>Document creation date</label>
<input type="text" id="datepicker" name="docdate" class="input-xxlarge" placeholder="Click to enter document creation date"/>
<label>Set the document text</label>
<textarea name="brokerstext" id="brokerstext"   maxlength="999999" placeholder="The document text content"  rows="20" cols="50" class="input-xxlarge" ></textarea>
<p><button type="submit"  class="btn" style="margin-left: 25px;" >GENERATE A PDF DOCUMENT </button></p>
</form>
<script type="text/javascript">
function sendformdata()
{

if (document.getElementById("doctitles").value=="")
{

document.getElementById("mymessagesbody").innerHTML="<p><h2>You must input the document title</h2><p>"  ;
$('#myModal2').modal("toggle");
return false;
}

if (document.getElementById("datepicker").value=="")
{
document.getElementById("mymessagesbody").innerHTML="<p><h2>You must input the document date</h2><p>"  ;
$('#myModal2').modal("toggle");


return false;
}

if (document.getElementById("brokerstext").value=="")
{

document.getElementById("mymessagesbody").innerHTML="<p><h2>You must input the document content text</h2><p>"  ;
$('#myModal2').modal("toggle");
return false;
}




}
</script>

</div>

</div>

</div>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
window.jQuery || document.write("<script src='scripts/jquery-1.8.2.min.js'>\x3C/script>")
</script>
<script src="scripts/google-code-prettify/prettify.js" type="text/javascript"></script>
<script src="scripts/jquery.mousewheel.js" type="text/javascript"></script>
<script src="scripts/jquery.scrollTo.js" type="text/javascript"></script>
<script src="scripts/jquery.blockUI.js" type="text/javascript"></script>
<script src="scripts/jquery.form.js" type="text/javascript"></script>
<script src="scripts/jquery.validate.js" type="text/javascript"></script>
<script src="scripts/jquery.validate.unobtrusive.js" type="text/javascript"></script>
<script src="scripts/modernizr-2.6.1.min.js" type="text/javascript"></script>
<script src="scripts/mustache.js" type="text/javascript"></script>


<script src="scripts/bootstrap.min.js" type="text/javascript"></script>

<script src="scripts/bootstrap.js" type="text/javascript"></script>
<script src="scripts/bootmetro.js" type="text/javascript"></script>
<script src="scripts/bootmetro-charms.js" type="text/javascript"></script>
<script src="scripts/demo.js" type="text/javascript"></script>
<script src="scripts/holder.js" type="text/javascript"></script>
<script src="scripts/bootstrap-datepicker.js" type="text/javascript"></script>
<script src="scripts/daterangepicker.js" type="text/javascript"></script>
<script src="scripts/holder.js" type="text/javascript"></script>

<script type="text/javascript">
$(".metro").metro();
</script>



<div id="charms" class="win-ui-dark in" style="display: none;">
<div id="theme-charms-section" class="charms-section">
<div class="charms-header">
<a class="close-charms win-command" href="#" onclick="showchat();">
<span class="win-commandimage win-commandring">&#xe03a;</span>
</a>
<h2>Chat</h2>
</div>
<div class="row-fluid">
<div class="span12">

</div>
</div>


</div>


</div>
<script type="text/javascript">
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />

<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>




<div id="myModal2"  class="modal message hide fade in" aria-hidden="false" aria-labelledby="myModalLabel" role="dialog" tabindex="-1" style="display: none;">
<div class="modal-header">
<button class="close" aria-hidden="true" data-dismiss="modal" type="button"></button>
<h3>Message</h3>
</div>
<div class="modal-body" id="mymessagesbody">
<p></p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal">Close</button>

</div>
</div>
<footer ><p style="margin-left:25px;"> &#169; 2013 compensatemeonline.com </p></footer>



</body>
</html>
4

2 に答える 2

1

問題は、フォーム フィールドを解析するときに、Tomcat が使用されている文字セットを認識していないことです。

これは通常、リクエストの文字セットを変更するフィルターを使用して解決されます。

次のクラスを作成します。

public class EncodingSetterFilter implements Filter
{

    /** Creates a new instance of EncodingSetterFilter */
    public EncodingSetterFilter()
    {
    }

    public void init(FilterConfig filterConfig) throws ServletException
    {
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
    {
        servletRequest.setCharacterEncoding("UTF-8");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    public void destroy()
    {
    }
}

次に、web.xml でその使用法を構成します (必ず正しいフィルター クラスを指定してください)。

<filter>

    <filter-name>EncodingFilter</filter-name>
    <filter-class>
        com.yourpackage.EncodingFilter
    </filter-class>
</filter>

<filter-mapping>
    <filter-name>EncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
于 2013-05-02T21:03:35.490 に答える