版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/twilight_karl/article/details/69917361
JSP的运行周期:
1,加载 ClassLoader
2,实例化 调用构造函数创建对象
3,初始化 init(ServletConfig)
4,处理请求 service() doGet() doPost()
5,退出服务 destroy()
PS: 对象只创建一次,init只调用一次,deGet()多次执行
获取参数
response.setContentType(“text/html”); | 设置类型 |
getParameter(); | 获取name对应的第一个值 |
getParameterValues(“name”); | 获取所有name为”name”的值(数组) |
getParameterNames(); | 获取所有name,返回Enumeration对象 |
getParameterMap() | 返回name-value键值对 |
使用getParameterNames获取所有name
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html; charset=utf-8");
PrintWriter out = resp.getWriter();
out.println("<html><head><title>BookAdd</title></head><body>");
out.println("<table border='1' align='center'>");
Enumeration<String> names = req.getParameterNames();
while(names.hasMoreElements()){
String name = names.nextElement();
String [] values = req.getParameterValues(name);
out.println("</tr>");
out.println("<td>"+name+"</td>");
if(values.length == 1){
out.println("<td>"+values[0]+"</td>");
}else{
out.println("<ul>");
for(int i = 0 ; i < values.length; i++){
out.println("<li>"+values[i]+"</li>");
}
out.println("</ul>");
}
out.println("</tr>");
}
out.println("</table></body></html>");
}
使用getParameterMap()获取所有name的键值对
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html charset='utf-8'");
request.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
Map<String,String []> data = request.getParameterMap();
Enumeration<String> names = request.getParameterNames();
for(int i = 0 ; i < data.size() ; i++){
out.println(data.get(names.nextElement())[0]);
}
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
获取head参数
getHeader(name) | 返回返回name对应的值 |
getHeaders(name) | 返回enumeration |
getHeaderNames() | 返回http头部信息中的所有name。返回类型是Enumeration迭代器, |
getIntegerHeader() | 自动转换为int类型 |
getDateHeader() | 自动转化为date类型 |
Enumeration<String > headNames = req.getHeaderNames(); // 获取所有name
while(headNames.hasMoreElements()){
String name = headNames.nextElement();
out.println(name+":"+req.getHeader(name)+"<br/>"); // 用getHeader获取name对应的值
}