jQuery Interacting with Java Servlet using JSON [GSON]


Users.java
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.cloud.model;

/**
 *
 * @author rampukar
 */
import java.util.*;

public class Users {
    private int userId;
    private String username;
    private String userpass;
    private int createdBy;
    private Date createdOn;

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getUserpass() {
        return userpass;
    }

    public void setUserpass(String userpass) {
        this.userpass = userpass;
    }

    public int getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(int createdBy) {
        this.createdBy = createdBy;
    }

    public Date getCreatedOn() {
        return createdOn;
    }

    public void setCreatedOn(Date createdOn) {
        this.createdOn = createdOn;
    }
   
}

UsersDao.java

import java.sql.*;
import com.cloud.db.*;
import java.util.List;
import com.cloud.model.*;
import java.util.ArrayList;

public class UsersDao {

    public Connection con;

    public UsersDao() {
        con = DbCon.getCon();
    }

    public List<Users> getAll() {
        List<Users> list = new ArrayList<Users>();
        try {
            PreparedStatement stmt = con.prepareStatement("select * from users");
            ResultSet Rs = stmt.executeQuery();
            while (Rs.next()) {
                Users user = new Users();
                user.setUserId(Rs.getInt(1));
                user.setUsername(Rs.getString(2));
                user.setUserpass(Rs.getString(3));
                list.add(user);
            }
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return list;
    }
}


MyJSON.java
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.backend.controller;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.cloud.dao.*;
import com.cloud.model.Users;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Pukar
 */
@WebServlet(name = "MyJSON", urlPatterns = {"/MyJSON"})
public class MyJSON extends HttpServlet {

    UsersDao dao;

    public MyJSON() {
        dao = new UsersDao();
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
//        PrintWriter out = response.getWriter();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            List<Users> user = new ArrayList<Users>();
            user = dao.getAll();
            String json = new Gson().toJson(user);
            response.setContentType("application/json");
            response.getWriter().write(json);
        } finally {
            out.close();
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
//        processRequest(request, response);

    }
}

jsonpage.jsp
<%-- 
    Document   : jsonpage
    Created on : May 1, 2016, 2:54:18 PM
    Author     : Pukar
--%>

<%@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="http://localhost:8084/EventMGT/assets/js/jquery-1.12.2.js" type="text/javascript"></script>
        <style type="text/css">
            *{
                font-size: 13px;
                font-family: arial;
            }
        </style>
    </head>
    <table border="1">
        <thead>
            <tr>
                <th>ID</th>
                <th>Username</th>
                <th>Userpass</th>
                <th>CreateBy</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
    <body>
        <script>
            $.get('MyJSON',function(resp){
                var table = '',len=resp.length;
                for(i=0;i<len;i++){
                    table+='<tr>';
                    table+='<td>'+resp[i].userId+'</td>';
                    table+='<td>'+resp[i].username+'</td>';
                    table+='<td>'+resp[i].userpass+'</td>';
                    table+='<td>'+resp[i].createdBy+'</td>';
                    table+='</tr>';
                }
                $('table').append(table);
            });
        </script>
    </body>
</html>

Output:



Share on Google Plus

About Ram Pukar

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment

0 comments:

Post a Comment