how to pass the javascript array to servlet - java

i have requirement i.e., i need to pass array of javascript to servlet. please guide me thanks
qwe.js
<script type="text/javascript">
var array2 = [];
function getTotalTests() {
console.log("called");
console.log("called"+array1.length);
for (i=0; i < array1.length; i++) {
array2[i] = array1[i];
console.log(array2[i]);
}
};
</script>
i need pass array2 to servlet

You will need to make a request of some sort to achieve this. If you do not wish to make a complete request, you can look at https://api.jquery.com/jQuery.ajax/ to make an asynchronous request and display the changes made(if required).

JSP page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
function func()
{
var arr=[2,3,3];
var form = $('<form action="Test" method="get">' +
'<input type="hidden" name="id" value="'+arr+'">' +
'</form>');
alert( $(form));
$(form).submit();
}
</script>
<body>
<button onclick="func()">Deepak</button>
</body>
</html>
Servlet
package test;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Test
*/
#WebServlet("/Test")
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public Test() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println(request.getParameter("id"));
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}

you can pass by using ajax
$.ajax({
type: "POST",
url: "servletname", //Your full URL goes here
data: {
dataname: datavalue
},
success: function (data, textStatus, jqXHR) {
},
error: function (jqXHR) {
}
});

Related

Match sql date to fullcalendar for displaying

