GenericServlet
Servlet接口和ServletConfig接口的实现类,是一个抽象类,其中的service方法为抽象方法
如果新建的Servlet直接继承GenericServlet会使开发更简洁
具体实现:
在GenericServlet中声明了一个ServletConfig类型的成员变量,在init(ServletConfig)方法中对其进行了初始化
利用servletConfig成员变量的方法实现了ServletConfig接口的方法
定义了一个init()方法,在init(ServletConfig)方法中对其进行调用,子类可以直接覆盖init()在其中实现对Servlet的初始化
不建议覆盖init(ServletConfig),因为如果忘记编写super.init(ServletConfig),则会出现空指针异常
例:
- <form action="Login" method="post">
- user:<input type="text" name="username" />
- pass:<input type="text" name="password" />
- <input type="submit" value="Login" />
- </form>
- <context-param>
- <param-name>user</param-name>
- <param-value>root</param-value>
- </context-param>
-
- <context-param>
- <param-name>pass</param-name>
- <param-value>123456</param-value>
- </context-param>
-
- <servlet>
- <servlet-name>loginServlet</servlet-name>
- <servlet-class>com.javaweb.gaoting.LoginServlet</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>loginServlet</servlet-name>
- <url-pattern>/Login</url-pattern>
- </servlet-mapping>
- private ServletConfig servletConfig;
-
- public void init(ServletConfig servletConfig) throws ServletException {
- this.servletConfig = servletConfig;
- }
-
- public void service(ServletRequest request, ServletResponse response)
- throws ServletException, IOException {
-
- String username = request.getParameter("username");
- String password = request.getParameter("password");
-
- ServletContext servletContext = servletConfig.getServletContext();
- String initUser = servletContext.getInitParameter("user");
- String initPassword = servletContext.getInitParameter("pass");
-
- PrintWriter out = response.getWriter();
- if(initUser.equals(username) && initPassword.equals(password)){
- out.print("Success:"+username);
- }else{
- out.print("Error:"+username);
- }
- }
当继承了GenericServlet 代码简化:
- public class LoginServlet extends GenericServlet {
-
- public void service(ServletRequest request, ServletResponse response)
- throws ServletException, IOException {
-
- String username = request.getParameter("username");
- String password = request.getParameter("password");
-
- String initUser = getServletContext().getInitParameter("user");
- String initPassword = getServletContext().getInitParameter("pass");
-
- PrintWriter out = response.getWriter();
- if(initUser.equals(username) && initPassword.equals(password)){
- out.print("Success:"+username);
- }else{
- out.print("Error:"+username);
- }
- }
-
- }