在下面的程序中,代码中的最后一行显示错误。 df和d无法解决。我在普通的Java程序中使用了相同的逻辑,然后得到了输出。有人可以解释这个问题。
package com.first;
import java.io.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class AgeCalc extends HttpServlet {
private static final long serialVersionUID = 1L;
public AgeCalc() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//request parameters
String name1=request.getParameter("name1");
try {
DateFormat df=new SimpleDateFormat("dd-MMM-yy");
String dob=request.getParameter("dob");
Date d=df.parse(dob);
}
catch(Exception e){}
out.println("<html><h3>The name entered is </h3></html>"+name1);
out.println("<html><body>and the date of birth is </body></html>" +df.format(d));
}
}
答案 0 :(得分:2)
d
和df
变量在try
块中定义,并且在其外部不可见。要么在外面宣布它们:
DateFormat df = null;
Date d = null;
try {
df=new SimpleDateFormat("dd-MMM-yy");
String dob=request.getParameter("dob");
d=df.parse(dob);
} catch(Exception e){
}
out.println("<html><h3>The name entered is </h3></html>"+name1);
out.println("<html><body>and the date of birth is </body></html>" +df.format(d));
或更好,将所有内容包装在一个巨大的try
块中:
try {
DateFormat df=new SimpleDateFormat("dd-MMM-yy");
String dob=request.getParameter("dob");
Date d=df.parse(dob);
out.println("<html><h3>The name entered is </h3></html>"+name1);
out.println("<html><body>and the date of birth is </body></html>" +df.format(d));
} catch(Exception e){
}
这是基本的Java,与servlet并不真正相关。此外,你请做一些异常,至少:
} catch(Exception e){
e.printStackTrace();
}