I'm very new to FullCalendar and I seriously don't know how to adapt it according to my project requirements. Chose it because my Lecturer wants me to. I am aware that fullcalendar is drag and drop function. What i'm trying to do is have an add button for each cell in my fullcalendar page then when I click add it will go to another jsp page (Add Events). Then I have date inputs (java.sql.Date) so this dates must match to full calendar date.I'm So sure that it's some logic here in index.jsp that needs to be done like if and else statement. If mysql date match to fullcalendar date,you display in that cell. Now what it's doing is print out date in every cell from database.And I just need to display the Title. Refer to the pictures attached :)
RetrieveServlet: Retrieve from AddEventsServlet (for adding events)
ackage servlet;
import java.io.IOException;
import java.util.ArrayList;
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 javax.servlet.http.HttpSession;
import database.DBAO;
import model.AddEvents;
/**
* Servlet implementation class RetrieveServlet
*/
#WebServlet("/RetrieveServlet")
public class RetrieveServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public RetrieveServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
doPost(request,response); //dispatcher sents deget request, since ur code is in dopost, u will need to all it.
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try
{
DBAO myDatabase = new DBAO();
ArrayList <AddEvents> myEventList = myDatabase.getAddEvents();
System.out.println(myEventList.size());
request.setAttribute("EventList",myEventList);
request.getRequestDispatcher("index.jsp").forward(request, response);
}catch(Exception ex)
{
System.out.println("Error Accessing Database:" +ex.getMessage());
}
}
}
AddEventsServlet:
package servlet;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.ListIterator;
import javax.servlet.RequestDispatcher;
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 javax.servlet.http.HttpSession;
import database.DBAO;
import model.AddEvents;
/**
* Servlet implementation class AddEventsServlet
*/
#WebServlet("/AddEventsServlet")
public class AddEventsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public AddEventsServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//doGet(request, response);
AddEvents myEvent = new AddEvents();
//create an object based on the Java class customers
//DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
//Assignment of data
myEvent.setTitle(request.getParameter("Title"));
myEvent.setEventDesc(request.getParameter("EventDesc"));
myEvent.setStartTime(request.getParameter("StartTime"));
myEvent.setEndTime(request.getParameter("EndTime"));
myEvent.setBudget(Double.valueOf(request.getParameter("Budget")));
myEvent.setStartDate(java.sql.Date.valueOf(request.getParameter("StartDate")));
myEvent.setEndDate(java.sql.Date.valueOf(request.getParameter("EndDate")));
myEvent.setEnvironment(request.getParameter("Environment"));
System.out.println(request.getParameter("Title"));
System.out.println(request.getParameter("EventDesc"));
System.out.println(request.getParameter("StartTime"));
System.out.println(request.getParameter("EndTime"));
System.out.println(request.getParameter("Budget"));
System.out.println(request.getParameter("StartDate"));
System.out.println(request.getParameter("EndDate"));
System.out.println(request.getParameter("Environment"));
System.out.println("Title="+myEvent.getTitle());
System.out.println("EventDesc="+myEvent.getEventDesc());
System.out.println("StartTime="+myEvent.getStartTime());
System.out.println("EndTime="+myEvent.getEndTime());
System.out.println("Budget="+myEvent.getBudget());
System.out.println("StartDate="+myEvent.getStartDate());
System.out.println("EndDate="+myEvent.getEndDate());
System.out.println("Environment="+myEvent.getEnvironment());
try
{
DBAO myDatabase = new DBAO();
ArrayList <AddEvents> myEventList = myDatabase.getAddEvents(); //not needed
//AddEvents myEventDetails =myDatabase.isEvent(myEvent,title, eventDesc, StartTime, EndTime, Budget); //not needed
HttpSession myRequest = request.getSession(true); //not needed
request.setAttribute("EventList",myEventList); //not needed
System.out.println(myEventList.size()); //not needed
// you comment out the method that insert data to database
myDatabase.AddEvents(myEvent);
// the dispatcher can go to RetrieveServlet and let it handle the retrieve
//myDatabase.delete(myEvent,title,eventDesc,StartTime,EndTime,Budget,StartDate,EndDate);
//name of delete database
request.getRequestDispatcher("index.jsp").forward(request, response);
}catch(Exception ex)
{
System.out.println("Error Accessing Database:" +ex);
}
}
}
index.jsp: Displaying the full calendar
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%#page import="model.AddEvents,java.util.ArrayList,java.util.ListIterator" %>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src= "https://code.jquery.com/jquery-3.2.1.min.js">
$(document).ready(function() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var events_array = [
{
title: 'Test1',
start: new Date(2012, 8, 20),
tip: 'Personal tip 1'},
{
title: 'Test2',
start: new Date(2012, 8, 21),
tip: 'Personal tip 2'}
];
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
dayClick: function(date, jsEvent, view) {
alert('Clicked on: ' + date.format());
alert('Coordinates: ' + jsEvent.pageX + ',' + jsEvent.pageY);
alert('Current view: ' + view.name);
// change the day's background color just for fun
$(this).css('background-color', 'red');
},
selectable: true,
events: events_array,
eventRender: function(event, element) {
element.attr('title', event.tip);
}},
$('#datepicker').datepicker({
inline: true,
onSelect: function(dateText, inst) {
var d = new Date(dateText);
$('#fullcalendar').fullCalendar('gotoDate', d);
}
}));
function changeDate() {
var StartDate = $('#datepicker').val();
$('#calendar').fullCalendar('gotoDate', startDate);
}
});
</script>
<title>Calendar</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" type="text/css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.6.1/fullcalendar.min.css" type="text/css" rel="stylesheet" />
</head>
<body>
<a class= "add_event_label" href="https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_textarea"></a>
<div class="container">
<div class="row">
<div class="col-xs-12">
<h1>Calendar</h1>
<div id="bootstrapModalFullCalendar"></div>
</div>
</div>
</div>
<!-- this is the pop up window when you press the button -->
<div id="fullCalModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span> <span class="sr-only">close</span></button>
<h4 id="modalTitle" class="modal-title"></h4>
</div>
<div id="modalBody" class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<a class="btn btn-primary" id="eventUrl" target="_blank">Event Page</a>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.6.1/fullcalendar.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script>
$(document).ready(function() {
$('#bootstrapModalFullCalendar').fullCalendar({
header: {
left: '',
center: 'prev title next',
right: ''
},
//action after calendar loaded
eventAfterAllRender: function(view){
if(view.name == 'month')
{
//loop all .fc-day elements
$('.fc-day').each(function(){
//jQuery styling
$(this).css({ 'font-weight': 'bold', 'font-size': '100%'});
$(this).css('position','relative');
//add elements to each .fc-day, you can modify the content in append() with your own html button code
$(this).append('<a class="add_event_label" onclick="changeDate()" href ="AddEvent.jsp" style="position:absolute;bottom:0;left:0;right:0;display:block;font-size:12px;color:blue;cursor:pointer;">(+)</a>' );
<%!ArrayList<AddEvents> myEventList; //have to declear in a declaration tag for access in the page %>
<% myEventList = (ArrayList<AddEvents>) request.getAttribute("EventList");
if(myEventList.size() == 0)
{
%>
<h2>No events</h2>
<%
}
else
{
%>
<%
ListIterator<AddEvents> li = myEventList.listIterator();
while(li.hasNext())
{
AddEvents myEvent = new AddEvents();
myEvent= (AddEvents)li.next();
%>
//This part it should add data according to date, now it's just adding all the data of title.
$(this).append('<p><font size="1">Title:</font></p><p><font size="1"><%= myEvent.getTitle() %></font></p></p>');
<%}
%>
<%
}
%>
});
}
},
eventClick: function(event, jsEvent, view) {
//$(".fc-day-number").prepend("(+) ");
$('#modalTitle').html(event.title);
$('#modalBody').html(event.description);
$('#eventUrl').attr('href',event.url);
$('#fullCalModal').modal();
return false;
}
})
})
</script>
</body>
</html>

