Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Answers Viewqa JSP-Servlet Data fetching from JSP or HTML

Have Programming Question? Ask it here!
 
 
 


prashant
Data fetching from JSP or HTML
1 Answer(s)      4 years and 8 months ago
Posted in : JSP-Servlet



Advertisement
View Answers

May 21, 2013 at 11:43 PM


 hello viewers this data entry and data fetching through mvc model
// START Servlet ( NAME: myservlet )

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hello.apps.servlets;

import com.google.gson.JsonArray;
import com.hello.apps.beans.classfiles;
import com.hello.apps.dao.mydao;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.PreparedStatement;
import java.io.PrintWriter;


public class myservlet extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /*
             * TODO output your page here. You may use following sample code.
             */
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet myservlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet myservlet at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out=response.getWriter();
      response.setContentType("html/json");
      String action=request.getParameter("act");
      if("retrieve".equalsIgnoreCase(action))
      {
            try {
                JsonArray ob=new mydao().renderdata();
                out.print(ob);
            } catch (SQLException ex) {
                Logger.getLogger(myservlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(myservlet.class.getName()).log(Level.SEVERE, null, ex);
            }
      }
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            classfiles obj = new classfiles();;
            obj.setName(request.getParameter("name"));
            obj.setAge(request.getParameter("age"));

            String gen = request.getParameter("gender");

            if (gen.equals("m")) {
                obj.setGender("Male");
            } else {
                obj.setGender("Female");
            }

            String gam = request.getParameter("game");
            if (gam.equals("1")) {
                obj.setGame("Cricket");
            } else if (gam.equals("2")) {
                obj.setGame("Carrom");
            } else {
                obj.setGame("Chess");
            }
             try {
                new mydao().insertfunction(obj);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(myservlet.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SQLException ex) {
                Logger.getLogger(myservlet.class.getName()).log(Level.SEVERE, null, ex);
            }

            out.print("sucess");
        } finally {
            out.close();
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}


//START DAO ( NAME: mydao )

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hello.apps.dao;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.hello.apps.beans.classfiles;
import com.hello.apps.utils.ConnectionManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;


public class mydao {

    Connection con = null;
    PreparedStatement ps;
    public String query;

    public boolean insertfunction(classfiles ob) throws ClassNotFoundException, SQLException {
        try {
            Connection con = (Connection) new ConnectionManager().creatConnection();
            query = "insert into login (name,age,gender,game) values(?,?,?,?)";
            java.sql.PreparedStatement ps = con.prepareStatement(query);
            ps.setString(1, ob.getName());
            ps.setString(2, ob.getAge());

            ps.setString(3, ob.getGender());
            ps.setString(4, ob.getGame());
            ps.executeUpdate();
            return true;
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
            return false;
        } catch (SQLException ex) {
            ex.printStackTrace();
            return false;
        }
    }

    public JsonArray renderdata() throws SQLException, ClassNotFoundException {
        JsonArray array = new JsonArray();

        Connection con = (Connection) new ConnectionManager().creatConnection();
        try {
            query = "select * from login";
            PreparedStatement ps = (PreparedStatement) con.prepareStatement(query);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                JsonObject ob = new JsonObject();
                ob.addProperty("name", rs.getString("name"));
                ob.addProperty("age", rs.getString("age"));
                ob.addProperty("gender", rs.getString("gender"));
                ob.addProperty("game", rs.getString("game"));
                array.add(ob);
            }
            return array;
        }   catch (SQLException ex) {
            Logger.getLogger(mydao.class.getName()).log(Level.SEVERE, null, ex);
            return array;
        } finally {
            con.close();
        }

    }
}

// START BEANS(NAME: classfiles)

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hello.apps.beans;


public class classfiles {
    private String name;
    private String age;
    private String gender;
    private String game;

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getGame() {
        return game;
    }

