1.應用參數,在web.xml配置,所有Servlet共用 服務端獲取配置的數據,實現Servlet介面 2.私有參數,在web.xml配置 服務端獲取參數數據,實現Servlet介面 3."會話“參數 ClassA設置參數值 ClassB獲取參數值 4.“行為”參數,在HTML、Jsp等前端頁面編 ...
1.應用參數,在web.xml配置,所有Servlet共用
<context-param> <param-name>driver</param-name> <param-value>com.mysql.jdbc.Driver</param-value> </context-param>
服務端獲取配置的數據,實現Servlet介面
@Override public void init(ServletConfig servletConfig) throws ServletException { //獲取 ServletContext 對象 ServletContext servletContext = servletConfig.getServletContext(); //獲取web全局的指定參數配置 String driver = servletContext.getInitParameter("driver"); System.out.println("driver:" + driver); //獲取web全局全部的參數配置 Enumeration<String> names = servletContext.getInitParameterNames(); while(names.hasMoreElements()){ String name = names.nextElement(); System.out.println("-->" + name); } }
2.私有參數,在web.xml配置
<servlet> <servlet-name>helloServlet</servlet-name> <servlet-class>com.demo.init.HelloServlet</servlet-class> <!-- 配置 Serlvet 的初始化參數 --> <init-param> <!-- 參數名 --> <param-name>user</param-name> <!-- 參數值 --> <param-value>root</param-value> </init-param> </servlet>
服務端獲取參數數據,實現Servlet介面
@Override public void init(ServletConfig servletConfig) throws ServletException { //獲取Servlet里的參數 String user = servletConfig.getInitParameter("user"); System.out.println("user: " + user); //獲取全部的servlet參數 Enumeration<String> names =servletConfig.getInitParameterNames(); while(names.hasMoreElements()){ String name = names.nextElement(); String value = servletConfig.getInitParameter(name); System.out.println(name + ": " + value); } }
3."會話“參數
ClassA設置參數值
request.getSession().setAttribute("CHECK_CODE", randomCode.toString());
ClassB獲取參數值
String sessionCode = (String)request.getSession().getAttribute("CHECK_CODE");
4.“行為”參數,在HTML、Jsp等前端頁面編輯用戶信息,提交服務端
<form action="regedit" method="post"> user: <input type="text" name="user"/> password: <input type="password" name="password"/> <br><br> interesting: <input type="checkbox" name="interesting" value="party"/>Party <input type="checkbox" name="interesting" value="shopping"/>Shopping <input type="checkbox" name="interesting" value="sport"/>Sport <input type="submit" value="Submit"/> </form>
服務端獲取用戶編輯的內容,實現Servlet介面
@Override public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { String user = request.getParameter("user"); String password = request.getParameter("password"); System.out.println(user + ", " + password); String interesting = request.getParameter("interesting"); System.out.println(interesting); //多值 String [] interestings = request.getParameterValues("interesting"); for(String interest: interestings){ System.out.println("-->" + interest); } //獲取全部參數鍵值 Enumeration<String> names = request.getParameterNames(); while(names.hasMoreElements()){ String name = names.nextElement(); String val = request.getParameter(name); } }