How to use class in JSP page ? In java works in JSP not...

Hello developers,
I need check if URL exists.. i use this code in java.. it works fine..
import java.net.*;
import java.io.*;
public class Check {
public static void main(String s[]) {
    System.out.println(exists("http://www.google.com"));
    System.out.println(exists("http://www.thisURLdoesntexis.com"));
static boolean exists(String URLName){
  try {
    HttpURLConnection.setFollowRedirects(false);
    // note : you may also need
    //        HttpURLConnection.setInstanceFollowRedirects(false)
    HttpURLConnection con =
       (HttpURLConnection) new URL(URLName).openConnection();
    con.setRequestMethod("HEAD");
    return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
  catch (Exception e) {
       e.printStackTrace();
       return false;
}in java all works fine.. it shows
TRUE
FALSE
but i have no idea how can i implement this java code to my check.jsp page..
i tried something like this..
<%@ page import="java.io.*" %>
<%@ page import ="java.net.*" %>
<BODY>
<%
static boolean exists(String URLName){
  try {
    HttpURLConnection.setFollowRedirects(false);
    // note : you may also need
    //        HttpURLConnection.setInstanceFollowRedirects(false)
    HttpURLConnection con =
       (HttpURLConnection) new URL(URLName).openConnection();
    con.setRequestMethod("HEAD");
    return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
  catch (Exception e) {
       e.printStackTrace();
       return false;
String a="http://www.google.com";
%>
<%= exists(a)%>and i want to see in my jsp page the result.. it means that JSP page shows
TRUE
Thanks in advance,

Hi there,
One solution is to use JavaBeans and call the methods for the JavaBean from the JSP page.
Suppose you have a JavaBean called TestConnectionBean as follows:
package test22;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.MalformedURLException;
import java.io.IOException;
  Set the testUrl before checking if connection exists.
public class TestConnectionBean {
    String testUrl;
    boolean connectionExists;
    public TestConnectionBean() {
    public String getTestUrl() {
        return testUrl;
    public void setTestUrl(String testUrl) {
        this.testUrl = testUrl;
    public boolean getConnectionExists() throws IOException, MalformedURLException {
        HttpURLConnection.setFollowRedirects(false);
        // note : you may also need
        //        HttpURLConnection.setInstanceFollowRedirects(false)
        HttpURLConnection con = null;
        con = (HttpURLConnection) new URL(this.testUrl).openConnection();
        con.setRequestMethod("HEAD");
        return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
    public void setConnectionExists(boolean connectionExists) {
        this.connectionExists = connectionExists;
}Then you can create a JSP page like this:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head><title></title></head>
  <body>
  <jsp:useBean id="testConnectionBean" class="test22.TestConnectionBean"/>
  <jsp:setProperty name="testConnectionBean" property="testUrl" value="http://www.google.com" />
  <br/><br/>
  Does the connection exist for http://www.google.com : <jsp:getProperty name="testConnectionBean" property="connectionExists"/>
  <br/><br/>
  <jsp:setProperty name="testConnectionBean" property="testUrl" value="http://www.thisURLdoesntexis.com" />
  <br/><br/>
  <%-- The following will give an exception : java.net.UnknownHostException: www.thisURLdoesntexis.com since the URL doesn't exist. 
  --%>
  <%--
  Does the connection exist for http://www.thisURLdoesntexis.com : <jsp:getProperty name="testConnectionBean" property="connectionExists"/>
  --%>
  </body>
</html>The output you see looks like:
Does the connection exist for http://www.google.com : true
I think it is better to handle the exceptions in the JavaBean itself, so now yyou can change the method signature of getConnectionExists , remove all exceptions from method signature but handle them with a try/catch inside the method itself.

Similar Messages

  • Questions on using classes inside BSP pages

    Hi Group,
    I have a few questions on how to use classes,interfaces,parameters in classes,
    and etc., relating to OOPs concepts that can be implemented in BSPs.
    Pls send me some link wherein I can explore things and use it in BSPs.
    Thanks & Regards,
    Vishnu.

    Hi Raja,
    I am facing issues like this:
    1) When I use the code in my BSP as under:
    <%
    class ZCL_MODEL_03 definition load.
    data ref1 type ref to ZCL_MODEL_03.
    data cust_id type c value "1000".
    data c_id type c.
    create object ref1.
    c_id = cust_id.
    call method ref1->CHECK_CUSTOMER changing cid = cust_id.
    %>
    Cannot we define variables in the Scriptlet?? or we need to do only in the attributes sections only?? or in both??
    2)I am not able to use both exporting & importing things in my method call.
    eg.,call method ref1->GET_CUSTOMER
                      exporting cid = cust_id
                      importing c_id = eid.
    In the method definition, I am only using simply logic like, I was trying to send a value into the "cid" defined in the method and putting that value into "eid" which was defined exporting, but, still I could not get the value into "c_id" that I have defined in the BSP page.
    Note: in both the things(in BSP and class definition as well, I am using the same
            type for defining the attributes.
    3)When can we define a "Returning" option in the Class method's parameter    
       Definition? and how can I use it with an example?
    Thanks in advance.
    Regards,
    Vishnu.

  • Need samples how to use classes in WebDynpro

    Hi,
    I Need To simple Samples how to use classes in WebDynpro.
    Regards

    Continued....
    and in the model
    right click->create model
    select the radio button import java bean .
    next ADD jars option will be seen
    Browse the jar on the dekstop.
    now add this model to the used models by right clicking on it.
    Now if you go to Data Modeler.
    You will find the used model.
    From there map to the component controller->view Controller.
    And continue with ur coding.
    Hope this helps you.
    Thanks & Regards,
    Lokesh.

  • How to see themes on full page of firefox like chrome and not only on the top bar

    <blockquote>Locking duplicate thread.<br>
    Please continue here: [[/questions/876505]]</blockquote>
    how to see themes on full page of firefox like chrome and not only on the top bar

    Personas or Lightweight Themes are the ones that just put a background on the toolbars.
    You can look for the real (original style) themes here:
    : https://addons.mozilla.org/en-US/firefox/themes/
    :and you should be able to easily identify them by their pictures. I would suggest that you pick a theme that is identified under the version information to also run in Firefox 8, so you will be able to continue when you upgrade to 6.0.2 and above.
    I am on 6.0.2 and I would be shown 450 themes.
    Another method is to install a style using the "Stylish" extension, specifically a global style is what you are interested in. There are 3,697 global styles which is one [http://userstyles.org/categories category] of styles. Styles are not programs but you can put up a background picture of your choosing or color areas. But instead of hundreds to choose from you have thousands and they are mostly variations of another style. One advantage of a style is that you can modify a style to suit yourself with little or no programming experience.
    : http://userstyles.org/styles/browse/global

  • How can I close out the page I am working on in safari when error boxes keep popping up?

    How can I close out the page I am working on in safari when error boxes keep popping up?

    What do the error messages say ?

  • How to use .dll compiled in Delphi in Java?

    Can anyone provide me information how to use .dll compiled in Delphi in Java? The .dll Delphi program may be non-OOP program.

    Hi
    If You want to write anything in PASCAL then simply write JNI code in C++ and call functions from this DELPHI DLL, but remember about changing the order of parameters etc when You call it. I had exactly the same problem, but it is possible, and we succeed.
    You will need exact description of input parameters required by PASCAL functions and of output parameters. Then construct in C++ objects wchich looks in memory exacly the same as they will look if You will be using PASCAL. Then PASCAL function will interprete this area in memory as known structure and will run.
    Maciek

  • Can we include a JSP page in an already included JSP Page

    Hi guys,
    I have a doubt with JSP include tag. The problem is ..
    Can we include a JSP page in an already included JSP Page
    AS shown below
    I have one JSP page
    Index.jsp
    -in this I am including "include.jsp"
    -Again within the "include.jsp" I am including "include1.jsp"
    It is neither giving an error nor displaying the content which is there in the "include1.jsp" but it is displaying the content of "include.jsp"
    first of all let me know whether it is possible or no.. If so then why is it not coming and what is required to do this..
    fast...
    Thanks
    Sreenadha Reddy K

    Hi guys,
    I have a doubt with JSP include tag. The
    g. The problem is ..
    Can we include a JSP page in an already included JSP
    Page
    AS shown below
    I have one JSP page
    Index.jsp
    -in this I am including "include.jsp"
    -Again within the "include.jsp" I
    he "include.jsp" I am including "include1.jsp"
    It is neither giving an error nor displaying the
    content which is there in the "include1.jsp" but it is
    displaying the content of "include.jsp"
    first of all let me know whether it is possible or
    no.. If so then why is it not coming and what is
    required to do this..
    fast...
    Thanks
    Sreenadha Reddy KIt is possible , u just have to change all the files and save them all again, clear the temp dirs where all the jsp's as compiled. Now after all this try , it should work .

  • My iphone 4s cannot connect the internet sometimes using the 3G, but sometimes it does work. i do not know what is wrong ?

    my iphone 4s cannot connect the internet sometimes using the 3G, but sometimes it does work. i do not know what is wrong ?

    5.0.2 has not been released, thus you can not upgrade.
    Stedman

  • How to invoke a jsp page from java which does not use Servlets?

    Hello,
    I am working in Documentum. I am trying to invoke a jsp page from another java page which does not use Servlets.
    I tried doing this by just instantiating the java class related to the jsp page from my present java class.In my java class related to the jsp page, I have defined onInit() and onRender() methods.
    Now, I am trying to call the jsp page from my present java class by just instantiating the java class related to the jsp page. This throws a java.lang.NullPointerException.
    Any comments or suggestions on this.Any help would be appreciated.
    Thanks,
    Ranjith M.V

    RanjithM.V wrote:
    Hello,
    Thanks for the reply. One important thing I forgot to mention. I am also using xml component.And?
    As this is the standard way used for coding in Documentum, I do not want to use Beans.Well, JSP's should, in and of themselves, contain no functional code. It should all be only display.
    Without that is it not possible?What did I say? I said,
    masijade wrote:
    It is possible, but I very, very, very, much doubt, that it would be worth the effort.And, if you don't know how, a forum is not truely going to be able to help you implement it (at least not in less than a few years time, at which point it would be outdated).
    >
    Appreciate your understanding and help.
    Thanks,
    Ranjith M.V

  • How to use Classes stored in "Classes" folder in JSP with tomcat ?

    Hello friends
    im using tomcat as server and MySQL as a Backend. now i am using the date calculation in Diff.class files which i have stored in catalina_home/webapps/prj_dev/Prj_files/classes/diff/DIff.class.
    now i am getting error that :
    Generated servlet error:
    Only a type can be imported. diff.Diff resolves to a package
    wht i have to do ?

    I don't include the "classes" word in my import anymore.. Waa.. I'm going nuts.. T.T
    Now, I'm trying to use the class through useBean..
    this is how my application looks like:
    /webapps
    -----/hangman-jsp
    ------------index.jsp
    ------------/WEB-INF
    -------------------web.xml
    -------------------MysteryPhrase.java
    -------------------/classes
    ---------------------------/beans
    ----------------------------------MysteryPhrase.class
    -----------/images
    -------------------hangman.gif
    This is what is in my MysteryPhrase:
    package beans;
    import java.lang.String;
    import java.lang.StringBuffer;
    public class MysteryPhrase {
         private String answer;
         private StringBuffer mysteryPhrase;
         private int guesses;
         private char[] alphabet;
         public MysteryPhrase () {
         this.alphabet = new char[26];
    public void setMysteryPhrase (String mysteryPhrase) {
         this.answer = mysteryPhrase;
         this.mysteryPhrase = new StringBuffer(mysteryPhrase.length());
         for (int i = 0; i < mysteryPhrase.length(); i++) {
              this.mysteryPhrase.setCharAt(i, '_');
    public void setGuess (char guess) {
         for (int i = 0; i < answer.length(); i++) {
              if (answer.charAt(i) == guess) {
                   mysteryPhrase.setCharAt(i, guess);
         guesses++;
    public String getMysteryPhrase () {
         return mysteryPhrase.toString();
    public String getAnswer () {
         return answer;
    public int getGuesses () {
         return guesses;
    This is what is in my index.jsp (It is not yet finished..I just started..)
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <jsp:useBean id="phrase" class="beans.MysteryPhrase"/>
    <jsp:setProperty name="phrase" property="MysteryPhrase" value="Hello!"/>
    <html>
         <head>
              <title>JSP/JSTL Implementation of Hangman</title>
              <style type="text/css">
                   div {
                        color: white;
                        background-color: gray;
                        position: absolute;
                        border-style: solid;
                        border-width: thin;
                        width: 20%;
                        height: 30%;
                        text-align: center;
                   #guessBoard {
                        top: 28%;
                        left: 42%
                   #mysteryPhraseBoard {
                        top: 50%;
                        left: 25%;
                        z-index: 2;
                   #statisticsBoard {
                        top: 57%;
                        left: 58%;
                        z-index: 2;
                   #categoryBoard {
                        top: 23%;
                        left: 10%
                   #hangman {
                        top: 7%;
                        left: 70%;
                   #char {
                        width: 20px;
                   body {
                        background-color: black;
              </style>
         </head>
         <body>
              <div id="categoryBoard">
                   <form method="post">
                        Please choose a category:
                        <select name="category">
                             <option>Category 1</option>
                             <option>Category 2</option>
                             <option>Category 3</option>
                             <option>Category 4</option>
                             <option>Category 5</option>
                             <option>Category 6</option>
                             <option>Category 7</option>
                             <option>Category 8</option>
                        </select>
                        <input type="submit" value="Change"/>
                   </form>
              </div>
              <div id="mysteryPhraseBoard">
                   The mystery phrase is
              </div>
              <div id="guessBoard">
                   <form method="post">
                        Enter a letter: <input id="char" type="text" name="letter"/>
                        or
                        Enter a word: <input type="text" name="word"/>
                        <input type="submit" value="Guess"/>
                   </form>
              </div>
              <div id="statisticsBoard">
                   Guesses: 0
                   Remaining Letters: 8
              </div>
              <div id="hangman">
                   <img src="images/hangman.gif"/>
              </div>
         </body>
    </html>

  • How to use class in JSP file?

    Hello All,
    I am new to Jsp.
    In Jsp file,I used class of myself.
    Why,the Constractor seems not working?
    Thanks in advance.

    Hi,
    You can import the class in a jsp file.
    Use <% page import = "">
    and call that class.
    If u want to import a funtion in your class, then u can insert that into scriplets like <%! ..%>
    Hope u got that!
    Artz

  • How to use .class files from jsp

    hi i want to use .class files in my jsp program can any one help me

    so if you are using pacakges here is normal example...
    say you .java code is something like...
    package com.util;
    public Class BeanUtility{
    }place the .class file at WEB-INF/classes/com/util folder if those folders are missing create it and place the .class file there. or pacakage it as a jar file & put it into WEB-INF/lib folder
    Now in jsp you can either use jsp:Usebean tag or use normal scriplets to create an instance of the nessary class...
    here is an example for you
    <%@ page language="java" import="com.util.BeanUtility" %>
    <%
    BeanUtility bn = new BeanUtility();
    %>however,i'd suggest you to make use of JSTL / Inbuilt tag libraries /MVC 2.0 approach for better maintainance & readablity.
    Hope this might help
    REGARDS,
    RaHuL

  • Using java class and variables declared in java file in jsp

    hi everyone
    i m trying to seperate business logic form web layer. i don't know i am doing in a right way or not.
    i wanted to access my own java class and its variables in jsp.
    for this i created java file like this
    package ris;
    import java.sql.*;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    public class  NewClass{
        public static void main(String args[]){
            Connection con = null;
            ResultSet rs=null;
            Statement smt=null;
            try{
                Class.forName("com.mysql.jdbc.Driver").newInstance();
                con=DriverManager.getConnection("jdbc:mysql:///net","root", "anthony111");
                smt=con.createStatement();
               rs= smt.executeQuery("SELECT * FROM emp");
               while(rs.next()){
                String  str = rs.getString("Name");
                }catch( Exception e){
                    String msg="Exception:"+e.getMessage();
                }finally {
          try {
            if(con != null)
              con.close();
          } catch(SQLException e) {}
    }next i created a jsp where i want to access String str defined in java class above.
    <%--
        Document   : fisrt
        Created on : Jul 25, 2009, 3:00:38 PM
        Author     : REiSHI
    --%>
    <%@page import="ris.NewClass"%>
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
       "http://www.w3.org/TR/html4/loose.dtd">
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title>JSP Page</title>
        </head>
        <body>
            <h1><%=str%></h1>
        </body>
    </html>I wanted to print the name field extracted from database by ResultSet.
    but it gives error cannot find symbol str.
    please help me to find right way to do this.
    i am using netbeans ide.

    Very bad approach
    1) Think if your table contains more than one NAMEs then you will get only the last one with your code.
    2) Your String is declared as local variable in the method.
    3) You have not created any object of NewClass nor called the method in JSP page. Then who will call the method to run sql?
    4) Your NewClass contains main method which will not work in web application, it's not standalone desktop application so remove main.
    Better create an ArrayList and then call the method of NewClass and then store the data into ArrayList and return the ArrayList.
    It should look like
    {code:java}
    package ris;
    import java.sql.*;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    public class  NewClass{
        public static ArrayList getNames(){
            Connection con = null;
            ResultSet rs=null;
            Statement smt=null;
            ArrayList nameList = new ArrayList();
            try{
                Class.forName("com.mysql.jdbc.Driver").newInstance();
                con=DriverManager.getConnection("jdbc:mysql:///net","root", "anthony111");
                smt=con.createStatement();
               rs= smt.executeQuery("SELECT * FROM emp");
               while(rs.next()){
                nameList.add(rs.getString("Name"));
               return nameList;
                }catch( Exception e){
                    String msg="Exception:"+e.getMessage();
                   </code><code class="jive-code jive-java"><font>return nameList;</code><code class="jive-code jive-java">
                }finally {
          try {
            if(con != null)
              con.close();
          } catch(SQLException e) {}
          </code><code>return nameList;</code>
    <code class="jive-code jive-java">    }

  • I used tag to show PDF file inside my JSP page, It is working properly in IE but nothing shows in Mozilla. What should I do?

    I've used to display a PDF file inside my JSP page. It is working fine in IE. However, many of users of this application are using Mozilla and the platform is Ubuntu so it is vital that the file is shown in Mozilla as well. How can I solve this problem.
    == This happened ==
    Every time Firefox opened
    == I run my jsp page

    Such conditional code will only work in IE and not in other browsers like Firefox.
    You can ask questions and advice about web development at the mozillaZine Web Development/Standards Evangelism forum.<br />
    A good place to ask questions and advice about web development is at the mozillaZine Web Development/Standards Evangelism forum.<br />
    The helpers at that forum are more knowledgeable about web development issues.<br />
    You need to register at the mozillaZine forum site in order to post at that forum.<br />
    See http://forums.mozillazine.org/viewforum.php?f=25

  • How to use Class "CL_GUI_CHART_ENGINE" in a abap program ?

    Hi Guys,
    I want to display data in my internal table in the form of a Graph using class "cl_gui_chart_engine".
    I had a look at sample program given by SAP - GRAPHICS_GUI_CE_DEMO but need some help to understand how can we use our own data to be displayed in the graph ? Basically what I am looking for is that where we need to do the changes in creation of XML file so that we can pass our own data ?
    ( perform create_data_demo using l_ixml_data_doc)
    Could you please help me with some sample code or pseudocode ?
    Thanks
    Ashwa

    Thanks Kai,
    I had already done the same thing and got the required output.
    Populate X-Axis ( Categories )
      LOOP AT ITAB.
    Populate Categories
        l_element = p_ixml_doc->create_simple_element(
                  name = 'C' parent = l_categories ).
        l_element->if_ixml_node~set_value( itab-value).
      ENDLOOP.
    Populate Y-Axis ( Values )
      LOOP AT VALUE_TAB.
       l_element = p_ixml_doc->create_simple_element(
                 name = 'S' parent = l_series ).
        l_element->if_ixml_node~set_value( value_tab-value).
      ENDLOOP.
    I am now trying to find the ways to change the default layout of the graph. I guess it should be done in "perform create_custom_demo using l_ixml_custom_doc." . I want that my graph should be displayed as lines instead of bar's.
    Once I achieve this I will share my findings along with sample code with the community.
    I wish I could get some documentation on class "cl_gui_chart_engine" and interfaces like "if_ixml_document".
    Thanks
    Ashwani

Maybe you are looking for

  • IPad version:how can I search a word on modules?

    Hi to everybody! How can I search a word in modules? I understand that I can do a search in spreadsheet, but I need to do in a module that is more efficient...so do you know? And why when I write on module I can't press enter and begin to write a new

  • RequestTimeout error while attempting to connect to the Crystal Server

    Hi Guys, We use Crystal Server 2008, along with an automated java tool that updates the JNDI name for the database. Both the java tool and the Crystal Server reside on the same box, and communicate via TCP/IP. Recently, we had some space added to the

  • Acrobat 7.0 activation problem

    I had to reinstall a copy of Acrobat 7.0 Standard.  Whenever I try to activate, I get a message that I must be a system administrator and that I should log out and log back in as system admin.  But I am logged in as system administrator.  I can't get

  • SCSI HD and OS9

    I installed X, but not 9, on my new HD. Now it won't recognize my external SCSI HD. The external SCSI HD worked w/my old HD, which had 9 AND X. Must I do a clean install of 9, then X? Or? A clean install of 9 and X is much work, w/saving files to a Z

  • [Solved] Silent LUKS boot

    [Synopsis] Create a hook as shown below to silence the kernel. I'd like to have a truly silent boot as in the Wiki but it only seems to address the login prompt. I would also like to get rid of the (USB) boot messages pollution of the the LUKS passwo