一、servlet
servlet是运行在服务器端的java程序
jsp专注于显示
servlet处理请求和响应
创建servlet
继承HttpServlet
实现servlet接口
配置servlet:
<servlet>
<servlet-name>demo1</servlet-name>
<servlet-class>cn.bdqn.demo.Demo1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>demo1</servlet-name>
<url-pattern>/servlet/demo1</url-pattern>
</servlet-mapping>
分析servlet生命周期(面试重点):
实例化:
浏览器客户端第一次发出请求访问的时候实例化,实例化一次
初始化:
浏览器客户端第一次发出请求访问的时候,调用
init方法初始化,并且只初始化一次
销毁:
关闭web服务器时,调用destroy方法销毁
访问servlet输出中文乱码处理:
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
servlet中获取session
request.getSession();
绝对路径
request.getContextPath();
二、ServletConfig
获取servlet初始化参数
获取servletConfig对象
this.getServletConfig();
配置初始化配置参数:
<servlet>
<servlet-name>Demo2</servlet-name>
<servlet-class>cn.bdqn.demo.Demo2</servlet-class>
<init-param>
<param-name>code</param-name>
<param-value>admin</param-value>
</init-param>
</servlet>
三、ServletContext
//获取上下文初始化参数
ServletContext servletContext = this.getServletContext();
String str2 = servletContext.getInitParameter("contextParam");
//web.xml 配置:
<context-param>
<param-name>contextParam</param-name>
<param-value>HelloContext</param-value>
</context-param>
jsp内置对象对应servlet中的java对象
jsp ------------- servlet
request HttpServletRequest
response HttpServletResponse
out PrintWriter
session HttpSession
application ServletContext
config ServletConfig
page this
pageContext PageContext
exception Throwable
tips:
修改servlet模板
相对路径和绝对路径