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



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

View Questions and Answers by Category

Advertisements


 
Have Programming Question? Ask it here!
 
 
 


prashant
Data fetching from JSP or HTML
1 Answer(s)      5 years and 2 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
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
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
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
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   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
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
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
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
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
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
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
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
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
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"/> <
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
Advertisements
 

 

 

DMCA.com