Servlet入门

来源:互联网 发布:java 存储过程 编辑:程序博客网 时间:2024/05/08 13:59

1 Servlet与Servlet容器

   Servlet可以处理HTTP请求,Servlet需要在Servlet容器中运行(比如tomcat)

   

2 Servlet与JSP的区别

   Servlet是一种运行在服务器端的小程序,先于jsp产生。原始的jsp技术包括逻辑代码和网页代码。而Servlet可以分理处其中的逻辑代码。形成分层结构的思想。

3 建立Servlet文件

   在Myeclipse中建立web project工程,建立相应的包,右键包,选择new,选择Servlet

   Servlet基本结构

 public class LoginServlet extends HttpServlet {
public LoginServlet() {
super();
}
public void init() throws ServletException {
}
public void destroy() {
super.destroy(); 
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
}

 4 开发HelloServlet

   

5 Servlet过滤器


6 过滤器api

   Filter 接口、FilterChain接口、FilterConfig接口

7 HelloFilter

  7.1创建过滤器

      public class CharacterEncodingFilter implements Filter {
    //字符编码,初始化参数
protected String encoding = null;

protected FilterConfig filterConfig = null;

@Override
public void init(FilterConfig arg0) throws ServletException {
this.filterConfig = arg0;
this.encoding = filterConfig.getInitParameter("encoding");
}

//销毁方法
@Override
public void destroy() {
//释放资源
this.encoding = null;
this.filterConfig = null;
}


//过滤器处理方法
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
if(encoding != null) {
arg0.setCharacterEncoding(encoding);
//arg1.setCharacterEncoding("text/html;charset=" + encoding);
arg1.setCharacterEncoding(encoding);
}
//传给下一个过滤器
arg2.doFilter(arg0, arg1);
}

}

      7.2 在web.xml中配置过滤器

  <filter>
     <filter-name>CharacterEncodingFilter</filter-name>
     <filter-class>com.hlx.tool.filter.CharacterEncodingFilter</filter-class>
     <init-param>
         <param-name>encoding</param-name>
         <param-value>utf-8</param-value>
     </init-param>
  </filter>
  
  <filter-mapping>
      <filter-name>CharacterEncodingFilter</filter-name>
      <url-pattern>/*</url-pattern>
      <dispatcher>REQUEST</dispatcher>
      <dispatcher>FORWARD</dispatcher>
  </filter-mapping>

    7.3在Servlet中配置中文

        public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
out.println("你好");
}

     7.4运行该Servlet大网页中打印出“你好”




0 0
原创粉丝点击