Redirect Other Jsp JavaScript - java

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.

Related

Redirecting to a JSP instead of the JSON response from a REST call

I am working on an assignment to create a simple blog, where a user can ask questions(posts) and answers can be given as comments.
With my limited knowledge on Java, REST and Jquery, I have managed to fetch the list of posts and am displaying them as a table.
Now whenever a user clicks on any post, he should be redirected to another page where the corresponding comments of the question can be displayed.
I have implemented a REST method in Java which returns the JSON response with the comments relevant to the post_id passed.
So whenever a user clicks on any post, he is redirected to a REST URL(.../services/comments?postID=1) and gets following response:
[
{
"postID": 1,
"commentID": 8,
"comment": "These are the answers getting added",
"commenterID": 7,
"commentDate": 1442671662000,
"commentVote": 0
}
]
Here is my JAVA method serving the REST call:
#GET
#Produces({ MediaType.APPLICATION_JSON })
public List<Comments> getUserComments(#QueryParam("postID") Integer postID) {
Session ses = HibernateUtil.currentSession();
ses.flush();
List<Comments> comments = null;
if(postID != null)
{
comments = ses.createQuery("select c from Comments c where c.postID="+postID+" order by c.commentDate desc").list();
}
HibernateUtil.closeSession();
return comments;
}
What is the "simplest" way to simultaneously redirect to a JSP where I can parse this JSON and display it?
You don't need to redirect the page to jsp.
What you need is a general template (jsp) of the page to display the post and its answers from the json. This page should make an ajax call to get the json for corresponding post (and its answers) and render it in the page.
Now the problem becomes how to do you pass the post id to this page.
You could do this by setting a non-html tag like this. <post_id id="post_id" value=1>. After the page is loaded the jquery will this tag (and extract the value attribute) to form the url for ajax call.
Example
Lets assume you have a page to display the list of all posts. This page will look like
post1
<br>
post2
Another jsp page to display the post and its comments. Lets call this post.jsp. This page should get a parameter post_id in the url. This page will set the tag <post_id> and use an ajax request to load the corresponding comments from REST url .../services/comments?postID="+post_id.
<body>
<script type="text/javascript">
$(document).ready(
function () {
//extract the post_id from tag value
var post_id = $("post_id").attr("value");
//form the rest url using post_id
var post_url = ".../services/comments?postID="+post_id;
$.ajax(
{
url: post_url,
success: function(data, status, jqXHR, json) {
json_data = JSON.parse(data);
html="";
for(var i=0; i<json_data.length; i++) {
//Comments rendering logic
html+= "<h5>"+json_data[i].comment +"</h5>";
}
$("#container").html(html);
}
}
);
}
);
</script>
<post_id value="<%= request.getParameter("post_id") %>" > </post_id>
<div id="container">
</div>
</body>

Not able to retrieve value of parameters from JSP page

Suppose
home.jsp code contain a button like
<input name="R" onclick="del(<%=rs.getString("VDB")%>)" type="radio" value="<%=rs.getString("VDB")%>" />
//note: i am passing value of VDB in del()
it is calling javascript as :
<script type="text/javascript">
function del(delno)
{
var ff = document.vendorform;
var url = "delete.jsp?+vendor="+delno;
window.navigate("delete_vendor.jsp?+vendor="+delno);
//window.location.href="delete_vendor.jsp?+vendor="+delno;
//ff.method = "POST";
//ff.action ="delete_vendor.jsp?+vendor="+delno;
//ff.submit();
}//i have used 3 methods to redirect to delete.jsp
delete.jsp :
on this page i want to retrieve value of vendor i used :
String D1=request.getParameter("vendor");
But getting null value.
Any help
var url = "delete.jsp?+vendor="+delno;
you have inserted wrong string +vendor. it should be only vendor in url.
var url = "delete.jsp?vendor="+delno;
Remove the "+" before the word vendor. Change
var url = "delete.jsp?+vendor="+delno;
To
var url = "delete.jsp?vendor="+delno;

How to show value from database to jsp without refreshing the page using ajax

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.

How can I alert message in Servlet code and sendredirect to JSP page?

I am trying to make a simple login page to deal with database using JSP, servlet with MVC concept and Data Access Object(DAO) and I am new in this. My problem now that I need to alert a box message in servlet if the user enters invalid name and password and sendRedirect to login.jsp page again. I set flag to be 1 if the user valid then do this if-check
if(validUserFlage == 1)
response.sendRedirect("User_Manipulation_Interface.jsp");
else {
//Here i want to alert message cause user invalid ??
response.sendRedirect("Admin_And_User_Login_Form.jsp");
}
searching for this i find this answer but i can`t understand how can i do it
the answer i found:
(( With send redirect you cant display the message where you want in the code. So as per me there might be two approaches. Display a message here and use include of requestdispatcher instead of send redirect or else pass some message to admin.jsp and display the message there. ))
Set a flag parameter like this,
response.sendRedirect("Admin_And_User_Login_Form.jsp?invalid=true");
on jsp
<c:if test=${invalid eq 'true'}">invalid credentials</c:if>
You can set the Parameters like errormsg in the servlet page and add it to the ri-direct object. Then you can check that variable errormsg and if it is null then the username is correct else the username is incorrect..
In Servlet Code:
if(username.equal(databaseusername))
{
RequestDispatcher rd = request.getRequestDispatcher("NextPage.jsp");
req.setAttribute("errormsg", "");
rd.forward(request, response);
}
else
{
RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
req.setAttribute("errormsg", "Wrong Username or Password");
rd.forward(request, response);
}
In JSP code:
<%
String msg=req.getAttribute("errormsg").toString();
if(!msg.equals(""))
{
// Print here the value of Msg.
}
%>
In servlet
String strExpired = (String) session.getAttribute("Login_Expired");
response.sendRedirect("jsp/page.jsp");
In jsp
<%
String strExpired = (String) session.getAttribute("Login_Expired");
out.print("alert('Password expired, please update your password..');");
%>

How to call servlet from javascript

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>

Categories

Resources