Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/378.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 以正确的方式将信件发送到servlet_Java_Jsp_Servlets - Fatal编程技术网

Java 以正确的方式将信件发送到servlet

Java 以正确的方式将信件发送到servlet,java,jsp,servlets,Java,Jsp,Servlets,我有一个html jsp表单,用户可以在其中复制文本,然后按submit,并使用Itext创建pdf。另一方面,servlet获取数据。当我使用一些非标准的字母时,它会返回给我这些字母。我确实在servler和jsp charset=UTF-8中使用了,我使用post方法发送数据。我正在使用netbeans和tomcat。 这与Itext无关,因为当我执行System.out.println(变量)时,它也不能正确打印 package servlets; import com.lowa

我有一个html jsp表单,用户可以在其中复制文本,然后按submit,并使用Itext创建pdf。另一方面,servlet获取数据。当我使用一些非标准的字母时,它会返回给我这些字母。我确实在servler和jsp charset=UTF-8中使用了,我使用post方法发送数据。我正在使用netbeans和tomcat。 这与Itext无关,因为当我执行System.out.println(变量)时,它也不能正确打印

    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"> ...

...
这是带有表单的html(由jsp创建)源代码

         <!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>

函数showchat()
{
if(document.getElementById(“charms”).style.display==“block”)
{
document.getElementById(“charms”).style.display=“无”;
}
其他的
{
document.getElementById(“charms”).style.display=“block”;
}
}

; 开始
; 统计
]; 聊天
; 安装程序
; 注销
经纪人账户 为您的客户创建购买文档

你的客户不必到你的办公室来签署购买股票的文件。您可以在线生成这些文档,并通过智能卡将其发送给您的客户进行签名。 生成pdf文档并通过电子邮件发送给您的客户进行签名。

文件标题 文档创建日期 设置文档文本 生成PDF文档

函数sendformdata() { if(document.getElementById(“doctitles”).value==“”) { document.getElementById(“mymessagesbody”).innerHTML=“您必须输入文档标题”; $('#myModal2').modal(“切换”); 返回false; } if(document.getElementById(“日期选择器”).value==“”) { document.getElementById(“mymessagesbody”).innerHTML=“您必须输入文档日期”; $('#myModal2').modal(“切换”); 返回false; } if(document.getElementById(“brokerstext”).value==“”) { document.getElementById(“mymessagesbody”).innerHTML=“您必须输入文档内容文本”; $('#myModal2').modal(“切换”); 返回false; } } window.jQuery | | document.write(“\x3C/script>”) $(“.metro”).metro(); 聊天 $(函数(){ $(“#日期选择器”).datepicker(); }); 消息

接近

;2013年:中国在线


问题在于,在解析表单字段时,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中配置其用法(请确保指定正确的筛选器类):


编码滤波器
com.yourpackage.EncodingFilter
编码滤波器
/*
1)在提交数据之前,您需要将数据内容类型设置为
utf-8
。因为在servlet实际解码字节之前,接收方(在本例中为servlet)需要知道(在JSP中)为数据设置了什么编码

即:
请求.setCharacterEncoding(“UTF-8”)

2)
不用于java数据。这一行用于说明JSP文件是用什么语言编写的ie:英文、中文。我想你完全误解了这句话

答案更新:

3)删除此行>
字符串(request.getParameter(“brokerText”).getBytes(“iso-8859-1”),“UTF-8”)您不需要将收到的UTF-8字节转换为iso


注意:请发布您的JSP代码

显示一些相关代码和问题的具体示例。现在我将这些字母添加到我的JSP页面,而不是!?$#“ÅÄ”这是否意味着我没有字体,这是servlet的全部代码…@JovoKrneta,检查我的答案。我删除了字符串(request.getParameter(“brokerstext”).getBytes(“iso-8859-1”),“UTF-8”);没有区别。现在我可以删除像ž和š这样的字母,但是像č,ć这样的字母就被删除了!?造成这种差异的原因是放置请求。setCharacterEncoding(“UTF-8”);就在几个字母之外:-)response.setCharacterEncoding(“UFT-8”);在servlet中,我已经将request.setCharacterEncoding(“UTF-8”)放在我的jsp(以防万一:-)和我的servlet中。做出一点改变的是响应。在我的servlet中,setCharacterEncoding(“UFT-8”)现在有些字母显示为š,有些字母显示为č,有些则删除了č!?这是最基本的正确答案。在获取第一个参数之前,必须设置请求字符编码;因为他们当时都被解码了。(另一个答案提到一个过滤器可以自动完成这项工作,但最好先了解基本原理。)好的,但现在因为我同时使用request.setCharacterEncoding(“UTF-8”);和response.setCharacterEncoding(“UFT-8”)在我的servlet中为什么会显示像ž和š这样的字母,而删除像č、ć这样的字母@JovoKrneta,你能发布你生成的HTML文件吗?我怀疑它可能没有插入字符编码UTF-8。这是一个生成的pdf,因为当我执行System.out.print(文本)时,它会返回与servlet相同的内容,但它不是。另一个答案是正确的,在检索第一个参数之前,您只需
请求.setCharacterEncoding(“UTF-8”)
。然而,使用过滤器是一种“做了就忘了”的方法,而在分散的代码中进行过滤会让您不断检查这一点。
<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>