• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

insert and update data in jsp using mvc model

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
============================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>
}


===================================================END SERVLET================================================================================

























============================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();
}

}
}



===================================================END DAO================================================================================




















===================================================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;
}

}








===================================================END BEANS================================================================================








===================================================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;
}


}







===================================================END CONNECTION================================================================================
















=================================================== START JSP PAGE INPUT================================================================================


<%@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">









Age:<input type="text" id="age" name="age">








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

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







Game:<select name="game">

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






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

</body>
</html>






=================================================== END JSP PAGE INPUT================================================================================









=================================================== START JSP PAGE OUTPUT================================================================================



<%@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>











===================================================END JSP PAGE OUTPUT================================================================================














































 
Bartender
Posts: 2270
20
Android Java ME Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Could you please paste your code inside code tags, its completely unreadable
 
Sheriff
Posts: 67746
173
Mac Mac OS X IntelliJ IDE jQuery TypeScript Java iOS
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
So what's the question?
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic