How to send values of a form from jsp to java

℡╲_俬逩灬. 提交于 2019-12-08 07:28:56

问题


I have a form which has 30 different fields. As passing them all to the controller need to have an attribute for each along with a pair of getter, setters.

I am going to make the form fields as an object and send the object to the controller.

I am using the following code *but some people suggest its a bad practice to call a java method from jsp and use JSTL instead, but do not know how to implement it using JSTL. Is there any other method to do it?*

My JSP

 <s:form>
 code to implement form goes here
 </s:form> 

<jsp:useBean id="obj" class="com.User"/>

    <jsp:setProperty property="*" name="obj"/>

      <%
         String myoutput = myController.Xclass(obj);
         out.print(myoutput);
         if(myController.Xclass(obj).equals("output"))
            {
               out.print("The form is successfully submitted.");
            }
      %>

The controller

  public String Xclass(User obj){
           return "output";
        }

To clarify my class diagram is a following:

User Class {
 all the attributes and getters setters
}

myController class extends User {

    public String XClass(User obj){
       ... work on the inputes ...
      return "output";
    }
}

回答1:


If the number of action properties is the issue, expose a POJO manually, or use ModelDriven.

Doing it manually is simple, for example:

public class UserController {
    private User user; // Plus public getter and setter
}

Then in the JSP you can refer to User properties by name:

<s:form ...>
  <s:textfield key="user.firstName"/>
  ...

Using ModelDriven is theoretically even easier, since it's put on the stack automagically. It can be tricky to make sure new models are instantiated only when required, but basically (from memory):

public class UserController implements ModelDriven<User> {
    private User user;
    public User getModel() { return user; }
}

Use the User properties directly in the JSP since the User is pushed on the stack:

<s:form ...>
  <s:textfield key="firstName"/>
  ...

Similarly, on form submission, a model is created and used as the first target of methods.

Please remember that you never send objects to the Java side: you always, and only, send strings (from normal HTTP form submissions). There may be magic on the server side that transforms those strings into objects, but it's just that: magic. Magic and hope.



来源:https://stackoverflow.com/questions/14843807/how-to-send-values-of-a-form-from-jsp-to-java

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