【javaWeb】前后端传递数据交互的两种方式

一、使用struct2的方法set及get

1、在jsp中直接定义定义form表单

<form id="formid"  name= "myform" method = post  action = login.action onsubmit = "return checkUser();" >
    <table width="100%" border="0">
         <tr>
                <td width="60" height="40" align="right">用户名&nbsp;</td>
                <td><input type="text" value="" class="text2" name = "username" id = "userid"/></td>
              </tr>
              <tr>
                <td width="60" height="40" align="right">密&nbsp;&nbsp;码&nbsp;</td>
                <td><input type="password" value="" class="text2" name = "password" id = "userpassid"/></td>
              </tr>
              <tr>
                <td width="60" height="40" align="right">&nbsp;</td>
                <td><div class="c4">
                    <input type="submit" value="" class="btn2"  /></div>
                    </td>

               </tr>
            </table>

           </form>

在js中对于数据进行核验

function checkUser(){
          
   
       var result = document.getElementById("userid").value;
       var password = document.getElementById("userpassid").value;
       if(result == ""  ){
         alert("用户名不能为空");
         return false;
       }
       if(password == ""  ){
        alert("密码不能为空");
         return false;
       }else{
       return true;
       }
    }

3、在对于数据提交的时候,会跳转到相应的action处

<action name="login" method="login" class="com.simpleton.demo.action.JsonAction">
</action>

4、对应提交的数据要在后台使用同一个命名,并设置set及get方法

private String username;

    private String password;

    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

5、在xml中配置的跳转action

public void login(){
    System.out.println(username);
    System.out.println(password);
}

6、简单的验证

点击login登录以后后台输出如下

二、使用ajax传递数据

1、在js中直接使用ajax作为异步请求

$.ajax({           
        type:"post",
        url:"addwordJsonAction",//请求的action
        data:{word : word},//传递的数据
        dataType:"json",//设置需要返回的数据类型
        success:function(data){
          
   
            //成功时返回的数据
        }           
});

2、在xml中的配置文件

<action name="*JsonAction" method="{1}" class="com.simpleton.demo.action.JsonAction">
    <!-- 返回json类型数据 -->
    <result type="json">
        <param name="root">result</param>
    </result>
</action>

3、对应的action文件中直接读取数据即可使用

HttpServletRequest request = ServletActionContext.getRequest();
String word = request.getParameter("word");
System.out.println(word);
经验分享 程序员 微信小程序 职场和发展