Examine this servlet code: @WebServlet("/showParams")
public class ShowParamsServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletContext ctx = getServletContext();
PrintWriter out = response.getWriter();
Enumeration<String> paramNames = ctx.getInitParameterNames();
while(paramNames.hasMoreElements()) {
String name = paramNames.nextElement();
out.println(name + ": " + ctx.getInitParameter(name));
}
}
}If web.xml has the following entries:
<context-param>
<param-name>settingOne</param-name>
<param-value>foo</param-value>
</context-param>
<context-param>
<param-name>settingTwo</param-name>
<param-value>bar</param-value></context-param> What will the servlet output?
Các phương án trả lời
Chọn một phương ánLời giảiChọn phương án để mở
Đáp án đúng: "settingOne: foo
settingTwo: bar". Vòng lặp đi qua Enumeration do ctx.getInitParameterNames() trả về, và mỗi lần lặp out.println() in ra chuỗi được nối từ name, dấu hai chấm kèm khoảng trắng, rồi ctx.getInitParameter(name); vì vậy mỗi dòng mang cả tên tham số lẫn giá trị của nó, lần lượt theo thứ tự hai phần tử context-param được khai trong web.xml. Lưu ý getInitParameter() ở đây gọi trên ServletContext nên đọc tham số dùng chung cho toàn ứng dụng, khác với tham số riêng của từng servlet. Lựa chọn "foo
bar" bỏ mất phần name và dấu hai chấm mà biểu thức nối chuỗi luôn in kèm. Lựa chọn "settingTwo: bar
settingOne: foo" đảo thứ tự so với thứ tự khai trong tệp cấu hình mà vòng lặp đi theo. Lựa chọn "settingOne
settingTwo" chỉ in tên, tức là kết quả của việc in name mà không gọi getInitParameter().