How to pass parameter to servlet

末鹿安然 提交于 2020-02-05 05:31:12

问题


How do I pass a parameter from a page's useBean in JSP to a servlet in Java? I have some data in a form that gets passed no problem with a submit button, but no way to send anything else. Please help? Here is my code:

<input name = "deleteGameButton" type = "submit" value = "Delete"
 onclick = "submitToServlet('DeleteGameServlet');">

Here is the corresponding javascript:

 function submitToServlet(newAction)
 {
   document.userGameForm.action = newAction;
 }

I'd like the servlet to have access to userBean

 <jsp:useBean id = "userBean" scope = "session" class = "org.project.User" />

回答1:


You kind of mess things here.

onclick() is Javascript and executed on client side. It has no (direct) way to update session-scoped bean. That bean is left on server-side, and was used when the HTML page was generated. To pass parameters back to servlet you need to use good old form fields, and submit the form.

Add more fields to the form, set their values before submit, then submit.

In Servlet call request.getParameter("name");

P.S. To automate this kind of things USE STRUTS. :-) Struts does exactly what you want: before passing the parameters to action, it populates the bean with those parameters. Transparently.




回答2:


It depends exactly what you are trying to do. The

<jsp:useBean id = "userBean" scope = "session" class = "org.project.User" />

tag will allow you to use the userBean attribute of the session in your jsp. If there is not a userBean attribute in the session, it will create a new one (using the default constructor for org.project.User) and place it in the session.

Then, when you get to the servlet, you can retrieve it with:

User user = (User)request.getSession().getAttribute("userBean");



回答3:


 getServletConfig().getServletContext().getRequestDispatcher("servlet path & name");         
 dispatcher.forward (request, response);



回答4:


Hi try with the next tag:

<jsp:useBean id = "userBean" scope = "session" class = "org.project.User"/>
 <jsp:setProperty name="beanName" property="propertyname" value="value"/>
</jsp:useBean>

more here

Good luck!



来源:https://stackoverflow.com/questions/234090/how-to-pass-parameter-to-servlet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!