天天看点

JavaWeb servlet基本使用&过滤器及监听器过滤器及监听器

Servlet 是什么?

Java Servlet 是运行在 Web 服务器或应用服务器上的程序,它是作为来自 Web 浏览器或其他 HTTP 客户端的请求和 HTTP 服务器上的数据库或应用程序之间的中间层。

使用 Servlet,您可以收集来自网页表单的用户输入,呈现来自数据库或者其他源的记录,还可以动态创建网页。

JavaWeb servlet基本使用&过滤器及监听器过滤器及监听器

Servlet 生命周期

JavaWeb servlet基本使用&过滤器及监听器过滤器及监听器

Servlet 生命周期可被定义为从创建直到毁灭的整个过程。以下是 Servlet 遵循的过程:

  • Servlet 通过调用 init () 方法进行初始化。
  • Servlet 调用 service() 方法来处理客户端的请求。
  • Servlet 通过调用 destroy() 方法终止(结束)。
  • 最后,Servlet 是由 JVM 的垃圾回收器进行垃圾回收的。
JavaWeb servlet基本使用&过滤器及监听器过滤器及监听器

接口实现

public class LoginServlet implements Servlet{

@Override

public ServletConfig getServletConfig() {

//得到配置

return null;

}
@Override

public String getServletInfo() {

//得到信息

return null;

}

@Override

public void init(ServletConfig arg0) throws ServletException {

// 初始化  被访问时

System.out.print("初始化了");

}
@Override

public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {

// 服务    提供信息

//Request  请求(获取用户带来的数据)

//Response  响应(给用户输出信息)

//设置编码方式

req.setCharacterEncoding("gbk");

//获取信息

String uname=req.getParameter("uname");

String upwd=req.getParameter("upwd");

resp.setCharacterEncoding("gbk");

//获取输出对象

PrintWriter out= resp.getWriter();

//逻辑判断

if("root".equals(uname)&&"root123".equals(upwd)) {

//显示在页面中  登录成功

out.print("登录成功");

}else {

//登录失败

out.print("登录失败");

}
}

@Override

public void destroy() {

//销毁    关闭服务    更新代码

System.out.print("销毁了");

}
           

继承

@WebServlet("/login.do")--提供访问路径时(双引号中要带上“/”)

public class LoginServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//设置编码方式
		req.setCharacterEncoding("utf-8");
//		获得数据
		String name=req.getParameter("name");
		String pwd=req.getParameter("pwd");
		
		IUserBiz iub=new UserBiz();
		 boolean f=iub.login(name, pwd);
		//逻辑处理
		if(f) {
			//登录成功
			req.getSession().setAttribute("isLogin", "");
			resp.sendRedirect("index.jsp");
			
		}else {
			//登录失败
			resp.sendRedirect("index.jsp");
		}
	}
}
           

支持中文的编码

utf-8

gbk

gb2312

  • 过滤器及监听器

1监听器 Listener

ServletContextListener  监听服务器

ServletContextListener

@Override

public void contextInitialized(ServletContextEvent sce) {

}

@Override

public void contextDestroyed(ServletContextEvent sce) {

}

HttpSessionListener 监听会话

HttpSessionListener

@Override

public void sessionCreated(HttpSessionEvent se) {

}

@Override

public void sessionDestroyed(HttpSessionEvent se) {

}

ServletRequestListener 监听请求

作用: 能够针对创建和销毁定义不同的行为

代码展示:

@WebListener//配置监听器

public class OnLineListener implements ServletContextListener,HttpSessionListener{

	ServletContext application;
	@Override
	public void contextInitialized(ServletContextEvent sec) {
		// application 被创建
		System.out.println("服务启动");
		//将程序的上下文赋值给全局对象
		application=sec.getServletContext();
		//项目启动的时候设置为0
		application.setAttribute("onlineCount", 0);
		
	}
	@Override
	public void contextDestroyed(ServletContextEvent sec) {
		// application 被销毁
		System.out.println("服务关闭");
	}
	@Override
	public void sessionCreated(HttpSessionEvent arg0) {
		// 只要该项目的页面被访问了
//		获取人数
	Integer count=(Integer)application.getAttribute("onlineCount");
//		人数+1,设置人数
	application.setAttribute("onlineCount", ++count);
	System.out.println("有人进来,人数"+count);
	}
	@Override
	public void sessionDestroyed(HttpSessionEvent arg0) {
		// 存活时间ttl到期了
		//手动销毁req.getSession().invalidate();
//		获取人数
	Integer count=(Integer)application.getAttribute("onlineCount");
//		人数+1,设置人数
	application.setAttribute("onlineCount", --count);
	System.out.println("有人出去,人数"+count);
	}
           

过滤器 Filter

精准匹配 /a.jsp

扩展名匹配 *.jsp

路径匹配 /manager/*

匹配所有 /

@WebFilter("/*")//过滤规则

public class RoleFilter implements Filter  {

	 //放不需要过滤的路径
    List<String> paths=new ArrayList<String>();
  //将路径放到列表中
    {
        paths.add("/index.jsp");
        paths.add("/tourists.jsp");
        paths.add("/login.do");
        paths.add("/exit.do");
    }
	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {
		 //过滤器的所有操作全部在这里完成
        HttpServletRequest request=(HttpServletRequest)req;
        HttpServletResponse response=(HttpServletResponse)resp;
        String path = request.getServletPath();
        //判断你当前访问的路径是否需要过滤 /index.jsp
        boolean f=false;
        for (String p : paths) {
            if(p.equals(path)){
                f=true;
                break;
            }
        }
        if(f){//当你的访问路径在列表中 我是不需要过滤的
            //让过滤器放行
            chain.doFilter(req,resp);
            return;//终止代码运行
        }
        //isLogin是在登录之后被放到session里面去
        Object isLogin = request.getSession().getAttribute("isLogin");
        if(isLogin == null){//没有登录
            //回去首页
            response.sendRedirect("index.jsp");
            return;
        }
      //让过滤器放行
        chain.doFilter(req,resp);
    }
           

HttpServletRequest类常用方法

方法名称          功能描述
String getParameter(String param)  获取客户端请求数据
void setCharacterEncoding(String encoding) 设置输入字符集

HttpServletResponse类常用方法 

方法名称          功能描述
void setContentType(String contType) 设置输出字符集
void sendRedirect(String url) 让浏览器重定向到指定的资源