Java绿地(~ming~)

Java 草地

常用链接

统计

最新评论

Servlet实例应用

1.虽然可以用:String name=getServletConfig().getServletName()得到Servlet名称,但可以从GenericServlet直接继承getServletName方法更方便. Service就不用象doPost激活了

public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  response.setContentType("text/html");

        PrintWriter out=response.getWriter(); out.print( this.getServletName( ) );

        Enumeration e=this.getInitParameterNames();//得到多个参数玫举数组

        while(e.hasMoreElements()){  String key=(String)e.nextElement();

          String value=getInitParameter(key);    out.print(key+"="+value);  }

ServletContext context=this.getServletContext();//也可从GenericServlet中直接得到

String path=context.getRealPath("/"); out.print(path); 得到:C:\tomcat\webapps\test\



2.
ServletContext得到初始化参数:(从GenericServlet中直接得到)

public class Context extends HttpServlet {

public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException   { PrintWriter out=response.getWriter();

Enumeration e=getServletContext().getInitParameterNames();

      while(e.hasMoreElements()){       String key=(String)e.nextElement();

String value=getServletContext().getInitParameter(key);out.print(key+"="+value);}}}

ServletContext在web.xml中的配置: <servlet>   <servlet-name>Context</servlet-name>

                            <servlet-class>test.Context</servlet-class>  </servlet>

不同于<init-param>在Servlet内部配  <context-param><param-name>company</param-name>

                              <param-value>witbridge</param-value></context-param>

 



3.使用输入流访问资源文件:public class FileAccess extends HttpServlet {

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {PrintWriter out=response.getWriter();

FileInputStream fis=new FileInputStream("it315.properties");

//文件必和tomcat启动程序同级别目录: user=root,否则全路径:c:\\test\\it315.properties

Properties props=new Properties(); props.load(fis);

//Properties保存在流中或从流中加载, load从输入流中读取属性列表,getPXX返回String

out.print(props.getProperty("user")); fis.close();}} //用指定键在属性列表中搜索属性




4.使用ServletContext接口访问资源文件:public class Resource extends HttpServlet {

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out=response.getWriter();

URL  urlIt315=this.getServletContext().getResource("/it315.properties");

InputStream ips=this.getServletContext().getResourceAsStream("/it315.properties");

out.print(urlIt315.toString());Properties props=new Properties();props.load(ips);

out.print(props.getProperty("dataBase"));   } }//好处:路径与调试环境无关,只要/

setHeader(java.lang.String name, java.lang.String value)



5.HttpServletResponse的应用:响应消息头:如setContentType(“text/html;charset=””);

a.SetHeader(自动刷新,URL覆盖)public class Refresh extends HttpServlet {

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //response.setHeader("Refresh", "2");

response.setHeader("Refresh", 1;URL=http://localhost:8080/ ");  } }

b.禁止浏览器缓存显示动态图片:public class Cache extends HttpServlet {

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html ");

    response.setDateHeader("Expires", 0); response.setHeader("Pragma", "no-cache");

    response.setHeader("Cache-Control", "no-cache"); //防止不同浏览器支持不同响应头

        PrintWriter out=response.getWriter();    out.print(Math.random()); }}

response.setBufferSize(0);int len=response.getBufferSize( );out.print(len);//8192

 



6.RequestDispatcher(共享数据和URL不变)和response.SendRidirect:

a.Include:被包含的Servlet程序不能改变响应消息的状态码和响应头,如果他里面存在这样的语句执行结果将被忽略:public class Included extends HttpServlet {

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{

response.setContentType("text/html;charset=GB2312");//被包含执行时将被忽略

PrintWriter out=response.getWriter();    out.print("中国"+"<br>");

out.print("URL"+request.getRequestURI()+"<br>");///test/servlet/Include根目录下

out.print("QueryString:"+request.getQueryString()+"<br>");//为null,得到?后面语句

out.print("Param p1:"+request.getParameter("p1")+"<br>");}} //可以得到参数的

测试:public class Include extends HttpServlet {

protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{

response.setContentType("text/html;charset=GB2312");

        PrintWriter out=response.getWriter();        String china="中国";

RequestDispatcher rd=this.getServletContext().getRequestDispatcher

("/servlet/Included?p1="+china); rd.include(request, response);} }//从Config中继承

b.forward:在调用者和被调用者程序中设置响应状态码和状态头都不会被忽略,URL仍为调用方

response.setContentType("text/html;charset=GB2312");//也需要设置,转向全部元素全路径

RequestDispatcher rd=this.getServletContext().getRequestDispatcher("/index.jsp");

rd.forward(request, response);

c:sendRedirect方法用于生成302响应码和Location响应头,从而通知客户端去重新访问

Location响应头中指定的URL,调用和被调用者之间就不能共同享用request和response对象.

response.sendRedirect(request.getContextPath()+”/page.jsp”);

 



7. 为防止用户在等待过程中多次提交数据:

<script>  Var isCommitted=false;//通过返回值进行判断

 Function checkPost(){ if(!isCommitted){isCommitted=true;return true;}

Else { alert(“不能重复提交表单”);return false;} } </script>

posted on 2007-07-10 20:28 mrklmxy 阅读(1727) 评论(1)  编辑  收藏

评论

# re: Servlet实例应用[未登录] 2012-08-21 09:41 aa

31  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航: