request.setAttribute()设置的值不能通过request.getParameter()[duplicate]

问题描述 投票:0回答:1

我遇到一个问题,其中Servlet接收从另一个Servlet转发的请求参数为null。

这是使用JPA和实体管理器来管理Student(id PK)实体Subject(subjectCode PK)实体多对多关系的Java Web应用程序的一部分。

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);

我遇到了一个问题,其中第二个servlet中的subjectCode被作为null接收。

以下两个servlet发生相同的问题:

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);

小服务程序正确地编辑了关系,但是将参数发送到第二个小服务程序时存在问题。

任何建议都会感激。

servlets
1个回答
0
投票

您正在为请求设置属性,但使用request.getParameter()。相反,您应该使用request.getAttribute()方法

第一部分

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

第二部分

System.out.println("String passed is : "+request.getAttribute("studentId"));
int id = Integer.parseInt((String) request.getAttribute("studentId"));
© www.soinside.com 2019 - 2024. All rights reserved.