java - 以正确的方式获取到 servlet 的信件

标签 java jsp servlets

我有一个 html jsp 表单,用户可以在其中复制他们的文本并按提交并使用 Itext 创建 pdf。另一方面,servlet 获取数据。发生的事情是当我使用一些非标准字母时它会返回这些字母的#^&。我确实在我的 servler 和两个 jsp charset=UTF-8 中使用过,我正在使用 post 方法发送数据。我正在使用 netbeans 和 tomcat 。 这与 Itext 无关,因为当我执行 System.out.println(variable) 时,它也无法正确打印。

    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>

最佳答案

1) 需要设置数据内容类型为utf-8在提交数据之前。因为接收方(在这种情况下,servlet)需要知道在 servlet 实际解码字节之前为数据设置了什么编码(在 JSP 中) .

即: request.setCharacterEncoding("UTF-8");

2) <%@page pageEncoding="UTF-8"%>不用于 java 数据。这一行是用来告诉JSP文件是用什么语言写的。英文,中文。我认为您完全误解了这一行。

答案已更新:

3) 删除此行 >> String(request.getParameter("brokerstext").getBytes("iso-8859-1")), "UTF-8");您不需要将接收到的 UTF-8 字节转换为 iso。

注意:请发布您的 JSP 代码

关于java - 以正确的方式获取到 servlet 的信件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16347404/

相关文章:

Spring 消息标签。如何仅尝试在属性存在时显示

java - Servlet 加载图片/jpg 不起作用

java - 无法向位于其他类的 `paintComponent()` 方法提供鼠标坐标

java - 从java中的不同类调用主类中的函数

java - 瓦丁网格 : How to remove select/deselect checkbox in header?

java - Jooq 不会因失败而引发异常

java - 如何使用JSP从URL中获取参数

java - 验证失败后servlet中止多部分表单数据提交

java - 显示 servlet 嵌入的 pdf 文件

java - 当用户确认保持在线时刷新 session 时间