Ajax call to servlet, get parameter

I'm calling my Java Servlet with an AJAX call, but I'm not able to read the input parameter from the request. I've tried two ways but with no luck:
var id;
$("#scan").click(function() {
id = 1;
$.ajax({
type: "POST",
data: id,
url: "http://10.1.42.249:8080/test-notifier-web/RestLayer"
});
});
And:
id = 1;
$.post('http://10.1.42.249:8080/test-notifier-web/RestLayer', {
reqValue: id
}, function(responseText) {
// $('#welcometext').text(responseText);
alert("OK!!!");
});
My servlet code is a simple log print of the request parameter, but the return value is always null:
String reqID = "";
log.info("Servlet called");
reqID = request.getParameter("reqValue");
log.info("reqID = " + reqID);
How can I get this working?
The only way I've found to get the code working is manually add the parameter to servlet url, like http://10.1.42.249:8080/test-notifier-web/RestLayer?reqValue=1
i have check you code.this is my working code.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
var id;
function fun() {
alert("aaaa");
id = 1;
$.ajax({
type : "POST",
data : {
reqValue : id
},
url : "/WebProject/callAjax"
});
}
</script>
</head>
<body>
<button id="scan" onclick="fun()">Sacn</button>
</body>
</html>
//Servlet
#WebServlet(urlPatterns = {"/callAjax",})
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(request.getParameter("reqValue"));
}
}
var id;
$("#scan").click(function() {
id = 1;
$.ajax({
type: "POST",
data: { reqValue : id},
url: "http://10.1.42.249:8080/test-notifier-web/RestLayer"
});
});
There are different methods you need to override in servlet. Those are doPost(), doGet(), service() and etc.
I suspect you are using doGet() method that's why when you add parameter to the URL your java code is working and in other two cases as you are using type : "POST" java code is unable to read the data from Request Body( in post method the data will be added to Request Body).
I suggest you to use doPost() or service() methods instead doGet().

How to send data to servlet using ajax without a submitting form

I am new with servlet, I am able to get data from the servlet but not able to send data to it and I want to do this without using a submitting form, can i get some help please
on the click of the button it will go to the servlet and return the text but not the value send to it
This is my index.jsp
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 4112686</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$('#somebutton').click(function() {
$.get('GetUserServlet', function(responseText) {
$('#somediv').text(responseText);
});
});
});
$("#somebutton").click(function(){
$.ajax
(
{
url:'GetUserServlet',
data:{name:'abc'},
type:'get',
cache:false,
success:function(data){alert(data);},
error:function(){alert('error');}
}
);
}
);
</script>
</head>
<body>
<button id="somebutton" onclick="showHint('GetUserServlet.java', 'travis');">press here</button>
<div id="somediv"></div>
</body>
this my servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String text = "Update Sucessful";
String name = request.getParameter("name");
response.setContentType("text/plain"); // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
response.getWriter().write( name + text); // Write response body.
you could either use $.ajax() or $.post here. since you have used $.ajax(). please refer below correction:
<!DOCTYPE html>
<html lang="en">
<head>
<title>SO question 4112686</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$('#somebutton').click(function() {
$.get('GetUserServlet', function(responseText) {
$('#somediv').text(responseText);
});
});
});
$("#somebutton").click(function(){
$.ajax({
url:'GetUserServlet',
data:{name:'abc'},
type:'get',
cache:false,
success:function(data){
alert(data);
$('#somediv').text(responseText);
},
error:function(){
alert('error');
}
}
);
}
);
</script>
</head>
<body>
<button id="somebutton">press here</button>
<div id="somediv"> </div>
</body>
and your servlet should be:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetUserServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String text = "Update successfull"; //message you will recieve
String name = request.getParameter("name");
PrintWriter out = response.getWriter();
out.println(name + " " + text);
}
You may use $.post method for this purpose.
Here is my solution
index.jsp
<!DOCTYPE html><html lang="en">
<head>
<title>SO question 4112686</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$("#somebutton").click(function() {
servletCall();
});
});
function servletCall() {
$.post(
"GetUserServlet",
{name : "Message from jsp"}, //meaasge you want to send
function(result) {
$('#somediv').html('Here is your result : <strong>' + result + '</strong>'); //message you want to show
});
};
</script>
</head>
<body>
<button id="somebutton">press here</button>
<div id="somediv"></div>
</body>
</html>
GetUserServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetUserServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String text = "<br>Message from servlet<br>"; //message you will recieve
String name = request.getParameter("name");
PrintWriter out = response.getWriter();
out.println(text + name);
}
}

