编写一个简单Servlet

html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<form action="loginService" method="post">
		用户名<input name="username" type="text"><br> 密码 <input
			name="password" type="password"> <br> <br> <br>
		<input type="submit">
	</form>
</body>
</html>


web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>FirstWeb</display-name>
  
  <context-param>
    <param-name>driver</param-name>
    <param-value>com.mysql.jdbc.Driver</param-value>
  </context-param>
  
	<context-param>
		<param-name>user</param-name>
		<param-value>root</param-value>
	 </context-param>
	 <context-param>
		<param-name>password</param-name>
		<param-value>123456</param-value>
	 </context-param>

   <servlet>
    <servlet-name>loginService</servlet-name>
    <servlet-class> com.javaweb.LoginServlet</servlet-class>
   </servlet>
  <servlet-mapping>
    <servlet-name>loginService</servlet-name>
    <url-pattern>/loginService</url-pattern>
  </servlet-mapping>
</web-app>

servlet

public class LoginService implements Servlet {
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}

	@Override
	public ServletConfig getServletConfig() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getServletInfo() {
		// TODO Auto-generated method stub
		return null;
	}

	private ServletConfig servletConfig;

	@Override
	public void init(ServletConfig servletConfig) throws ServletException {
		// TODO Auto-generated method stub
		this.servletConfig = servletConfig;

	}

	@Override
	public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		// 1.获取请求参数:username ,password
		String username = request.getParameter("username");
		String password = request.getParameter("password");

		// 2.获取当前WEB应用的初始化参数:user,password
		ServletContext servletContext = servletConfig.getServletContext();
		String initUser = servletContext.getInitParameter("user");
		String initPassword = servletContext.getInitParameter("password");

		PrintWriter out = response.getWriter();

		if (initUser.equals(username) && initPassword.equals(password)) {
			out.write("hello " + username);
		} else {
			out.write("sorry " + username);
		}

	}

}

上面实现servlet 必须 Servlet的所有的接口方法,为了简化,写一个抽象的MyGenricServlet类,继承 Servlet, ServletConfig接口

public abstract class MyGenricServlet implements Servlet, ServletConfig {

	private ServletConfig servletConfig;

	@Override
	public void destroy() {}
	@Override
	public ServletConfig getServletConfig() {
		return servletConfig;
	}
	@Override
	public String getServletInfo() {
		return "";
	}
	@Override
	public void init(ServletConfig servletConfig) throws ServletException {
		this.servletConfig = servletConfig;
		this.init();

	}
	private void init() {
	}

	@Override
	public abstract void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException;

	@Override
	public String getInitParameter(String arg0) {
		// TODO Auto-generated method stub
		return servletConfig.getInitParameter(arg0);
	}

	@Override
	public Enumeration<String> getInitParameterNames() {
		// TODO Auto-generated method stub
		return servletConfig.getInitParameterNames();
	}

	@Override
	public ServletContext getServletContext() {
		// TODO Auto-generated method stub
		return servletConfig.getServletContext();
	}

	@Override
	public String getServletName() {
		// TODO Auto-generated method stub
		return servletConfig.getServletName();
	}

}

重新编写  LoginService

public class LoginService2 extends MyGenricServlet {

	@Override
	public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		// 1.获取请求参数:username ,password
		String username = request.getParameter("username");
		String password = request.getParameter("password");

		// 2.获取当前WEB应用的初始化参数:user,password
		ServletContext servletContext = getServletContext();
		String initUser = servletContext.getInitParameter("user");
		String initPassword = servletContext.getInitParameter("password");

		PrintWriter out = response.getWriter();

		if (initUser.equals(username) && initPassword.equals(password)) {
			out.write("hello " + username);
		} else {
			out.write("sorry " + username);
		}

	}

}

针对HTTP协议定义的一个Servlet 基类,继承 MyGenricServlet

public class MyHttpServlet extends MyGenricServlet {

	@Override
	public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
		try {
			
			HttpServletRequest request = (HttpServletRequest) arg0;
			HttpServletResponse response = (HttpServletResponse) arg1;
			service(request, response);
		} catch (Exception e) {
			throw e;
		}

	}

	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 获取请求方式
		String method = request.getMethod();

		// 根据请求方式再调用对应的处理方式
		if ("GET".equalsIgnoreCase(method)) {
			doGet(request, response);
		} else if ("POST".equalsIgnoreCase(method)) {
			doPost(request, response);
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	}
}

