简体   繁体   中英

Passing data from java to jsp

I am working on struts and I am trying to pass a String value from a java file to a jsp page. But I am receiving a null value. Please help.

My java code :

import java.io.IOException;
import javax.servlet.ServletException;
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;

public class myAction extends Action {
    public ActionForward execute(ActionMapping mapping, ActionForm form,
    HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {

        String s="Karthikeyan";

        request.setAttribute("s",s);

        RequestDispatcher reqDispatcher = getRequestDispatcher("first.jsp");
        reqDispatcher.forward(request,response);        

        return (mapping.findForward("success"));
    }
}

My jsp code :

<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>

    <body>
        Welcome!!!!!!!!

        <%
            String s=(String)request.getAttribute("s");
            out.println("s="+s);
        %>
    </body>
</html>

My jsp output :

Welcome!!!!!!!! s=null 

I wanted to know why 's' is not getting assigned. Help would be greatly appreciated.

Instead of doing

<%
   String s=(String)request.getAttribute("s");
   out.println("s="+s);
%>

Try to replace the whole thing with:

s=${s}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM