Chat LIVE With Programming Experts! There Are 23 Online Right Now...

Welcome to Dream.In.Code
Become a Java Expert!

Join 244,173 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,350 people online right now. Registration is fast and FREE... Join Now!




ajax- redirect to another jsp

 
Reply to this topicStart new topic

ajax- redirect to another jsp

vibinvictoria
1 Sep, 2008 - 01:33 AM
Post #1

D.I.C Head
**

Joined: 16 Jul, 2008
Posts: 71



Thanked: 3 times
My Contributions
Hi all

In this thread a post sample program for ur reference.
The following thinks are done.
1. index.jsp - in this page user enter username and password.
2. action class- check username and pasword. if it's same forward to another page else response the error message to index.jsp

But forward the next page doesn't work..
In forward page i read request.getAttribute() , which is set on action class
4 ur review
-------
CODE

index.jsp
---------
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%><%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
    
    <script type="text/javascript">
    
    function initRequest() {
       if (window.XMLHttpRequest) {
           return new XMLHttpRequest();
       } else if (window.ActiveXObject) {
           isIE = true;
           return new ActiveXObject("Microsoft.XMLHTTP");
       }
   }
    
    function ajaxFunction()
    {
        
        if (false) {  //always false.. don't worry about that..
          
       } else {
      
               var name=document.getElementById('username').value;
               var ps=document.getElementById('password').value;
               
      
           var url = "ajaxtest.do?username="+name+"&password="+ps;
           var req = initRequest();
           req.onreadystatechange = function() {
               if (req.readyState == 4) {
                   if (req.status == 200) {
                           alert(req.responseXML);
                       parseMessage(req.responseXML);
                   } else if (req.status == 204){
                       clearTable();
                   }
               }
           };
           req.open("GET", url, true);
           req.send(null);
       }
    }
     function parseMessage(responseXML) {
        var message = responseXML.getElementsByTagName("message")[0];
        setMessage(message.childNodes[0].nodeValue);
    }
    function setMessage(message) {
    var mdiv = document.getElementById("status");
    if (message == "invalid") {
       mdiv.innerHTML = "<div style=\"color:red\">Invalid User Id</ div>";
    }
    if (message == "Success")
     {
      // mdiv.innerHTML = "<div style=\"color:green\">Valid User Id</ div>";
      document.location="test.jsp"
    }
}
    </script>


    
  </head>
  
  <body>
      <form name="ajax">
      
      <div id="status">
          
      </div>
      
      User Name : <input type="text" name="username" id="username" > <br>
      Password : <input type="password" name="password" id="password" > <br>
      Upload : <input type="file" ><br />      
       <input type="button" onclick="ajaxFunction();" value="Click">            
  
       
       </form>
  </body>
</html>



Action class
------------
CODE

/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.dckap.ajax.action;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
* MyEclipse Struts Creation date: 08-14-2008
*
* XDoclet definition:
*
* @struts.action validate="true"
*/
public class AjaxtestAction extends Action {
    /*
     * Generated Methods
     */

    /**
     * Method execute
     *
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     */
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
        // TODO Auto-generated method stub
        
        
        
        System.out.println("ajax test execute successyully");
        try
        {
            String userName=request.getParameter("username");
            String pwd=request.getParameter("password");            
            System.out.println("userName="+userName +" password="+pwd);
            
            
            String err="";
            
            if(userName.equalsIgnoreCase(pwd))
            {
                err=errorMessage("Success");
                request.setAttribute("authorname",userName);    //authorname pass to another jsp            
                return mapping.findForward("success"); // struts config- mapping to test.jsp
                
            }
            else
            {
                err=errorMessage("invalid");
            }
            
            System.out.println("return not executed");
            
            if(err.length()>0)
            {
                    System.out.println("err="+err);
                 response.setContentType("text/xml");
                 response.setHeader("Cache-Control", "no-cache");  
                 response.getWriter().write(err);
                          
            }
            
        }
        catch(Exception  ie)
        {
            
        }
        
        return null;
    }
    public String errorMessage(String err)
    {
        return "<message>"+err+"</message>";
        
    }
}

test.jsp
--------

CODE

<body>
    This is my JSP page.
    <%= request.getAttribute("authorname") %> // read the login user name
    <br>
  </body>


but i executed the code above. Username and password mismatch i got the error message response. but if it's true no response(actualy need to redirect to another jsp(test.jsp).

This post has been edited by vibinvictoria: 1 Sep, 2008 - 01:34 AM

User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic

Time is now: 7/4/09 05:43AM

Live Java Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month