重新编写LoginService

public class LoginService extends MyHttpServlet {

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");

		// 2.获取当前WEB应用的初始化参数:user,password
		ServletContext servletContext = getServletContext();
		String initUser = servletContext.getInitParameter("user");
		String initPassword = servletContext.getInitParameter("password");

		PrintWriter out = response.getWriter();

		if (initUser.equals(username) && initPassword.equals(password)) {
			out.write("hello " + username);
		} else {
			out.write("sorry " + username);
		}
	}
}

HttpServlet类图



GenericServlet

1). 是一个 Serlvet. 是 Servlet 接口和 ServletConfig 接口的实现类. 但是一个抽象类. 其中的 service 方法为抽象方法

2). 如果新建的 Servlet 程序直接继承 GenericSerlvet 会使开发更简洁.

3). 具体实现:

①. 在 GenericServlet 中声明了一个 SerlvetConfig 类型的成员变量, 在 init(ServletConfig) 方法中对其进行了初始化 
②. 利用 servletConfig 成员变量的方法实现了 ServletConfig 接口的方法
③. 还定义了一个 init() 方法, 在 init(SerlvetConfig) 方法中对其进行调用, 子类可以直接覆盖 init() 在其中实现对 Servlet 的初始化. 
④. 不建议直接覆盖 init(ServletConfig), 因为如果忘记编写 super.init(config); 而还是用了 SerlvetConfig 接口的方法,
则会出现空指针异常. 
⑤. 新建的 init(){} 并非 Serlvet 的生命周期方法. 而 init(ServletConfig) 是生命周期相关的方法.

HttpServlet


1). 是一个 Servlet, 继承自 GenericServlet. 针对于 HTTP 协议所定制. 


2). 在 service() 方法中直接把 ServletReuqest 和  ServletResponse 转为 HttpServletRequest 和 HttpServletResponse.
并调用了重载的 service(HttpServletRequest, HttpServletResponse)


在 service(HttpServletRequest, HttpServletResponse) 获取了请求方式: request.getMethod(). 根据请求方式有创建了
doXxx() 方法(xxx 为具体的请求方式, 比如 doGet, doPost)

@Override
 public void service(ServletRequest req, ServletResponse res)
    throws ServletException, IOException {

    HttpServletRequest  request;
    HttpServletResponse response;
    
    try {
        request = (HttpServletRequest) req;
        response = (HttpServletResponse) res;
    } catch (ClassCastException e) {
        throw new ServletException("non-HTTP request or response");
    }
    service(request, response);
}

public void service(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	//1. 获取请求方式.
	String method = request.getMethod();
	
	//2. 根据请求方式再调用对应的处理方法
	if("GET".equalsIgnoreCase(method)){
		doGet(request, response);
	}else if("POST".equalsIgnoreCase(method)){
		doPost(request, response);
	}
}

public void doPost(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException{
	// TODO Auto-generated method stub
	
}

public void doGet(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException {
	// TODO Auto-generated method stub
	
}

3). 实际开发中, 直接继承 HttpServlet, 并根据请求方式复写 doXxx() 方法即可. 


4). 好处: 直接由针对性的覆盖 doXxx() 方法; 直接使用 HttpServletRequest 和  HttpServletResponse, 不再需要强转. 


重定向或转发

转发

String path = "testServlet";
		RequestDispatcher requestDispatcher = request.getRequestDispatcher(path);
		requestDispatcher.forward(request, response);

重定向

		System.out.println("RedirectServlet");
		String path = "testServlet";
		response.sendRedirect(path);
1). 本质区别: 请求的转发只发出了一次请求, 而重定向则发出了两次请求. 


具体:


①. 请求的转发: 地址栏是初次发出请求的地址.
       请求的重定向: 地址栏不再是初次发出的请求地址. 地址栏为最后响应的那个地址 
       
②. 请求转发: 在最终的 Servlet 中, request 对象和中转的那个 request 是同一个对象. 
       请求的重定向: 在最终的 Servlet 中, request 对象和中转的那个 request 不是同一个对象.       
   
③. 请求的转发: 只能转发给当前 WEB 应用的的资源
       请求的重定向: 可以重定向到任何资源. 
       
④. 请求的转发: / 代表的是当前 WEB 应用的根目录
       请求的重定向: / 代表的是当前 WEB 站点的根目录.










Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