1

I am having an issue where a servlet receives a request parameter forwarded from another servlet as null.

This is part of a Java Web app using JPA and entity manager to manage a Student(id PK) entity Subject(subjectCode PK) entity many to many relationship.

String code = (String) request.getParameter("subCode");
int id = Integer.parseInt((String) request.getParameter("stdToAdd"));

studentFacade.addSubject(id, code);
subjectFacade.addStudent(id,code);

request.setAttribute("subjectCode", code);
request.getRequestDispatcher("ListSubStd").forward(request, response);
String code = (String) request.getParameter("subjectCode");
System.out.println("Subject code: " + code+"\n");
//this prints null when called from the above servlet code
List<Student> students = subjectFacade.getStudents(code);
Subject subject = subjectFacade.find(code);
request.setAttribute("subjectStudentList",students);
request.setAttribute("subject", subject);
request.getRequestDispatcher("ListSubjectStudents.jsp").forward(request, response);

I am getting an issue where subjectCode is being received as null in the second servlet.

Same issue happens with the following two servlets:

int id = Integer.parseInt((String) request.getParameter("stdId"));
String code = (String) request.getParameter("subToAdd");

studentFacade.addSubject(id, code);
subjectFacade.addStudent(id,code);

request.setAttribute("studentId", id);
request.getRequestDispatcher("ListStdSub").forward(request, response);
System.out.println("String passed is : "+request.getParameter("studentId"));
//prints null here as well, but only when called from the servlet above
int id = Integer.parseInt((String) request.getParameter("studentId"));

List subjects = studentFacade.getSubjects(id);
Student student = studentFacade.find(id);

request.setAttribute("studentSubjectList",subjects);
request.setAttribute("student",student);

request.getRequestDispatcher("ListStudentSubjects.jsp").forward(request, response);

The servlets properly edit the relationships, but there is an issue with the parameters being sent to the second servlet.

Any advice appreciated.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Mohamed Moustafa
  • 377
  • 4
  • 18
  • Because you are confusing attributes and parameters. Change to `String code = (String) request.getAttribute("subjectCode");` – Alan Hay Nov 11 '19 at 09:03

1 Answers1

0

You are setting attribute to the request but using request.getParameter(). instead you should use request.getAttribute() method

first part

String code = (String) request.getAttribute("subjectCode");
System.out.println("Subject code: " + code+"\n");

Second part

System.out.println("String passed is : "+request.getAttribute("studentId"));
int id = Integer.parseInt((String) request.getAttribute("studentId"));
Onkar Musale
  • 909
  • 10
  • 25