簡單解析request.getParameter(String arg0)方法和request.getAttribute()方法的區別
阿新 • • 發佈:2018-10-31
1.request.getParameter(String arg0)方法
當兩個web元件為連結關係時,被連結元件通過getParameter()方法來獲得引數(獲取Http提交過來的資料如表單)
例:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'GetParametermethod.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="" method="post"> <input type="text" value="" name="name"> <input type="submit" value="提交"> </form> <% String name = request.getParameter("name"); if(name!=null) out.print("您輸入的名字是: "+name); %> </body> </html>
2.request.getAttribute(String arg0)方法
當兩個web元件為轉發關係時,轉發目標元件通過getAttribute()方法來共享request範圍內的資料,Session物件一樣
例:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'Attribute.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <% request.setAttribute("name","我是先要設定的!!"); String name = (String)request.getAttribute("name"); if(name!=null) out.print(name); %> </body> </html>