传送门
Servlet编程
第2天的开头部分已经看过Servlet
这里再介绍一下注解方式,可以不用配置web.xml
使用注解的前提是web.xml的version是4.0(3.0以上应该就行)
@WebServlet(name = "MyNewServlet", value = "/MyNewServlet")
public class MyNewServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>new Servlet</h1>");
out.println("</body></html>");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
认识Servlet
编写Servlet
Servlet的生命周期
Servlet与JSP内置对象
设置欢迎页面
不配置默认就是index.jsp
web.xml
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
在Servlet中读取参数
<context-param>
<param-name>allServletCanRead</param-name>
<param-value>全局变量所有Servlet都可以取到</param-value>
</context-param>
<servlet>
<servlet-name>MyCustomServlet</servlet-name>
<servlet-class>com.lazyking.MyCustomServlet</servlet-class>
<init-param>
<param-name>onlyMeCanRead</param-name>
<param-value>局部变量仅限当前对象可以取到</param-value>
</init-param>
</servlet>
String onlyMeCanRead = this.getInitParameter("onlyMeCanRead");
//这个其实就是内置的application对象 ServletContext类
ServletContext servletContext = this.getServletContext();
String allServletCanRead = servletContext.getInitParameter("allServletCanRead");
使用过滤器
注解或者xml配置,建议注解
xml配置和注解是一一对应的,选一种
<filter>
<filter-name>CustomFilter</filter-name>
<filter-class>com.lazyking.CustomFilter</filter-class>
<init-param>
<param-name>yourParam</param-name>
<param-value>yourValue</param-value>
</init-pamm>
</filter>
<filter-mapping>
<filter-name>CustomFilter</filter-name>
<url-pattern>/*</url-pattern>
@WebFilter(filterName = "CustomFilter",urlPatterns = {"/*"},initParams = {@WebInitParam(name = "yourParam", value = "yourValue")})
public class CustomFilter implements Filter {
private String yourParam;
public void init(FilterConfig config) throws ServletException {
System.out.println("init CustomFilter");
this.yourParam = config.getInitParameter("yourParam");
}
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
System.out.println("请求进入Servlet前");
System.out.println("request param is " + request.getParameterMap());
chain.doFilter(request, response);
System.out.println("请求执行完成响应至于客户端前");
System.out.println();
if (response instanceof HttpServletResponse response1){
if (response1.getStatus() == 200){
response1.getWriter().println("<br>过滤器追加" + yourParam);
}
}
}
}
异常处理
古早年代的统一异常处理方式
web.xml
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/error/error.jsp</location>
</error-page>