Servlet Configuration in web.xml
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>DataEntry</servlet-name>
<servlet-class>com.ctn.origin.connection.DataEntry</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DataEntry</servlet-name>
<url-pattern>/dataentry</url-pattern>
</servlet-mapping>
Javascript :
<script type="text/javascript">
function unloadEvt() {
document.location.href='/test/dataentry';
}
</script>
But using this javascript can't call my servlet.
Is there any error ? how to call servlet ?
From your original question:
document.location.href="/dataentry";
The leading slash / in the URL will take you to the domain root.
So if the JSP page containing the script is running on
http://localhost:8080/contextname/page.jsp
then your location URL will point to
http://localhost:8080/dataentry
But you actually need
http://localhost:8080/contextname/dataentry
So, fix the URL accordingly
document.location.href = 'dataentry';
// Or
document.location.href = '/contextname/dataentry';
// Or
document.location.href = '${pageContext.request.contextPath}/dataentry';
Apart from that, the function name unloadEvt() suggests that you're invoking the function during onunload or onbeforeunload. If this is true, then you should look for another solution. The request is not guaranteed to ever reach the server. This depends on among others the browser used. How to solve it properly depends on the sole functional requirement which is not clear from the question.
You can try this if you are using jQuery. It's simple:
<script>
$(window).unload(function() {
document.location.href='/test/dataentry';
});
</script>
This can be done using ajax
<script type="text/javascript">
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", "/testmail/dataentry", true);
xmlhttp.send();
}
</script>
Related
servlet is not sending back response to ajax code. Plaease help!!!
html code, here output should be printed
this is ajax code in javascript
<script language="javascript">
reqObj=null;
function getPrice(){
if(window.XMLHttpRequest){
reqObj=new XMLHttpRequest();
}else {
reqObj=new ActiveXObject("Microsoft.XMLHTTP");
}
reqObj.onreadystatechange=process;
var area = document.getElementById('product').value;
var fType= document.getElementById('size').value;
reqObj.open("POST","./getPricefromSize?pro="+area+"&size="+fType,true);
reqObj.send(null);
}
function process1(){
if(reqObj.readyState==4){
var prce=reqObj.responseText;
document.getElementById("price").innerHTML=prce;
}
}
</script>
this is my servlet code:
String str=request.getParameter("pro");
String str1=request.getParameter("size");
PrintWriter out1=response.getWriter();
System.out.println("pro: "+str+"size: "+str1);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:linpaws","system","oracle");
st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs=st.executeQuery("select price from labpro where usernm='"+labid+"' and product='"+str+"' and sze='"+str1+"'");
rs.first();
price=rs.getString(1);
System.out.println("price"+price);
out1.write(price);
rs.close();
st.close();
output is printed in console. But not showing in ajax call
You are missing some bits out of your code:
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");
http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp should put you on the right track.
Another reason its not working is your assigning process to your onreadystatechange e.g
onreadystatechange=process but process must exactly match the name of the function your assigning which in your case is process1 so the code would become reqObj.onreadystatechange=process1.
I did a Login with Javascript which is very simple but i need redirect to other page after validate user and password . I have the following code but this opens a lash and i need to redirect to other jsp
<script type="text/javascript" language="javascript">
function loginUser()
{
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
if(username == "JBARBA" && password == "123")
{
alert('Bienvenido Jose Carlos Barba Gutierrez');
url = 'menu.jsp';
window.open(url);
}else{
alert('Usuario y/o Password Incorrectos');
}
}
</script>
I think you are looking for location.replace('newurl');
https://developer.mozilla.org/en-US/docs/Web/API/Window.location
I hope, that you don't want to rely on this code.
There is absolutly NO security in this login.
I am trying to to call a Java class when a button gets clicked from JSP. inside my JSP file I have the following:
<%
Object name = session.getAttribute("name");
Object ext = session.getAttribute("ext");
DBOps ops = new DBOps();
ReturnGetDisplayInfo GDI = ops.getDisplayInfo(ext);
%>
I have a method in DBOps that will delete a certain field so I added a button to teh table that displays the information and now I am trying to call the delete method when the button is clicked. so I tried doing the following but it did not work.
<td><button onclick=<% ops.delete(ext); %>>Delete</button></td>
I was looking at some examples that utilize javascript but it uses defiend functions in teh script rather than calling the Java class.
Thanks in advance
You can't do that directly. You need a roundtrip to the server.
The best option for that is AJAX:
make a servlet that handles performs the delete request when a certain url is invoked
use jQuery (or native XmlHttpRequest) to invoke that url
(DWR - direct web remoting is also an option, which is implemented using AJAX)
One example of my code, in javascript and ajax, if it can help you:
On my jsp i have a onClick"changeTimeZone(org)"
Javascript:
function changeTimeZone(org)
{
//Prepare a new ajaxRequest.
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
//state 4 is response ready.
//Status 200 is page found.
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//fill the timezone field with the reponse of my servlet.
document.getElementById('timeZoneText').value = xmlhttp.responseText;
}
};
//send an ajax request.
//Go to my servlet
xmlhttp.open('GET','mainServlet?command=ajax.ChangeTimeZone&Org=' + org.value, true);
xmlhttp.send();
}
I am an Ajax fresher
Ajax
function ajaxFunction() {
if(xmlhttp) {
var txtname = document.getElementById("txtname");
xmlhttp.open("POST","Namelist",true);
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("txtname=" + txtname.value);
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.getElementById("message").innerHTML=xmlhttp.responseText;
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
jsp
<form name="fname" action="Namellist" method="post">
Select Category :
<select name="txtname" id="txtname">
<option value="Hindu">Hindu</option>
<option value="Muslim">Muslim</option>
<option value="Christian">Christian</option>
</select>
<input type="button" value="Show" id="sh" onclick="ajaxFunction();">
<div id="message">here i want to display name</div><div id="message1">here i want to display meaning</div>
</form>
servlet
String ct=null;
ct=request.getParameter("txtname");
Connection con=null;
ResultSet rs=null;
Statement st=null;
try{
con=Dbconnection.getConnection();
PreparedStatement ps=con.prepareStatement("select name meaning from (select * from namelist order by dbms_random.value)where rownum<=20 and category='+ct+'" );
rs=ps.executeQuery();
out.println("name" + rs);
**Here I have confusion,**
}
catch(Exception e)
{
System.out.println(e);
}
How can i diaplay servlet value to jsp.
Please help me? or please provide some good tutorial links.
You have to make below changes :-
In Servlet :-
Set the response content type as:- response.setContentType("text/xml"); in top section of the servlet. By setting this we can send the response in XML format and while retrieving it on JSP we will get it based on tag name of the XML.
Do whatever operation you want in servlet...
Save the value for ex-
String uname=";
uname="hello"; //some operation
//create one XML string
String sendThis="<?xml version='1.0'?>"
+"<Maintag>"
+"<Subtag>"
+"<unameVal>"+uname+"</unameVal>"
+"</Subtag>"
+"</Maintag>"
out.print(sendThis);
Now we'll go to JSP page where we've to display data.
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function ajaxFunction() {
if(xmlhttp) {
xmlhttp.open("GET","NameList",true); //NameList will be the servlet name
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
getVal();
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
function getVal()
{
var xmlResp=xmlhttp.responseText;
try{
if(xmlResp.search("Maintag")>0 )
{
var x=xmlhttp.responseXML.documentElement.getElementsByTagName("Subtag");
var xx=x[0].getElementsByTagName("unameVal");
var recievedUname=xx[0].firstChild.nodeValue;
document.getElementById("message").innerText=recievedUname;//here
}
}catch(err2){
alert("Error in getting data"+err2);
}
}
And here you are done. :)
1.In servlet code
PrintWriter output = response.getWriter();
String result = "value";
writer.write(result);
writer.close()
2. Why you don't use jquery ?
You can replace your code on -
$.post('url', function(data) {
$('#message1').html(data);
});
query post example
Probably off the hook but might be useful, rather than putting up all the javascript for Ajax call use some javascript library preferably jQuery for making the Ajax call.
Any javascript library you use will help you make the code compact and concise and will also help you maintain cross browser compatibility.
If you planning to write all the XHTTP code yourself, you might end up spending a lot of time for fixing cross browser issues and your code will have a lots of hacks rather than the actual business logic.
Also, using library like jQuery will also achieve the same stuff with less number of lines of code.
Hope that helps.
looking for a javascript class like swfobject to embed java and have a simple fallback if the user doesn't have java or refuses the security prompt.
thanks,
Josh
You could build one pretty easily.
Have something like a div set up like this:
<div id="java-applet">
Message to user saying that they need Java here
</div>
Then add Java Plugin Detection (builder) to your JavaScript. Then if that returns true, then do something like:
document.getElementById("java-applet").innerHTML = "<applet>stuff here</applet>";
appletobject may work, but I have not used it.
Just embed the applet like you normally do and insert the fallback inside or insert a javascript snippet to remove the object: Besides param, you can add other elements, e.g. paragraphs with text or javascript calling some function to replace the object.
<script type="text/javascript">
function replace_object(x) {
$(x)...
}
</script>
<object x="y" id="some_applet">
<param name="y" value="z">
<p>java not available. some alternative here. <!-- option 1 --></p>
<script type="text/javascript">
replace_object('some_applet'); // option 2
</script>
</object>
This helps!
I got a very strange problem while using applet to do batch file downloading from the server side.
The Ajax request seems conflict with applet request, the applet file downloading interrupted with some socket exception.
The applet works fine under JRE5.0, it might be caused by our recent upgrade to JRE6.0.
<div id="java-applet"></div>
<script>
var t;
function startApplet() {
var attributes = {codebase:'<%=request.getContextPath()%>',
code:'<%=appletClass%>',
archive:'applet/SignedApplet.jar',
width:0,
height:0} ;
var parameters = {para1:'value1',
para2:'value2',
java_arguments:'-Xms64m -Xmx512m'
} ;
var version = '1.6' ;
var buildAppletTag = function() {
var tag = '<applet';
for (var attribute in attributes){
tag += (' ' + attribute + '="' + attributes[attribute] + '"');
}
tag += ">";
for (var parameter in parameters){
tag += '<param name="' + parameter + '" value="' + parameters[parameter] + '"/>';
}
tag += '</applet>';
return tag;
};
document.getElementById("java-applet").innerHTML = buildAppletTag(attributes, parameters, version);
clearTimeout(t);
}
t = setTimeout("startApplet()", 1000); // delayed
</script>