Servlet 参数
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); } }