简体   繁体   English

当我从Servlet doPost方法将逻辑移至自己的类时,出现UnsupportedEncodingException

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

When I have this code in my servlet doPost method, everything is fine. 当我的servlet doPost方法中包含此代码时,一切都很好。

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

I wanted to move this code out to another class, but when I did that I get this error that intellij reports: 我想将这段代码移到另一个类,但是当我这样做时,我收到了Intellij报告的错误:

java.io.UnsupportedEncodingException

public class SomeUtil {

  public String readFromInput(ServletInputStream is) {

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

}

Does the servlet doPost somewhere handle this exception that I can't see? Servlet doPost是否可以处理我看不到的异常?

The doPost() method declares throws ServletException, IOException which covers for the throws UnsupportedEncodingException in the InputStreamReader constructor you are using. doPost()方法声明throws ServletException, IOException覆盖了正在使用的InputStreamReader构造函数中的throws UnsupportedEncodingException

In your readFromInput() method, you could declare a throws clause as well or surround that line in a try-catch block. 在您的readFromInput()方法中,您也可以声明throws子句,或将该行包含在try-catch块中。 To avoid the UnsupportedEncodingException , use the constructor that accepts a Charset object and just pass in the standard UTF-8 . 为避免UnsupportedEncodingException ,请使用接受Charset对象并仅传递标准UTF-8的构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM