简体   繁体   中英

Passing parameters from JSP page to servlet without using form parameters

I have been trying to pass parameters from my welcome.jsp page to details.java servlet.But the value that I am getting in servlet details.java is null. Here's the code for welcome.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<% 
String n=(String)session.getAttribute("name");
if(n==null)response.sendRedirect("login.html");

%>
Hello there!!
<%
out.println(n+"<br>");
String u=(String)session.getAttribute("userid");
out.println(u);
HttpSession session1=request.getSession();  
session1.setAttribute("userid",u); 
%>


<h3>Click here to see your salary details</h3>
<form action="Details">

<button>Salary details</button>
</form>
<h3>Click here to see your other details</h3>
<form action="">
<button>Other</button>
</form>
</body>
</html>

Here's the code for servlet details.java

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    PrintWriter out=response.getWriter();
    out.println(request.getParameter("userid"));
    //out.println(userid+"<br>");
    
    response.getWriter().append("Served at: ").append(request.getContextPath());
}

The output that I'm getting is

null Served at: /login

Is there any way in which I can pass these parameter values to my servlet without using form?

you should use the c:set element from the core library and set scope to request. Example from the docs:

<c:set var="foo" scope="request" value="..."/>

Don't forget to declare the tag library at the top of your JSP:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

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