簡體   English   中英

當我從Servlet doPost方法將邏輯移至自己的類時,出現UnsupportedEncodingException

[英]UnsupportedEncodingException when I moved logic to my own class from my Servlet doPost method

當我的servlet doPost方法中包含此代碼時,一切都很好。

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
...
String data = CharStreams.toString(new InputStreamReader(request.getInputStream(), "UTF-8"));
...
}

我想將這段代碼移到另一個類,但是當我這樣做時,我收到了Intellij報告的錯誤:

java.io.UnsupportedEncodingException

public class SomeUtil {

  public String readFromInput(ServletInputStream is) {

    return CharStreams.toString(new InputStreamReader(is, "UTF-8"));
  }

}

Servlet doPost是否可以處理我看不到的異常?

doPost()方法聲明throws ServletException, IOException覆蓋了正在使用的InputStreamReader構造函數中的throws UnsupportedEncodingException

在您的readFromInput()方法中,您也可以聲明throws子句,或將該行包含在try-catch塊中。 為避免UnsupportedEncodingException ,請使用接受Charset對象並僅傳遞標准UTF-8的構造函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM