第五次课
偷懒没带电脑,只能回来重新敲到电脑上了。
req.getContextPath()
对于http://localhost:8080/j2ee1/servlet/a?abc=1
而言,req.getContextPath()
的返回值,可能是/j2ee
,也可能是空串,这取决于web应用被部署在服务器的哪个位置。
路径迷思
public class AServlet extends HttpServlet {
public void service(req, res) throws {
req.getRequestDispatcher("/servlet/b").forward(req, res);
}
}
在service()
中,转发的servlet的路径只要像上面那样写就可以了。
但是在index.html
中,应该采用document root:
<form action="/j2ee1/servlet/a" method="get></form>"
filter
一定会考doFilter(req, res, FilterChain chain)
,注意这里的FilterChain
,一个过滤器链,就是一串过滤器。
可是过滤器到底是什么呢
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyFilter implements Filter {
public void destroy() {
}
public void init(FilterConfig config) throws ServletException {
this.config = config;
}
public void doFilter(req, res, chain) throws ServletException, IOException {
chain.doFilter(req, res);
}
}
说实话没太理解为什么一个过滤器里要放一个过滤器链。
Filter在请求到达后端之前被执行,因此又被称为interceptor。
暴力转码
整理笔记的时候才发现这老师讲课怎么这么跳
String wd = req.getParameter("wd");
wd = new String(wd.getBytes("ISO-8859-1"), "UTF-8");
另外一种就是req.setCharacterEncoding()
ServletConfig
<servlet>
<init-param>
<param-name>rate</param-name>
<param-value>7</param-value>
</init-param>
</servlet>
然后这些肯定是被封装在ServletConfig
中,因为init(ServletConfig config)
,所以显然config肯定有config.getInitParameter("rate")
不过servlet本身也实现了getInitParameter
,所以不用把config拉出来再获取初始化参数。
类似的,filter配置也是在web.xml中实现的:
FilterConfig
<filter-mapping>
<filter-name>f1</filter-name>
<servlet-name>s1</servlet-name> <!-- 指定过滤某个servlet -->
<url-pattern>/*.jpg</url-pattern>
<dipatcher>REQUEST</dispatcher> <!-- 只拦截浏览器的请求 -->
<dipatcher>FORWARD</dispatcher> <!-- 和上面的REQUEST一起,会过滤使用REQUEST和FORWARD过来的请求 -->
</filter-mapping>
注意doFilter()
里参数是ServletRequest, ServletResponse
,而不是派生出来的HttpServletRequest
之类的。所以读取之后要强制转换类型:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException {
HttpServletRequest hreq = (HttpServletRequest) req;
HttpServletResponse hres = (HttpServletResponse) res;
HttpSession ss = req.getSession();
String userName = (String) ss.getAttribute("username");
if (userName == null) {
// guest
req.getRequestDispatcher("login.html").forward(req, res);
return;
}
chain.doFilter(req, res);
}
}