您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Form.action传值问题

2024/3/16 16:19:16发布20次查看
通过浏览器地址栏输入url并通过?传递参数请求资源时,?后面的参数叫做 查询字符串,会触发后台servlet的doget(),因为通过浏览器地址栏直接访问的方式是get方式。
下面顺便了解一下form的method属性对传参的影响。
原始表单:
用户名:
第一种情况:
上面表单的action属性不写时,直接点击“提交”按钮,会触发表单的提交事件,此时,通过火狐浏览器的控制台可以发现:
消息头中有如下关键信息:(1)请求地址后面通过'?'传递参数(2)请求方式为get
参数信息: 查询字符串
指定form的method属性时:
用户名:
第二种情况:
消息头中有如下关键信息:(1)请求地址后面没有传递任何参数(2)请求方式为post
参数信息: 表单数据
上面两种方式的相应都是刷新后显示当前页面,因为form没有指定action属性,默认提交的地址就是当前页面。
现在通过指定action属性访问servlet来进一步了解method属性。
testservlet.java核心源码:
@webservlet(/servlet/testservlet)
public class testservlet extends httpservlet {
private static final long serialversionuid = 1l;
protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
response.getwriter().print(doget());
}
protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
response.getwriter().print(dopost());
}
}
第三种情况:method=get action=/test/servlet/testservlet
用户名:
上面的消息头,参数和第一种情况是一样的,不过后台响应了一个doget().
第四种情况: method=post action=/test/servlet/testservlet
用户名:
上面的消息头,参数和第一种情况是一样的,不过后台响应了一个dopost().
testservlet.java 添加获取参数代码:
protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
string param = request.getparameter(type);
response.getwriter().print(doget() get type=+param);
}
protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {
string param = request.getparameter(type);
response.getwriter().print(dopost() get type=+param);
}
第五种情况,method=get 在action后面传参action = /servlet/testservlet?type=01,同时在后台servlet中获取参数
此时浏览器地址栏:http://localhost:8080/test/servlet/testservlet?username=
可以发现,后台的doget()是获取不到参数type的.
同时发现,type参数是没有加入到“查询字符串”的
第六种情况,method=post 在action后面传参action = /servlet/testservlet?type=01,同时在后台servlet中获取参数
可以发现,后台的dopost()是可以获取参数type的。
同时,参数一栏和以前有些不同:既有“查询字符串”又有“表单数据”
所以上面给我们一种启示,就是通过?在form的action后面传递参数时,我们需要手动指定form的method=post,不然是获取不到?后面的参数的;
思维误区:之前我们在浏览器地址栏通过url传递参数,也是通过?来实现的,它最终也是调用doget()方式,所以我们就认为在的表单(默认method=get)中action后面可以通过?来传参。
最终原因:(个人总结)get方式提交表单数据时,会重组url,它只会将form的表单数据组装成“查询字符串”,提交到form的action中指定的url,所以原来通过?方式传递的参数是不会提交的,因为url重组了就丢失了。
但是post方式提交表单时,它会将表单数据和?后面的参数,分开保存,一起提交给form中action指定的url。
(参考资源)html form: why action can't have get value in it?
http://stackoverflow.com/questions/3548795/html-form-why-action-cant-have-get-value-in-it
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product