Cannot set property 'innerHTML' of null. Issue with AJAX (java)

So I want to learn AJAX and I wanted to make identical app like the one in here
and I pretty much copied it but it doesn't work. I don't know why, I was trying to solve it on my own but can't find any solution.
My .js file is :
function ajaxAsyncRequest(reqURL) {
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", reqURL, true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
// How to get message
alert('It\'s K');
document.getElementById("message").innerHTML = xmlhttp.responseText;
alert(xmlhttp.responseText);
} else {
alert('Something is wrong !');
}
}
};
xmlhttp.send(null);
}
The index .jsp is:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="javascript.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<input type="button" value="Show Server Time" onclick='ajaxAsyncRequest("getTime")' />
</body>
</html>
and my servlet code is:
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/getTime")
public class GetTimeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public GetTimeServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet (HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
PrintWriter out = response.getWriter();
LocalDate currentTime= LocalDate.now();
String message = "Currently time is "+currentTime.toString();
out.write(message);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
But when I click on the button I get the message which I pointed in the title in the line document.getElementById("message").innerHTML = xmlhttp.responseText;
in .js file.
I'm running it through http://localhost:8080/HelloAjax/, so no local, It loads later than the page, so I have no idea what can it be.
document.getElementById("message") is null because there is no element with id 'message' in the DOM. Try changing your HTML:
<body>
<div id="message"></div>
<input type="button" value="Show Server Time" onclick='ajaxAsyncRequest("getTime")' />
</body>

How to get the table content value in java?

Here, I am getting table content value (datatoexport) in servlet. But unable to get in excel page.
Getting empty page when download. Here, I am exporting table contents to excel in java.
Your help is highly appreciated.
JSP Code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Export to Excel - Demo</title>
<script src="scripts.js"></script>
<script language="javascript">
function exportToExcel()
{
alert("test");
$("#datatoexport").val( $("<div>").append( $("#exportTableSelector").eq(0).clone() ).html() );
$('#myForm').submit();
}
</script>
</head>
<body>
<form id="myForm" action="Sample" method="post">
<table id="exportTableSelector" align="left" border="2">
<thead>
<tr bgcolor="lightgreen">
<th>Sr. No.</th>
<th>Text Data</th>
<th>Number Data</th>
</tr>
</thead>
<tbody>
<%
for (int i = 0; i < 10; i++) {
%>
<tr bgcolor="lightblue">
<td align="center"><%=i + 1%></td>
<td align="center">This is text data <%=i%></td>
<td align="center"><%=i * i%></td>
</tr>
<%
}
%>
</tbody>
</table>
<br><br>
<p>
some text
</p>
<input type="hidden" name="datatoexport" id="datatoexport" value="">
<input type="hidden" value="excel_download" name="fileName" id="fileName">
<a href="" onclick="exportToExcel();" target="_blank" >Export to Excel</a>
</form>
</body>
</html>
Servlet:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Sample
*/
public class Sample extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Sample() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("Inside doGet");
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("Inside doPost");
actionExportToExcel(request, response);
}
public void actionExportToExcel(HttpServletRequest request, HttpServletResponse response)
{
String fileName = request.getParameter("fileName");
System.out.println("filename: " +fileName);
String datatoexport = request.getParameter("datatoexport");
System.out.println("datatoexport: " +datatoexport);
response.setHeader("Content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=test_file.xls");
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setDateHeader("Expires", 0);
System.out.println("datatoexport" +datatoexport);
}
}
Doesn't look like you are writing any data to the response. Try adding
response.getWriter().write(datatoexport);
response.getWriter().flush();
response.getWriter().close();
First get the PrintWriter object from HttpServletResponse by
PrintWriter out=response.getWriter();
then try writing whatever you want to write like
out.println("Whatever you want to write.");
You can do it client side, without a server request by doing something like this:
function exportToExcel()
{
var datatoexport = $("<div>").append( $("#exportTableSelector").eq(0).clone() ).html();
window.open('data:vnd.ms-excel;charset=utf-8,' + escape(datatoexport));
}

Categories