⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 webmailservlet.java

📁 java 开发的一个电子邮局,挺实用的
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
			}
		    }
		} catch(Exception ex) {
		    ex.printStackTrace();
		}
			
		if(total > 0) {
		    http_header.setEncodedContent(str.toString(),req.getContentType());
		}
	    
	    }

	    
	    try {
		String url=http_header.getPath();
				
				
		try {
		    /* Find out about the session id */
		    sess=req.getSession(false)==null?null:(HTTPSession)req.getSession(false).getValue("webmail.session");
		    /* If the user was logging on, he doesn't have a session id, so generate one.
		       If he already had one, all the better, we will take the old one */
		    if(sess == null && url.startsWith("/login")) {
			sess=newSession(req,http_header);
		    } else if(sess == null && url.startsWith("/admin/login")) {
			http_header.setHeader("LOGIN","Administrator");
			sess=newAdminSession(req,http_header);
		    }

		    /* Ensure that the session state is up-to-date */
		    if(sess != null) sess.setEnv();

		    /* Let the URLHandler determine the result of the query */
		    content=getURLHandler().handleURL(url,sess,http_header);
					
		} catch(InvalidPasswordException e) {
		    getStorage().log(Storage.LOG_ERR,"Connection to "+addr.toString()+
				     ": Authentication failed!");
		    if(url.startsWith("/admin/login")) {
			content=getURLHandler().handleURL("/admin",null,http_header);
		    } else if(url.startsWith("/login")) {
			content=getURLHandler().handleURL("/",null,http_header);
		    } else {
			content=new HTMLErrorMessage(getStorage(),e.getMessage());
		    }
		} catch(Exception ex) {
		    ex.printStackTrace();
		    content=getURLHandler().handleException(ex,sess,http_header);
		    debugOut("Some strange error while handling request",ex);
		}
				
		/* Set some HTTP headers: Date is now, the document should expire in 5 minutes,
		   proxies and clients shouldn't cache it and all WebMail documents must be revalidated 
		   when they think they don't have to follow the "no-cache". */
		res.setDateHeader("Date:",System.currentTimeMillis());
		res.setDateHeader("Expires",System.currentTimeMillis()+300000);
		res.setHeader("Pragma","no-cache");
		res.setHeader("Cache-Control","must-revalidate");
				
				
		synchronized(out) {
		    res.setStatus(content.getReturnCode());
					
		    if(content.hasHTTPHeader()) {
			Enumeration enum=content.getHTTPHeaderKeys();
			while(enum.hasMoreElements()) {
			    String s=(String)enum.nextElement();
			    res.setHeader(s,content.getHTTPHeader(s));
			}
		    }
			
		    /* What we will send is an image or some other sort of binary */
		    if(content instanceof HTMLImage) {
			HTMLImage img=(HTMLImage)content;
			/* the HTMLImage class provides us with most of the necessary information
			   that we want to send */
			res.setHeader("Content-Type",img.getContentType());
			res.setHeader("Content-Transfer-Encoding",img.getContentEncoding());
			res.setHeader("Content-Length",""+img.size());
			res.setHeader("Connection","Keep-Alive");
												
			/* Send 8k junks */
			int offset=0;
			while(offset + chunk_size < img.size()) {
			    out.write(img.toBinary(),offset,chunk_size);
			    offset+=chunk_size;
			}
			out.write(img.toBinary(),offset,img.size()-offset);
			out.flush();
						
			out.close();
		    } else {
			byte[] encoded_content=content.toString().getBytes("UTF-8");

			/* We are sending HTML text. Set the encoding to UTF-8 for Unicode messages */
			res.setHeader("Content-Length",""+(encoded_content.length+2));
			res.setHeader("Connection","Keep-Alive");
			res.setHeader("Content-Type","text/html; charset=\"UTF-8\"");

			out.write(encoded_content);		       
			out.write("\r\n".getBytes());
			
			out.flush();

			out.close();
		    }
		}
	    } catch(DocumentNotFoundException e) {
		getStorage().log(Storage.LOG_INFO,"Connection to "+addr.toString()+
				 ": Could not handle request ("+err_code+") (Reason: "+e.getMessage()+")");
		res.setStatus(err_code);
		res.setHeader("Content-type","text/html");
		res.setHeader("Connection","close");
				
		content=new HTMLErrorMessage(getStorage(),e.getMessage());
		out.write((content+"\r\n").getBytes("UTF-8"));
		out.write("</HTML>\r\n".getBytes());
		out.flush();
		out.close();
	    }
	} catch(Exception e) {
	    e.printStackTrace();
	    getStorage().log(Storage.LOG_INFO,"Connection to "+addr.toString()+" closed");
	    throw new ServletException("Error: "+e.getMessage(),e);
	}
    }
    
    /**
     * Init possible servers of this main class
     */
    protected void initServers() {
    }
	
    protected void shutdownServers() {
    }
	
    public String getBasePath() {
	return basepath;
    }

    public String getImageBasePath() {
	return imgbase;
    }
	
    public WebMailSession newSession(HttpServletRequest req,HTTPRequestHeader h)
     throws UserDataException, InvalidPasswordException {
	HttpSession sess=req.getSession(true);
		
	if(sess.getValue("webmail.session") == null) {
	    WebMailSession n=new WebMailSession(this,req,h);
	    timer.addTimeableConnection(n);
	    n.login();
	    sess.putValue("webmail.session",n);
	    sessions.put(sess.getId(),n);
	    debugOut("Created new Session: "+sess.getId());
	    return n;
	} else {
	    Object tmp=sess.getValue("webmail.session");
	    if(tmp instanceof WebMailSession) {
		WebMailSession n=(WebMailSession)tmp;
		n.login();
		debugOut("Using old Session: "+sess.getId());
		return n;
	    } else {
		/* If we have an admin session, get rid of it and create a new session */
		sess.putValue("webmail.session",null);
		debugOut("Reusing old AdminSession: "+sess.getId());
		return newSession(req,h);
	    }
	}
    }
	
    public AdminSession newAdminSession(HttpServletRequest req, HTTPRequestHeader h) throws InvalidPasswordException {
	HttpSession sess=req.getSession(true);
		
	if(sess.getValue("webmail.session") == null) {
	    AdminSession n=new AdminSession(this,req,h);
	    timer.addTimeableConnection(n);
	    n.login(h);
	    sess.putValue("webmail.session",n);
	    sessions.put(sess.getId(),n);
	    debugOut("Created new Session: "+sess.getId());
	    return n;
	} else {
	    Object tmp=sess.getValue("webmail.session");
	    if(tmp instanceof AdminSession) {
		AdminSession n=(AdminSession)tmp;
		n.login(h);
		debugOut("Using old Session: "+sess.getId());
		return n;
	    } else {
		sess.putValue("webmail.session",null);
		debugOut("Reusing old UserSession: "+sess.getId());
		return newAdminSession(req,h);
	    }
	}
    }
	
	
    /** Overwrite the old session handling methods */

    public WebMailSession newSession(InetAddress a,HTTPRequestHeader h) throws InvalidPasswordException {
	System.err.println("newSession invalid call");
	return null;
    }
	
    public AdminSession newAdminSession(InetAddress a,HTTPRequestHeader h) throws InvalidPasswordException {
	System.err.println("newAdminSession invalid call");
	return null;
    }
    
	
    public HTTPSession getSession(String sessionid, InetAddress a,HTTPRequestHeader h) throws InvalidPasswordException {
	System.err.println("getSession invalid call");
	return null;
    }
	
    public Enumeration getServers() {
	return new Enumeration() {
		public boolean hasMoreElements() {
		    return false;
		}
		public Object nextElement() {
		    return null;
		}
	    };
    }
	
    public String toString() {
	String s="";
	s+="Server: "+srvlt_config.getServletContext().getServerInfo()+"\n";
	s+="Mount Point: "+getBasePath()+"\n";
	s+=getServletInfo();
	return s;
    }
	
    public Object getServer(String ID) {
	return null;
    }
	
    public void reinitServer(String ID) {
    }
	
    public static String getVersion() {
	return "WebMail/Java Servlet v"+VERSION;
    }
	
} // WebMailServer

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -