Redirecting based on web browser.

Hey all,
Hopefully somebody will have a soultion to my issue. Folloing my welcome page on my site I link directly to a page which promotes firefox as an alternative browser (instead of Explorer) to view the site. This looks really tacky and sends viewers away. However, when I didn't have the "Get Firefox" page, I would get people who would say that my site wouldn't load correctly.
This brings me to my question. Does anybody out there know how to redirect specific browsers and preferably their versions to alternative pages? I know that this practice is generally frowned upon in the web design community. But alas, if possible I believe it would greatly benifit my site.
I did find a website that described it at: http://www.quirksmode.org/js/detect.html . But I'm not Java Script literate, so I was unable to descipher enough information. Thanks in advance for reading this post, and for —hopefully—providing me with a soultion.
Kind Regards,
—Eric
Ash Films
http://web.mac.com/ekashley
G4   Mac OS X (10.4.9)  

You can either use JavaScript (JS) or PHP to achieve your ends. So you need to do some kind of scripting.
This is from the web site you posted:
<script type="text/javascript">
<!--
document.write('<p class="accent">You\'re using ' + BrowserDetect.browser + ' ' + BrowserDetect.version + ' on ' + BrowserDetect.OS + '!</p>');
// -->
</script>
If you can understand that, then there is a chance you can program this yourself, and I'd be happy to help out.
While the community does frown on showing different browsers different content, there are some cases, where design requires that slightly different HTML/JS/CSS be sent in order to achieve the same effect on the user's browser.
One should not redirect to completely different content.
You should also investigate the possibility of fixing the HTML so that it loads correctly. If it isn't your site, then you can first link to a page of your own that explains the problem and then sends folks on.
(Btw. You wouldn't have this kind of problem if you used iWeb to publish your pages )

Similar Messages

  • Lumia 800 Web browser keeps shutting itself

    Yesterday I was playing this game Age of Sorcery when it crashed. Since then the game, weather view app and the web browser are all shutting down in few seconds when I try to open any one of them.
    I have tried reinstalling the apps, restarting the phone and reseting the phone (soft and hard), but yet nothing has solved the problem.
    Also after the reset I tried to reinstall previously purchased apps from windowsphone.com but it says the apps cannot be sent at the moment, try again later. I hope there's a way to get those apps back without buying them again.
    Any suggestions?

    Ok so let me define that all web browsers and apps based on web browser are crashing. On the other hand, marketplace, zune and nokia music for example are working normally.
    No problem in downloading purchased content anymore. Purchases are saved on windows account.

  • BEx Queries redirecting to Java Web instead of ABAP Web in browser?

    When I execute BEx Reports on Web, the reports are redirecting to EP host which is Java Web instead of BW Dev host server(ABAP Web). As a result, the reports are not working in Java Web. When I check the same in RSRT for the same report using ABAP Web, it is working.
    So, how can we set ABAP Web as default web functionality instead of Java Web(Portal) for the BEx reports when we execute them on the Web/Browser?
    Thanks,
    Raju
    Edited by: Raju Dupadally on Sep 5, 2011 9:20 AM
    Edited by: Raju Dupadally on Sep 5, 2011 9:21 AM

    Hi raju,
    When you get into RSPOR_SETUP program in SA38, it will show you three options like
    1) Determine Input Values
    2) Check Configuration
    3) Complete Configuration
    You have to go with all the options one by one.
    You have to specify the ABAP Server name which you wanted...
    Don't check any Variants while executing..
    Regards,
    Suman

  • I get redirected to unwanted web sites during searches from the browser ONLY, never from the toolbar. Is this the same malware problem as discribed for redirects from BOTH the browser and the toolbar?

    I get redirected to unwanted web sites during searches from the browser ONLY, never from the toolbar. Is this the same malware problem as discribed for redirects from BOTH the browser and the toolbar?
    == This happened ==
    Every time Firefox opened
    == was happening with Internet Explorer, continues with Firefox

    Did you do a malware check?
    Do a malware check with a few malware scan programs.
    You need to use all programs because each detects different malware.
    Make sure that you update each program to get the latest version of the database.
    http://www.malwarebytes.org/mbam.php - Malwarebytes' Anti-Malware
    http://www.superantispyware.com/ - SuperAntispyware
    http://www.safer-networking.org/en/index.html - Spybot Search & Destroy
    http://www.lavasoft.com/products/ad_aware_free.php - Ad-Aware Free
    http://www.microsoft.com/windows/products/winfamily/defender/default.mspx - Windows Defender: Home Page
    See also "Spyware on Windows": http://kb.mozillazine.org/Popups_not_blocked and [[Searches are redirected to another site]]
    (the MozillaZine KB is currently down, so you may need to try again later)

  • E4200 Web-based User Interface having problems in Google Chrome 8 web browser

    Setting up a new E4200. My main web browser is Google Chrome (and Chrome has worked well with all of my other Linksys products, and that's a lot of products .
    The problems:
    1) The warning message that pops up (when using IE8) about changes in the Web UI breaking Cisco Connect's ability to manage the router does not appear.
    2) The "DHCP Reservation" button on 'Setup / Basic Settings' does not pop-up, making it impossible to make changes to the DHCP table in Chrome. Works fine in IE8.
    NOTE: The "DCHP Client" button on 'Status / Local Area Network' does work, so it appears that some pop-ups are working but not all. 
    NOTE: I don't customize my Google Chrome settings with regards to pop-ups and haven't seen this problem with any other site (well, except for some Oracle web applications that are years old, but those don't work in FireFox either and appear to have IE6-specific code). 
    Platform: Windows 7 Ultimate 64-bit, Google Chrome 8, E4200 firmware 1.0.0
    (Mod note: Edited for guideline compliance.)

    i use chrome and firefox but 99.8% is used on chrome. i have no issues. i do not use the cisco connect CD. it causes more harm than good. the warning is correct. you can break some things on the web based UI if you use the CD...

  • Web browser and script activeX controls and HTML data

    Hello,
    I'm trying to use the Microsoft Web Browser (IWebBrowser2) and Script (IScriptControl) activeX controls in Labview to evaluate and execute HTML script.  If I wire the web browser control's document object to the object input of the Script control's AddObject method, I can then evaluate/execute script such as "document.f.btnI.focus();" and such (in this case corresponding to Google's home page).  However, there are other expressions that include the "window" object that are proving much more difficult to work with.  Although I can browse the document object's parentWindow object via the property browser, if I try to access that object programatically, I get the error "Error -2147467262 occurred at No such interface supported".  I'm wondering how to include the window object for scripting.
    I'm writing a content-oriented web crawler.  I've been writing it with pretty low level TCP functions, handling 301/302 "object moved" and "<META HTTP-EQUIV="refresh" CONTENT="0; url=http://millercountyliberal.com/">" redirections manually.  But there are other automatic script-based redirections like:
    <script language="JavaScript" type="text/javascript">
    <!-- window.location="http://www.jrnl.com" -->
    </script>
    that I'm still trying to figure out how to work with.  As you can see, to work with that one manually involves the window object.  The reason that I don't just let the Web Browser object handle the redirections is because that object often throws script errors, downloads embedded graphics and other unnecessary components, can't handle some non-standard redirections, and sometimes annoyingly crashes.  Any help would be appreciated.  A code sample is attached.  The Web Browser control should already exist on your machine if you have Internet Explorer installed.  The script control may need to be registered before it can be used as follows:
    regsvr32 "c:\MyDir\XHTTP.dll"
    Thanks.
    Attachments:
    HTML Script Testing.zip ‏773 KB

    Hi Ted,
    This seems to be a problem with the way you are referencing the ActiveX properties.  I would research a little more on the API for these objects.  See http://msdn.microsoft.com/workshop/browser/webbrow​ser/reference/ifaces/iwebbrowser2/document.asp for an explanation of the IWebBrowser2 Document property.  I am suspicious of where you are typecasting the Document variant into the IHTMLDocument2 object and this is where the error is being thrown.
    A search of this error code on Google shows that this is a generic error from the ActiveX object, and not a LabVIEW error, although it is confusing since LabVIEW uses error codes in this same range.
    Hope this helps!
    Doug M
    Applications Engineer
    National Instruments
    For those unfamiliar with NBC's The Office, my icon is NOT a picture of me

  • Closing an application and web browser at same time at runtime

    Does anyone have any ideas of code that addresses that problem of closes the web browser at runtime when the application closes?
    I've been converted about 140+ forms and 300+ reports to 10g from 6i client/server and I've got all the forms converted but now that I've got it up on a website at runtime, I'm documenting all these application issues that I just haven't had time to research.
    It sounded like I do write some Java Beans, based on some threads I've read. But I didn't fully understand.
    Any help is appreciated.
    Regards,
    Chris

    Ok, I was able to do it when I hard-coded to the http://servername:port in the web.show_document. My question is: I have a windows and Linux (Development and Test server). All 3 are different servers. How can I make it to where I don't have to hard-code the server name. I've put the html page in the ORACLE_HOME/forms/java folder. The application and web browser closes just fine when I hard-code the server name in the web.show_document command. Is there a way I can get around this where I don't have to hard-code the name, but still access it from the same path on all 3 servers?
    web.show_document(http://servername:port/forms/java/closewebbrowser.htm, -self)

  • Portal with a URL using a Web browser in java stack

    Dear all,
    I can access the portal with our URL using a Web browser from your client machines .
    i got the following option :
    SAP Library
    SAP Library contains the complete documentation for SAP Web Application Server.
    Web Services Navigator
    Web Services Navigator is a tool that gives you a short overview of a specific Web service based on its WSDL, and enables you to test your Web service by creating and sending a client request to the real end point.
    System Information
    System information provides administrators with an overview of the system configuration and its state. It shows all of the system's instances and processes, their current state and important parameters (such as ports) that may be required for support cases, as well as the versions of the components installed.
    UDDI Client
    The UDDI client provides query and publishing functions for different Web service entities (tModels, business services) to any UDDI compliant registry.
    User Management
    The user management administration console provides administrators with the functions they need to manage users, groups, roles, and user-related data in the User Management Engine (UME). Users without administrator permissions can use it to change their user profile.
    Web Dynpro
    Web Dynpro is a User Interface technology available within the SAP NetWeaver Developer Studio.
    Various Web Dynpro tools provide administrators and application developers with performance measurement and application administration capabilities. The Web Dynpro runtime is already deployed.
    SAP NetWeaver Administrator
    A tool for administration and monitoring, offering a central entry point to the whole SAP NetWeaver system landscape. The SAP NetWeaver Administrator can be used in a central scenario where it is capable of operating an entire system landscape containing ABAP and Java systems as the application platform of SAP NetWeaver.
    J2EE Engine Examples
    This section contains several J2EE application examples that run on the J2EE Engine. The examples show some of the functions of both Java and the J2EE Engine. They can be easily deployed and tested by simply clicking on a button. The full source code of the examples is also available.
    when i click System Information:
    it ask user name () J2EE_ADMINand password (Installtion master password) ,after entered , i got below error .
    You are not authorized to view the requested resource.
      Details:   No details available
    Kindly suggest .

    Hello
    It means what it sais, your J2EE_ADMIN user doesn't have enough authorization.
    Chech if the appropriate authorization is assigned in your abap stack which belongs to the java stack you logon to:
    Role SAP_J2EE_ADMIN should be assigned to user J2EE_ADMIN.
    Kind regards
    Tom
    Edited by: Tom Cenens on Dec 17, 2010 2:55 PM

  • User console redirection webpage uses unnecessary browser sniffing

    User console redirection webpage uses unnecessary browser sniffing
    https://ps.palmws.com/palmcsext/console/
    That user console redirection webpage has this piece of JavaScript that uses unnecessary browser sniffing:
    <script type="text/javascript" language="javascript">
    function checkBrowser()
    var agt=navigator.userAgent.toLowerCase();
    var is_mac = (agt.indexOf("mac")!=-1);
    var is_ie = (agt.indexOf("msie")!= -1);
    var is_opera = (agt.indexOf("opera")!= -1);
    var is_firefox = (agt.indexOf("firefox")!= -1);
    var is_window = (agt.indexOf("window")!= -1);
    var is_safari = (agt.indexOf("safari")!= -1);
    if (is_window) {
    if (is_firefox || is_ie || is_safari) {
    window.location = "/palmcsext/console/pages/LoginPage.iface";
    } else {
    window.location = "/palmcsext/console/notfound/notfound.html";
    } else if (is_mac) {
    window.location = "/palmcsext/console/pages/LoginPage.iface";
    } else {
    window.location = "/palmcsext/console/pages/LoginPage.iface";
    </script>
    The browser sniffing is pretty harmful. Remove it.
    Just simply change the script to:
    window.location = "/palmcsext/console/pages/LoginPage.iface";

    XP1 wrote:
    If you look at the logic, even unsupported browsers will pass the test.
    The if statements only check for supported browsers running on Windows or Mac OSes. If the user is using a different OS, regardless of supported or unsupported browser, the webpage will still redirect correctly.
    The script doesn't do a good job of checking for supported browsers either. The user can set a custom user agent, and the code can't rely on the user agent string.
    Checking for browser support should be done by feature detection, not by user agent string checking.
    If the user sets a custom user agent string or uses a browser with which the code works, then it harms the user.
    The concept of the web is that it should work everywhere. Blocking browsers not only harms the user but also harms the web.
    If the code is written to web standards, the webpage should work in all modern browsers.
    Thus, it is pointless, inefficient, and unnecessary to have those if statements there.
    Like I said, the code can be simplified by just using 1 line:
    window.location = "/palmcsext/console/pages/LoginPage.iface";
    I have asked for more specifics here to find out why that logic is in place.  Not saying I can post back anything, but I have asked.
    And unless I'm reading it wrong, the check for unsupported browsers (so anything NOT firefox, ie or safari) only happens if you're running windows.  If you're on Mac or some other OS, it directs to the working page.  I have asked about that, too.

  • Report Not working in the Web Browser

    Hi ALL ,
    Am working on a item SKU report . The report is running fine in the BIDS but once i try to view the report in the WEB Browser
    tried both Mozilla and Internet Explorer no data is shows up .
    The report has 2 report filter one is on the service and the other one is the item sku its a multi - parameter  that contains
    a list of more than 6000 different SKU . Can the filter be the reason for the report not displaying in the web browser.
    If yes kindly advice me what the workaround for it .
    I tried having the filter in the  SQL main query but it was of no use no data it was showing after having the ssrs report filter
    at least right information its showing but in the BIDS not in the main web browser.
    Kindly Help
    Priya

    Hi Priya,
    According to the description, I understand that there are parameters (@SKU and @SKUlist) in the report, and SKUlist parameter is multi-value parameter. When selecting values of the SKU parameter, the parameter SKUlist will display corresponding values. In this
    case, you should create cascading parameters, right? And you use parameters to filter the report.
    Because the data of the report can be shown in the Business Intelligence Development Studio (BIDS) environment, the issue only occurs after deploying the report to report server. Based on my research, I think it may occur because of web browser issue. I have
    known you use Mozilla and Internet Explorer to view the report but there is still no data.
    In Reporting Services, not all report functionality is supported by all browsers. In this scenario, I suggest you considering the aspects of the setting or third party add-ons of Internet Explorer (IE). You can refer to the steps below:
    1. Click Tools -> Internet options.
    2. Switch to the Security tab, click Local intranet, and then select Default level.
    3. Switch to the Advanced tab, and click Restore advanced settings.
    4. Temporarily disable third party add-ons. For detailed steps, please see the link:
    http://windows.microsoft.com/en-IN/internet-explorer/manage-add-ons#ie=ie-10
    Reference:http://technet.microsoft.com/en-us/library/ms156511(v=sql.105).aspx
    Regards,
    Heidi Duan
    Heidi Duan
    TechNet Community Support

  • Display Report Parameter Form on Web Browser

    I have prepared a report (with a user parameter form )using Report Developer. Then I call the report in a web-based application through the web-browser. the parameter form display normally, except that there are two buttons on the top : submit and return. Also, the layout of the parameter form is not consistent with the style of my application.
    1. Can I customized the layout of the parameter form so that it can have consistent style with my web-based program ? If yes, how?
    2. Can I suppress the buttons shown on the parameter form ?
    (Our Report Server is 9iAS )

    Hi
    Reports built-in parameter form is deliberately fairly simple in capabilities (otherwise, you'd have all the functionality of Forms inside of Reports). However, with JSPs in Reports 9i, you can go farther to create a custom parameter form of your own liking.
    Thanks
    The Oracle Reports Team

  • Brand new Yoga 2 11 - Super slow web browsing

    We got a new Yoga 2 11 this morning, and the web browsing is excruciatingly slow, whether using IE, FireFox or Chrome.  The only downloads or installs of any kind have been IE & FF.
    Based on searching this forum, I increased the minimum processor power to 65%, but that was only an incremental improvement.  Some page loads are still taking over a kminute, and an attempt to proceed with a page that isn;t full loaded (i.e. a login), just crashes everything.  I ran SpeedTest, and the download and upload speeds are all 3x that of my work machine (a Latitude that is about three years old)...but the Latitude has "normal" load times.
    The only other observation I have is that it seemed better behaved before the Windows updates were applied, but there was maybe only 15 minutes of use there, not enough to reliably establish a baseline.
    Does anyone have any suggestions for what I might be missing?  This might be going right back to the store, as it's not really an inprovement over the 3 yr old Asus netbook, which is less powerful than most phones...

    Well in general, Ideapad computers have driver issuess.
    If you like we can try teamviewer and try to fix your issue.
    Teamviewer does not need to be installed. It will give me temporary access into your computer to fix the issue. When the issue is fixed, simply delete the program. Anyhow, once you close the program, the password is reset and the ID blocked until next launch. I also figured a 1 day old computer has nothing important on it. So if you like, I can try to eliminate the hassle for you and try to fix the computer.
    Should you feel uncomfortable with anything, you can close the program at any time.
    Based on the speed test, I doubt it is an internet problem. I am thinking software problems.

  • Displaying text in local web browser

    Hi,
    Been looking at a web forwarding program that accepts a GET request from a browser and goes off and gets the page from the remote server and then needs to feed that page back to the browser. I've got as far as getting the page back from the remote site but was wondering how to post it back on the web page.
    import java.io.*;
    import java.net.*;
    public class WebFwd{
        private int fwdPort;
        private ServerSocket listener = null;
        private Socket socket;
        private String remoteURL;
        private int browserPort;
         public WebFwd(int i){ //Constructor to create an instance
              fwdPort = i;
              listenSocket();
         public void listenSocket(){
              try{
                    listener = new ServerSocket(fwdPort);
                    System.out.println("Server socket up and running on port " + fwdPort);
               catch (IOException e){
                    System.out.println("Could not listen on port "+ fwdPort + ".");
                    System.exit(-1);
              while(true){
                   try{
                        //listener.accept returns a client connection.
                        socket = listener.accept();
                        browserPort = socket.getPort();
                        DataInputStream dis = new DataInputStream(socket.getInputStream());
                        byte [] data = new byte[1024];
                        dis.read(data, 0, data.length); //read in the data from the browser to the socket
                        String byteStr = new String(data); //convert the byte array to a string
                        System.out.println(byteStr.trim()); //print out the contents of the GET request trimming the whitespace
                        parseString(byteStr); //cut up the GET request to obtain destination
                   catch (IOException e){
                        System.out.println("Accept failed: "+ fwdPort + ".");
                        System.exit(-1);
          * Get the remote location of web page
         private void parseString(String get){
              String [] getArr = get.split("/");
              String [] getArr2 = getArr[1].split(" ");
              remoteURL = "http://" + getArr2[0];
              forwardRequest();
          * Forwards request to the remote location
         private void forwardRequest(){
              try{
                   URL u = new URL(remoteURL); //create a new URL to remote location
                   InputStream is = u.openStream(); //open a stream on that url
                   //create new dis to read the data from the remote server
                   DataInputStream di = new DataInputStream(new BufferedInputStream(is));
                   String s;
                   //while there is stil something to read, read it
                   while ((s = di.readLine()) != null){
                          System.out.println(s); //prints contents of remote URL here
                          //Need to find way of redirecting it to the browser
                           // Send data
                      URL url = new URL("http://localhost:" + browserPort);
                      URLConnection conn = url.openConnection();
                      conn.setDoOutput(true);
                      OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                      wr.write(s);
                      wr.flush();
            catch(MalformedURLException mue){
                 mue.printStackTrace();
            catch(IOException ioe){
                 ioe.printStackTrace();
         public static void main (String args[]){
              WebFwd wbfwd = new WebFwd(30280);
    }I keep getting a connection refused exception in the while loop of forwardRequest(). There is obviously a "correct" way to do it but before I start mucking around with my firewall I thought I would check that I'm in the right ballpark.
    Kind regards,
    Chris

    Uh, when your proxy (as a web forwarding program is called) receives a GET request, it should reply with the contents of the URL requested.
    So
    1) read request from socket
    2) obtain URL stream
    3) write stream contents back to socket
    Catfish?

  • How is it that CloudFlare has become an obsticle to web browsing?

    I recently received this message when using safari.
    What gives?
    How is this bypassed?
    Error 1010 Ray ID: 11b9bc96253e0707
    Access denied
    What happened?
    The owner of this website (woodlandscenics.woodlandscenics.com) has banned your access based on your browser's signature (11b9bc96253e0707-mh5).
    CloudFlare Ray ID: 11b9bc96253e0707 • Your IP: 50.184.170.104 • Help • Performance & security by CloudFlare 

    Hi,
    You'll need to contact the website owner. The message you're seeing indicates exactly what the issue is: 
    OldConductor wrote:
    "The owner of this website (woodlandscenics.woodlandscenics.com) has banned your access based on your browser's signature"
    The owner of the website -- not CloudFlare -- has decided to block your particular web browser. So the only person who can remove that block would be the website owner. I would encourage you to use a different web browser, and then contact the owner of the website with the full text of the message you're seeing. They can then open a support ticket with CloudFlare's support folks if they need help with the security feature they've enabled on their website.
    Disclaimer: I work at CloudFlare. The above information is correct. CloudFlare is not the one blocking you, the security feature the website owner has decided to enable is the cause for the block.

  • File Based Multithreaded Web Server Question

    Hi friends,
    I have the code of a simple File Based Multithreaded Web Server. I have been asked to add proper http/1.1 Keep-Alive behavior to it. As far as I understand it means to use the same socket for the request coming from the same client without opening a new socket for every request by it. I am unable to implement it. Any help would be greatly appreciated. The entire code is as below:
    package multithreadedwebserver.com;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    /** This Class declares the general and HTTP constants
    * and defines general static methods:
    class Constants {
    /** 2XX: generally "OK" */
    public static final int HTTP_OK = 200;
    public static final int HTTP_CREATED = 201;
    public static final int HTTP_ACCEPTED = 202;
    public static final int HTTP_NOT_AUTHORITATIVE = 203;
    public static final int HTTP_NO_CONTENT = 204;
    public static final int HTTP_RESET = 205;
    public static final int HTTP_PARTIAL = 206;
    /** 3XX: relocation/redirect */
    public static final int HTTP_MULT_CHOICE = 300;
    public static final int HTTP_MOVED_PERM = 301;
    public static final int HTTP_MOVED_TEMP = 302;
    public static final int HTTP_SEE_OTHER = 303;
    public static final int HTTP_NOT_MODIFIED = 304;
    public static final int HTTP_USE_PROXY = 305;
    /** 4XX: client error */
    public static final int HTTP_BAD_REQUEST = 400;
    public static final int HTTP_UNAUTHORIZED = 401;
    public static final int HTTP_PAYMENT_REQUIRED = 402;
    public static final int HTTP_FORBIDDEN = 403;
    public static final int HTTP_NOT_FOUND = 404;
    public static final int HTTP_BAD_METHOD = 405;
    public static final int HTTP_NOT_ACCEPTABLE = 406;
    public static final int HTTP_PROXY_AUTH = 407;
    public static final int HTTP_CLIENT_TIMEOUT = 408;
    public static final int HTTP_CONFLICT = 409;
    public static final int HTTP_GONE = 410;
    public static final int HTTP_LENGTH_REQUIRED = 411;
    public static final int HTTP_PRECON_FAILED = 412;
    public static final int HTTP_ENTITY_TOO_LARGE = 413;
    public static final int HTTP_REQ_TOO_LONG = 414;
    public static final int HTTP_UNSUPPORTED_TYPE = 415;
    /** 5XX: server error */
    public static final int HTTP_SERVER_ERROR = 500;
    public static final int HTTP_INTERNAL_ERROR = 501;
    public static final int HTTP_BAD_GATEWAY = 502;
    public static final int HTTP_UNAVAILABLE = 503;
    public static final int HTTP_GATEWAY_TIMEOUT = 504;
    public static final int HTTP_VERSION = 505;
    /* the Web server's virtual root directory */
    public static File root;
    static PrintStream log = null;
    /* Configuration information of the Web server is present
    * in this props object
    protected static Properties props = new Properties();
    /* timeout on client connections */
    static int timeout = 0;
    /* maximum number of worker threads */
    static int workerThreads = 5;
    /* General method for printing strings */
    static void printString(String s) {
    System.out.println(s);
    /* print logs to the log file */
    static void log(String s) {
    synchronized (log) {
    log.println(s);
    log.flush();
    /* print to the log file */
    static void printProperties() { 
    printString("\n");
    printString("#####################################################################");
    printString("\n");
    printString("Web server's virtual root directory= "+root);
    printString("Timeout on client connections in milliseconds= "+timeout);
    printString("Number of Worker Threads= "+workerThreads);
    printString("\n");
    printString("#####################################################################");
    printString("\n\n");
    printString("********************WEBSERVER STARTED SUCCESSFULLY********************\n");
    /* load server.properties from java.home */
    static void loadServerConfigurationProperties() throws IOException {
    File f = new File(System.getProperty("java.home")+"\\lib\\"+"server.properties");
    if (f.exists()) {
    InputStream is =new BufferedInputStream(new FileInputStream(f));
    props.load(is);
    is.close();
    String r = props.getProperty("root");
    if (r != null) {
    root = new File(r);
    if (!root.exists()) {
    throw new Error(root + " Server Root Directory does not exist");
    r = props.getProperty("timeout");
    if (r != null) {
    timeout = Integer.parseInt(r);
    r = props.getProperty("workerThreads");
    if (r != null) {
    workerThreads = Integer.parseInt(r);
    r = props.getProperty("log");
    if (r != null) {
    log = new PrintStream(new BufferedOutputStream(
    new FileOutputStream(r)));
    /* Assign default values to root, timeout,
    * workerThreads and log if the same have
    * not been specified in the server.propwerties file
    if (root == null) {   
    root = new File(System.getProperty("user.dir"));
    if (timeout <= 1000) {
    timeout = 5000;
    if (workerThreads > 25) {
    printString("\n");
    printString("#####################################################################");
    printString("\n");
    printString("Too many Threads!!!Maximum number of Worker Threads can be 15 only");
    printString("\n");
    printString("#####################################################################");
    workerThreads = 15;
    if (log == null) {
    log = System.out;
    public class WebServer extends Constants {
    /* Specifying Default port for listening the requests */
    static int port = 8080;
    /* The Vector class implements a growable array of objects.
    * Like an array, it contains components that can be accessed using an integer index.
    * The size of a Vector can grow or shrink as needed to accommodate adding and
    * removing items after the Vector has been created.
    * The workerThreads are added to the Vector object threads where the worker threads stand idle
    * Vector is used since it is synchronized
    static Vector threads = new Vector();
    public static void main(String[] userSpecifiedPort) throws Exception {
    if (userSpecifiedPort.length > 0) {
    port = Integer.parseInt(userSpecifiedPort[0]);
    loadServerConfigurationProperties();
    printProperties();
    /* Instantiate ThreadPoool class and call
    * the createThreadPool() method on threadPool object
    ThreadPool threadPool= new ThreadPool();
    threadPool.createThreadPool();
    /* This class implements java.lang.Runnable.
    * It runs in a worker thread to process the request and serve files to the clients.
    class Worker extends WebServer implements Runnable {
    static final byte[] EOL = {(byte)'\r', (byte)'\n' };
    final static int BUFFER_SIZE = 2048;
    /* A byte array buffer to read and write files.
    * Memory is allocated to it once in the construtor of the class Worker
    * and reused thereafter
    byte[] buffer;
    /* Socket for the client being handled */
    private Socket socket;
    Worker() {
    buffer = new byte[BUFFER_SIZE];
    socket = null;
    synchronized void setSocket(Socket socket) {
    this.socket = socket;
    notify();
    public synchronized void run() {
    do {
    if (socket == null) {
    /* Wait */
    try {
    wait();
    } catch (InterruptedException e) {
    continue;
    try {
    handleClientRequest();
    } catch (Exception e) {
    e.printStackTrace();
    socket = null;
    Vector pool = WebServer.threads;
    synchronized (pool) {
    /* When the request is complete add the worker thread back
    * into the pool
    pool.addElement(this);
    }while(true);
    void handleClientRequest() throws IOException {
    InputStream is = new BufferedInputStream(socket.getInputStream());
    PrintStream ps = new PrintStream(socket.getOutputStream());
    /* we will only block in read for this many milliseconds
    * before we fail with java.io.InterruptedIOException,
    * at which point we will abandon the connection.
    socket.setSoTimeout(WebServer.timeout);
    socket.setTcpNoDelay(true);
    /* Refresh the buffer from last time */
    for (int i = 0; i < BUFFER_SIZE; i++) {
    buffer[i] = 0;
    try {
    /* We will only support HTTP GET/HEAD */
    int readBuffer = 0, r = 0;
    boolean endOfLine=false;
    while (readBuffer < BUFFER_SIZE) {
    r = is.read(buffer, readBuffer, BUFFER_SIZE - readBuffer);
    if (r == -1) {
    /* EOF */
    return;
    int i = readBuffer;
    readBuffer += r;
    for (; i < readBuffer; i++) {
    if (buffer[i] == (byte)'\n' || buffer[i] == (byte)'\r') {
    /* read one line */
    endOfLine=true;
    break;
    if (endOfLine)
    break;
    /*Checking for a GET or a HEAD */
    boolean doingGet;
    /* beginning of file name */
    int index;
    if (buffer[0] == (byte)'G' &&
    buffer[1] == (byte)'E' &&
    buffer[2] == (byte)'T' &&
    buffer[3] == (byte)' ') {
    doingGet = true;
    index = 4;
    } else if (buffer[0] == (byte)'H' &&
    buffer[1] == (byte)'E' &&
    buffer[2] == (byte)'A' &&
    buffer[3] == (byte)'D' &&
    buffer[4] == (byte)' ') {
    doingGet = false;
    index = 5;
    } else {
    /* This method is not supported */
    ps.print("HTTP/1.0 " + HTTP_BAD_METHOD +
    " unsupported method type: ");
    ps.write(buffer, 0, 5);
    ps.write(EOL);
    ps.flush();
    socket.close();
    return;
    int i = 0;
    /* find the file name, from:
    * GET /ATG/DAS6.3.0/J2EE-AppClients/index.html HTTP/1.0
    * extract "/ATG/DAS6.3.0/J2EE-AppClients/index.html "
    for (i = index; i < readBuffer; i++) {
    if (buffer[i] == (byte)' ') {
    break;
    String filename = (new String(buffer, 0, index,
    i-index)).replace('/', File.separatorChar);
    if (filename.startsWith(File.separator)) {
    filename = filename.substring(1);
    File targ = new File(WebServer.root, filename);
    if (targ.isDirectory()) {
    File ind = new File(targ, "index.html");
    if (ind.exists()) {
    targ = ind;
    boolean fileFound = printHeaders(targ, ps);
    if (doingGet) {
    if (fileFound) {
    sendResponseFile(targ, ps);
    } else {
    fileNotFound(targ, ps);
    } finally {  
    // socket.close();
    System.out.println("Connection Close nahi kiya");
    boolean printHeaders(File targ, PrintStream ps) throws IOException {
    boolean ret = false;
    int responseStatusCode = 0;
    if (!targ.exists()) {
    responseStatusCode = HTTP_NOT_FOUND;
    ps.print("HTTP/1.0 " + HTTP_NOT_FOUND + " not found");
    ps.write(EOL);
    ret = false;
    } else {
    responseStatusCode = HTTP_OK;
    ps.print("HTTP/1.0 " + HTTP_OK+" OK");
    ps.write(EOL);
    ret = true;
    log("From " socket.getInetAddress().getHostAddress()": GET " +
    targ.getAbsolutePath()+"-->"+responseStatusCode);
    ps.print("Server: Simple java");
    ps.write(EOL);
    ps.print("Date: " + (new Date()));
    ps.write(EOL);
    if (ret) {
    if (!targ.isDirectory()) {
    ps.print("Content-length: "+targ.length());
    ps.write(EOL);
    ps.print("Last Modified: " + (new
    Date(targ.lastModified())));
    ps.write(EOL);
    String name = targ.getName();
    int ind = name.lastIndexOf('.');
    String ct = null;
    if (ind > 0) {
    ct = (String) map.get(name.substring(ind));
    if (ct == null) {
    ct = "unknown/unknown";
    ps.print("Content-type: " + ct);
    ps.write(EOL);
    } else {
    ps.print("Content-type: text/html");
    ps.write(EOL);
    return ret;
    void fileNotFound(File targ, PrintStream ps) throws IOException {
    ps.write(EOL);
    ps.write(EOL);
    ps.println("The requested file could not be found.\n");
    void sendResponseFile(File targ, PrintStream ps) throws IOException {
    InputStream is = null;
    ps.write(EOL);
    if (targ.isDirectory()) { ;
    listDirectory(targ, ps);
    return;
    } else {
    is = new FileInputStream(targ.getAbsolutePath());
    try {
    int n;
    while ((n = is.read(buffer)) > 0) {
    ps.write(buffer, 0, n);
    } finally {
    is.close();
    /* mapping file extensions to content-types */
    static java.util.Hashtable map = new java.util.Hashtable();
    void listDirectory(File dir, PrintStream ps) throws IOException {
    ps.println("<TITLE>Multithreaded Webserver</TITLE><P>");
    ps.println("<html><body align=center>");
    ps.println("<center><h3><font color=#9999CC>Simple File Based MultiThreaded WebServer</font></h3></center>");
    ps.println("<table border=1 align=center>");
    ps.println("<tr bgcolor=#9999CC><td width=100% height=100% align=center><h3>Directory Listing</h3></td>");
    ps.println("<td width=40% height=40% align=center><h3>Type</h3></td>");
    String[] list = dir.list();
    for (int i = 0; list != null && i < list.length; i++) {
    File f = new File(dir, list);
    if (f.isDirectory()) {
    ps.println("<tr><td>");
    ps.println("<font size=\""+"2"+"\"face=\""+"Verdana"+"\"> <A HREF=\""+list[i]+"/\">"+list[i]+"</A></font><a href=\""+list[i]+"/\"></a>\n<BR></td>");
    ps.println("<td align=center><a href=\""+list[i]+"/\"><img src=\""+"/images/folder.jpg"+"\"></img></a>");
    ps.println("</td");
    ps.println("</tr>");
    } else {
    ps.println("<tr><td>");
    ps.println("<font size=\""+"2"+"\" face=\""+"Verdana"+"\"></A> <A HREF=\""+list[i]+"\">"+list[i]+"</A></font><A HREF=\""+list[i]+"\"></A>\n<BR></td>");
    ps.println("<td align=center><a href=\""+list[i]+"/\"><img src=\""+"/images/file.gif"+"\"></img></a>");
    ps.println("</tr>");
    ps.println("</table>");
    ps.println("<P><HR><I><font color=blue>"+(new Date())+"</font></I>");
    ps.println("<I><font color=blue>Copyright to HCL Technology Ltd</font></I>");
    ps.println("<I><font color=blue>Author Vivek Kumar Sinha</font></I>");
    ps.println("</body></html>");
    The ThreadPool class contains a Vector of WorkerThread objects.
    These objects are the individual threads that make up the pool.
    The WorkerThread objects will start at the time of their construction.
    If there are more HTTP requests than there are WorkerThreads,
    the extra requests will backlog until WorkerThreads free up.
    class ThreadPool extends WebServer{
    void createThreadPool(){
    for (int i = 1; i <= workerThreads; ++i) {
    Worker w = new Worker();
    Thread t=new Thread(w, "Worker Thread No."+i);
    t.start();
    /* Uncomment to check the number of worker threads running */
    // printString("Worker Thread No."+i+" Started");
    threads.addElement(w);
    try{
    ServerSocket serversocket = new ServerSocket(port);
    do {
    Socket socket = serversocket.accept();
    Worker w = null;
    synchronized (threads) {
    if (threads.isEmpty()) {
    /* Do nothing */
    } else {
    w = (Worker) threads.elementAt(0);
    threads.removeElementAt(0);
    w.setSocket(socket);
    } while (true);
    } catch (IOException e) {
    e.printStackTrace();

    Thank you for Welcoming me!!! I am very new to this forum so din't have this idea.
    I am unable to add the keep alive behavior . I don't have problem with any part of the code. The problem is i don't know how to make that enhancement in the existing code.
    Regards

Maybe you are looking for

  • Insert / update data to a table through DBLINK (oracle)

    I try to insert / update a table from one instance of oracle database to another one through oracle dblink, get following error: java.sql.SQLException: ORA-01008: not all variables bound ORA-02063: preceding line from MYLINK at oracle.jdbc.dbaccess.D

  • Bought mtn lion need to get it on additional computer

    bought mtn. lion and now i want to install on my laptop...when i go to app store it asks me to purchase again....

  • How long can a form be?

    Is there a limit? How many pages, how many questions? Thanks!

  • Printing to a Dell

    I'm trying to print from mabook pro to dell photo 928 printer via wired connection. Printer setup doesn't show Dell software or drivers. I've heard that Dell printers work with epson drivers. Does anyone know if this is true and if so which Epson dri

  • Hi, am trying to display chinese characters

    hi,..i have problem displaying chinese characters using the reporting tools. i even changed the .jsp to use UTF8 encoding but the jsp doesnt display the correct chinese characters. Anyone can help ?