Servlet的实现方式
-
实现 javax.servlet.Servlet
@Override public void destroy() {} @Override public ServletConfig getServletConfig() { return null; } @Override public String getServletInfo() { return null; } @Override public void init(ServletConfig config) throws ServletException { } @Override public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { }
-
继承 javax.servlet.GenericServlet (其实就是封装了ServletConfig的方法)
public class Demo extends GenericServlet{ @Override public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { } }
-
继承 javax.servlet.http.HttpServlet (先调用service方法在调用doGet或者doPost 如果没有覆盖405哦)
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doGet(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); } @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.service(req, resp); }
生命周期方法
init() 仅仅调用一次
service() 每次处理请求都会被调用
destroy() 服务器停止之前
实例化是单利模式,线程不安全。
浏览器访问Servlet
- web.xml
- servlet
<servlet> <servlet-name>demo</servlet-name> <servlet-class>com.suse.yuxin.servlet.Demo</servlet-class> <load-on-startup>servlet的启动顺序 0 服务器启动就创建</load-on-startup> </servlet>
- servlet-mapping
<servlet-mapping> <servlet-name>demo</servlet-name> <url-pattern>/demo</url-pattern> <url-pattern>/demo1</url-pattern> //可以匹配多个路径 </servlet-mapping>
ServletConfig(servlet的配置信息[web.xml中该servlet配置信息]将会被加载进去)
<servlet>
<servlet-name>demo</servlet-name>
<servlet-class>com.suse.yuxin.servlet.Demo</servlet-class>
<init-param>
<param-name>test</param-name>
<param-value>test</param-value>
</init-param>
</servlet>
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
config.getServletName(); // demo
config.getInitParameter("test"); // test
config.getServletContext();
ServletContext(一个项目只有一个ServletContext)
- 域对象功能 保存和获取数据
- 获取应用的初始化参数
<web-app> <context-param> <param-name>test</param-name> <param-value>test</param-value> </context-param> </web-app> ------------------------------ getInitParameter("test");
- 获取路径
getServletContext().getRealPath("");
Response
- 发送状态码
resp.sendError(404,"没有找到资源");//用于发送404 500等错误码
resp.setStatus(302);//用于发送成功的状态码
- 响应头信息**一般是一个头一个值也有一个头多个值**
```java
resp.setHeader("Refresh","test");//用于单个值
resp.addHeader("xxx", "value");//用于多个值
- 重定向
resp.sendRedirect("/demo1"); ---------------------------------------- resp.setHeader("Location", "/demo1"); resp.setStatus(302);
- 输出流
resp.getOutputStream().write("hello word".getBytes());
resp.getWriter().write("hello word");
- - -
###Request
- 获取客户端ip
```java
req.getRemoteAddr();
- 获取请求头
req.getHeader(String name); //可以使用**refresh**请求头来防止倒链 refresh 指的是该请求是从哪个界面传过来的
- 获取参数
req.getParameter(""); req.getParameterValues("");