    public void setGame(String game) {
        this.game = game;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

//START CONNECTION(ConnectionManager)

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.hello.apps.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 *
 * @author 
 */
public class ConnectionManager {
    Connection con=null;
    public Connection creatConnection() throws ClassNotFoundException, SQLException
    {
        Class.forName("com.mysql.jdbc.Driver");
        con=DriverManager.getConnection("jdbc:mysql://localhost:3306/exit","root","root");
        return con;
    }


}

//START JSP PAGE 

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <form action="myservlet" method="post">
            Name:<input type="text" id="name" name="name">
            <br>
            <br>
            <br>
            <br>

            Age:<input type="text" id="age" name="age">
            <br>
            <br>
            <br>
            <br>
            Gender:<input type="radio" id="gen" name="gender" value="m">Male 

            <input type="radio" id="gen" name="gender" value="f">Female

            <br><br><br><br>

            Game:<select name="game">

                <option value="1">Cricket</option>
                <option value="2">Chess</option>
                <option vlaue="3">Carrom</option>
            </select>

            <br><br><br><br>
            <button type="submit" name="submit" value="submit" >Sign in</button>
            <button  type="reset"  name="reset" value="reset">Reset</button>                              
        </form>

    </body>
</html>

//START JSP PAGE 

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <script src="jquery-1.9.1.min.js"></script>  
        <script>
            $(document).ready(function()
        {
            getdetails();
        });
        </script>
    </head>

    <body>

        <script>
            function getdetails()
            {
                $.getJSON("myservlet",{act:"retrieve"}, function(data){
                    var name,age,game,gender;
                    var string="";
                    $('#output').empty();
                    for(var i=0;i<data.length;i++)
                        {
                            name=data[i].name;
                            age=data[i].age;
                            game=data[i].game;
                            gender=data[i].gender;

                             string=""+"<tr>"+"<td>"+name+"</td>"+"<td>"+age+"</td>"+"<td>"+gender+"</td>"+"<td>"+game+"</td>"+"</tr>";

                            $("#newbody").append(string);   

                        }

                });
            }
        </script>

        <div>
            <table>
                <thead>
                    <tr>
                <th>Name</th>
                <th>Age</th>
                <th>Gender</th>
                <th>Game</th>
                    </tr>
                </thead>
                <tbody id="newbody">

                </tbody>
            </table>

        </div>
    </body>
</html>


Related Tutorials/Questions & Answers:
Data fetching from JSP or HTML - JSP-Servlet
Data fetching from JSP or HTML  Hi Deepak, Can u pls help me as i have a problem with jsp/html frameset. my question is how can i fetch the data from frameset which is in html format.pls help me. Thanks
Fetching the exact data from file using java
Fetching the exact data from file using java  **hi ... i am having one .lst file.. that file consists of instructions and opcodes.. now i want to fetch only the opcode from that file.. could u pls anyone guide me this using java
Advertisements
fetching data from cosole - Development process
fetching data from cosole  Hi Deepak, i hv parsed... that console data into the database? how can i parse that console data and save... into data(name,address) values('"+arr[0]+"','"+arr[1]+"')"); } catch (Exception e
autocompletion in textfield fetching from database in jsp
autocompletion in textfield fetching from database in jsp  hi i want to retrieve country name from mysql db to textfield.. maeans if anyone type... i caant able to select particular name to textfield... it should be in jsp
Fetching database field from servlet to jsp page ?
Fetching database field from servlet to jsp page ?  Hello Java... field. I wanted to pass some of the database field from servlet to jsp... (i...) field to jsp page . { where 'rs' is Resultset object} please help
how to create a bar chart in jsp by fetching value from oracle databse?
how to create a bar chart in jsp by fetching value from oracle databse?  i want to show the population of various states in a bar chart in my jsp page by fetching the data from my oracle table. i am using my eclipse as my IDE
Fetching image from database
Fetching image from database  I have uploaded image path and image name in database so, now how can i display that image using JSP or HTML page(is it possible to display using tag using concatination). image path i have stored
iphone storing and fetching data
iphone storing and fetching data  How to store and fetch data in an iphone application
fetching data using servlets - SQL
for fetching data from a ORACLE10g database using SERVLETS.   Hi Friend...fetching data using servlets  I have successfully made connection with the oracle10g database that i am using and also able to put in data using JSP
extract data from HTML
extract data from HTML  how to write the coding for to extract data from html tags like(h3,p) and then extracted data should be stored in data base? can anybody tell me how to write the coding
Fetching data from excel file on other website and display in interactive graph form
Fetching data from excel file on other website and display in interactive graph form  Hello, I am making a website using HTML and CSS, I am done... pull data data from those and generate graphs out of it? I really need it urgently
JSP Get Data Into Dropdown list From Database
JSP Get Data Into Dropdown list From Database In this section we will discuss... fetching of data into the dropdown list in JSP using Eclipse IDE and the Tomcat 7... data from the database and set it into the dropdown list in JSP using MySQL
retriving data from sql server using jsp code and placing them in text fields of html code
retriving data from sql server using jsp code and placing them in text fields of html code  Hi, my question is how to retrieve data from sql server 2008 using a jsp file and place the values in the text fields of a html file
SEARCHING THE DATA FROM DATABASE AND DISPLAY THE SEARCHED DATA IN HTML PAGE
SEARCHING THE DATA FROM DATABASE AND DISPLAY THE SEARCHED DATA IN HTML PAGE  pls help me....in this i want to search books from the database... the user specified $data = mysql_query("SELECT * FROM book WHERE upper($field
Link from html to jsp - Development process
Friend, To give link from html page to jsp, you have to run the jsp page.After...Link from html to jsp   Hi, Can u send me code. when i click html link button , control should go to jsp page wat i mentioned in view
how to insert data in database using html+jsp
how to insert data in database using html+jsp  anyone know what... = null; // declare a resultset that uses as a table for output data from... = 0; // sql query to retrieve values from the specified
How to export data from html file to excel sheet by using java
How to export data from html file to excel sheet by using java   reading the data from Html file
How to export data from html to excel sheet by using java
How to export data from html to excel sheet by using java   How to export data from html to excel sheet by using java
display data from a table in Access Database in a HTML page
display data from a table in Access Database in a HTML page  how to display data from a table in Access Database in a HTML page in a Java Program
How to export data from html file to excel sheet by using java
How to export data from html file to excel sheet by using java    How to export data from html file to excel sheet by using java
retrive data from oracle to jsp
retrive data from oracle to jsp  i am a beginer in jsp so please help... cost and manager name and storing it in the data base. in search proj fiel...(); psmt= conn.prepareStatement("select * from CR_EMPLOYEE_DETAILS
read excel data from jsp - JSP-Servlet
read excel data from jsp  Hi how to read excel file from jsp? Excel file is created manually entered data having many sheets? and read the entire sheet and also edit with jsp? pls suggest me?   Hi Friend, 1
data are not display in JSP from database - JSP-Servlet
data are not display in JSP from database   i want to finding some data through a SQL query from SQL server database to a JSP page based on some... of this jsp page. like.. School Result and three request parameters 'class', 'from
JSP to add details to a database from a HTML form.
JSP to add details to a database from a HTML form.  Hi I'm a second year CS student who has to use JSP to validate a HTML form and add the details..... Can anyone tell me what is wrong with my code? html code first
how to display data from database in jsp
how to display data from database in jsp  how to display data from database in jsp
How to pass parametes from JSP page to HTML page? - JSP-Servlet
How to pass parametes from JSP page to HTML page?  Hi all, In my project I have one JSP page and one HTML page. In JSP page I have created HTML... to pass the values from my JSP page to HTML page. Pls help me out. Hitendra 
how to refresh google map using ajax by fetching lat long from database
how to refresh google map using ajax by fetching lat long from database  i have a jsp page where we select the object and by submitting the form the route travelled by it will be displayed on the google map by fetching the lat
Display Data from Database in JSP
, to show data from the database click on the link that calls another .jsp file named... this jsp page and show all data from the table. Click on the <--back...; <html> <head> <title>display data from
displaying data retrieved from a database in a jsp page
displaying data retrieved from a database in a jsp page  the page... ServletException, IOException { response.setContentType("text/html;charset=UTF-8...("PageTitle"); try { response.setContentType("text/html;charset=UTF-8
Restricting the user from filling the data in a textfield using html
Restricting the user from filling the data in a textfield using html  I got a requirement like this, If the user is trying to fill a text field, i have to restrict him
Calling In JavaScript Functions from HTML Form To Validate User Entered Data
Calling In JavaScript Functions from HTML Form To Validate User Entered... and editing my html to call my functions to validate the user entered data...; <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <
How to Retrieve data from database in jsp
How to Retrieve data from database in jsp In this section we will discuss about how to fetch data from database table. We will give a simple example which will demonstrate you about fetching data from database table. Example We
jsp programe for displaying data from database
jsp programe for displaying data from database  i am using JSP.i want.../WebSevices/19592-retriving-data-from-sql-server-using-jsp-code-and-placing-them..."')"); ResultSet rs = stmt.executeQuery( "SELECT * FROM data"); String id
jsp programe for displaying data from database
jsp programe for displaying data from database  i am using JSP.i want.../WebSevices/19592-retriving-data-from-sql-server-using-jsp-code-and-placing-them..."')"); ResultSet rs = stmt.executeQuery( "SELECT * FROM data"); String id
jsp programe for displaying data from database
jsp programe for displaying data from database  i am using JSP.i want.../WebSevices/19592-retriving-data-from-sql-server-using-jsp-code-and-placing-them..."')"); ResultSet rs = stmt.executeQuery( "SELECT * FROM data"); String id
retrive data from database using jsp in struts?
retrive data from database using jsp in struts?   *search.jsp* <%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%> <... searchProduct(SearchDTO sdto) { String query="select * from product
Exporting data from mysql into csv using jsp
Exporting data from mysql into csv using jsp  Hi friends.... I want to export the data from mysql to csv file using... i am having 30 columns in my database.. Eg- text1,text2,text3,....,upto text30... i want to export this data
JSP Get Data From Database
JSP Get Data From Database In this section we will discuss about how to get data from database using JSP. To get data from database to a JSP page we... example which lets you understand to fetch data from database in JSP
how to display data from jsp file into database
how to display data from jsp file into database  this is a jsp file...(); in the below example. the error is "cannot convert from java.sql.Statement..." contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@page
How to read and display data from a .properties file from a jsp page
How to read and display data from a .properties file from a jsp page ... the data from this .properties file and display it in table format. Ex:by using... = DEDCHGG_PWDP and goes on... I have to create a jsp page to show these data
Retrieve data from databse using where in JSP
Retrieve data from databse using where in JSP  Hi, can somebody help me? I have a jsp page. in that i want to get data from the database where...=request.getParameter("username"); String sql; sql="SELECT * FROM register WHERE
retrieving of data from one jsp to another jsp - JSP-Servlet
retrieving of data from one jsp to another jsp  using jsp i m displaying a table ,in table i m displaying a radio button then values like id,name etc... that is used for different jsp please help me sir... thanks in advance   Hi
Retrieving data from data base using jsp combo box
Retrieving data from data base using jsp combo box  Hi guys please help me , i have on GUI page int that Server type(like apache,jboss,weblogic) one... of the server it has to display the process name from database into the process name
how to get data from database into dropdownlist in jsp
tutorial go through the link JSP Get Data Into Dropdown list From Database   ...how to get data from database into dropdownlist in jsp  Can anybody tell me what is the problem in this code as i am not able to fetch the data from
How to retrieve array values from html form to jsp?
How to retrieve array values from html form to jsp?  Hi! I am... it into jsp. Means i just want to retrieve values from html form containing array... sample code for how to retrive array values from html to jsp.   hi friend
data fecth from data base in( sql 2000) htmlform and jsp
data fecth from data base in( sql 2000) htmlform and jsp  hi iam using jsp and html form data fecth from database display the textbox help me i want whenever select from dropdown list select the projectname to display
data retrival from database throw simple jsp..
data retrival from database throw simple jsp..  We can retrieve the the data from data base simple jsp page: Jsp Page:retrive.jsp <...; Statement stmt = null; String Query="SELECT * FROM STUD"; try
How to send the data selected from drop down menu from html page to sql 2005 database.
How to send the data selected from drop down menu from html page to sql 2005... by user from html drop down menu such as check-in date for hotel reservation system ,how can I save these data in database and how to retrieve later .Thanks
How to show data from database in textbox in jsp
How to show data from database in textbox in jsp   How to show data from database in textbox in jsp   Here is an example that retrieve the particular record from the database and display it in textbox using JSP. <
how to save html form data into .csv file using only jsp.
how to save html form data into .csv file using only jsp.  Dear all, I am developing a website only using jsp and html. i need to save the form data into a .csv file using jsp. can anyone give me any sample solution or tutorial
 

 

 

DMCA.com