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>
Related
I have searched the forums a lot for a solution to my problem but so far nothing. So I need your help!
Currently I am taking the Java EE course: "Develop websites with Java EE" on openclassrooms and arrived on JDBC I am blocked.
The principle consists of reading data in the database from the Java code and displaying them at the level of the JSP. But the display poses a problem at the JSP level. Thank you for your help! Here is my code for the JSP.
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>titre</title>
</head>
<body>
<h1>Bienvenue dans mon site</h1>
<ul>
<c:forEach var="utilisateur" items="${ utilisateurs }" >
<li><c:out value="${ utilisateurs.prenom }" /><c:out value="${ utilisateurs.nom }" /></li>
</c:forEach>
</ul>
</body>
</html>
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;
import sn.mballo.bdd.Personnes;
#WebServlet("/bonjour")
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
public Test() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Personnes tablePersonnes = new Personnes();
request.setAttribute("utilisateurs", tablePersonnes.recupererUtilisateurs());
this.getServletContext().getRequestDispatcher("/WEB-INF/bonjour.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
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>
I just started learning servlet and got the following problem.
I need to use forward method in my servlet and show the result in other frame.
But nothing is shown. When I use include method, it's shown me the result.
How can I shown my result with forward method?
frame.jsp
<%# page import="StudyC.C18_HelloWeb"%>
<%# page language="java" contentType="text/html; charset=Windows-31J"
pageEncoding="Windows-31J"%>
<html>
<head>
<title>検索画面</title>
</head>
<FRAMESET ROWS ="20%,80%" >
<FRAME SRC ="C18_HelloINPUT.jsp" NORESIZE scrolling = yes>
<FRAME SRC ="C18_HelloOUTPUT.jsp" NORESIZE scrolling = no name = frameOutput>
</FRAMESET>
C18_HelloINPUT.jsp
<%# page language="java" contentType="text/html; charset=Windows-31J"
pageEncoding="Windows-31J"%>
<%# page import = "javax.servlet.RequestDispatcher" %>
<html>
<script>
function validateForm() {
var x = document.forms['myForm']['dataName'].value;
if (x == null || x.match(/^\s*$/)) {
alert('空です');
return false;
}
}
</script>
<style>
h1 {text-align:center;}
</style>
<h1>入力画面</h1><br>
<form name='myForm' action="C18_HelloWeb" method="get"
onsubmit='return validateForm()'target='frameOutput' >
<input type='text' name='dataName'>
<input type='submit' value='クエリ送信'>
</form>
C18_HelloOUTPUT.jsp
<%# page language="java" contentType="text/html; charset=Windows-31J"
pageEncoding="Windows-31J"%>
<html>
<style>
h1 {text-align:center;}
</style>
<h1>出力画面</h1>
</html>
C18_HelloWeb.java
package StudyC;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class C18_HelloWeb extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void init(ServletConfig config)
throws ServletException{
}
protected void doGet (HttpServletRequest request, HttpServletResponse respone)
throws ServletException, IOException {
respone.setContentType("text/html; charset=Windows-31J");
request.setCharacterEncoding("Windows-31J");
HttpSession session = request.getSession(true);
PrintWriter out = respone.getWriter();
RequestDispatcher rd = request.getRequestDispatcher("C18_HelloOUTPUT.jsp");
rd.forward(request,respone);
String firstName = request.getParameter("dataName");
#SuppressWarnings("unchecked")
ArrayList<String> dataList = (ArrayList<String>)session.getAttribute("PreviousItems");
if( dataList == null ) {
dataList = new ArrayList<String>();
session.setAttribute("PreviousItems", dataList);
}
dataList.add(firstName);
int i = 0;
do{
out.print(HTMLFilter.filter(dataList.get(i)) + "<br>");
i++;
} while(i<dataList.size());
}
protected void doPost(HttpServletRequest request, HttpServletResponse respone)
throws IOException, ServletException
{
doGet(request, respone);
}
}
I think there is a problem in the C18_HelloINPUT.jsp and C18_HelloWeb.java. Thank you!
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));
}
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) {
}
});