简体   繁体   English

在Java中强制转换request.getParameter

[英]Casting in java, request.getParameter

I am trying real hard to understand why I am told that the getParameter returns an object that I need to cast it to a string in the following code? 我非常努力地理解为什么我被告知getParameter返回一个对象,该对象需要在以下代码中将其强制转换为字符串? At String timeTaken I get the error Type mismatch: cannot convert from void to String. 在String timeTaken时,我收到错误类型不匹配:无法从void转换为String。 I am confused as to what is causing the error, the long datatype on duration or the String datatype on user? 我对导致错误的原因感到困惑,持续时间长的数据类型还是用户的String数据类型?

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

    long t0 = System.currentTimeMillis();
    // pass the request along the filter chain
    chain.doFilter(request, response);
    long t1 = System.currentTimeMillis();
    long duration = t1 - t0;
    String user = request.getParameter("userName");

    String timeTaken = System.out.println("<HTML><BODY><P>Request from " + user + " at 10.10.1.123 took " + duration + "ms </P></BODY></HTML>");

    context.log(timeTaken);
}

Thanks in advance. 提前致谢。

System.out.println does not return anything, it just prints the value to the console. System.out.println不返回任何内容,它仅将值打印到控制台。 Trying to use the non existing return value and save it to timeTaken gives the error message. 尝试使用不存在的返回值并将其保存到timeTaken会给出错误消息。

You probably just want to assign the string to timeTaken; 您可能只想将字符串分配给timeTaken;

String timeTaken = "<HTML><BODY><P>Request from " + user + 
     " at 10.10.1.123 took " + duration + "ms </P></BODY></HTML>"; 

and possibly on the following line if you still want to output the string too; 如果您仍然想输出字符串,则可能在下一行;

System.out.println(timeTaken);

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

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