将表单请求提交到本页

在Web应用程序中,有时需要将表单请求提交到本页进行处理

实现将表单提交到本页,只要将表单的action属性设置为本页即可,假定表单页为index.jsp
,那么action的值为index.jsp,然后应用request对象的getParameter()方法来获取表单元素的值。
在这里插入图片描述

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="index8.jsp" method="post">
	<table align="center" height="150" height="300">
		<tr><td align="center" colspan="4" height="20"></td></tr>
		<tr><td align="center" colspan="4">用户登录</td></tr>
		<tr>
			<td>用户名:</td>
			<td><input type="text" name="name"></td>
		</tr>
		<tr>
			<td>密码:</td>
			<td><input type="password" name="pwd"></td>
		</tr>
		<tr>
			<td></td>
			<td><input type="submit" name="submit" value="登录"></td>
		</tr>
		<%
		if(request.getParameter("submit")!=null){
		request.setCharacterEncoding("UTF-8");
		String name=request.getParameter("name");
		String pwd=request.getParameter("pwd");
		
		%>
		<tr>
			<td>用户名参数为:</td>
			<td><%=name %></td>
		</tr>
		<tr>
			<td>密码参数为:</td>
			<td><%=pwd %></td>
		</tr>
		<%} %>
	</table>
</form>
</body>
</html>

在index.jsp页中获取表单信息,关键代码:

<%
		if(request.getParameter("submit")!=null){
		request.setCharacterEncoding("UTF-8");
		String name=request.getParameter("name");
		String pwd=request.getParameter("pwd");
		
		%>

需要注意的

,在页面中使用request对象的getParameter()方法来获取参数时,在页面加载后就会自动执行这段代码,因此,需要 if(request.getParameter("submit")!=null)进行合理判断,只有提交表单后才可以执行request对象的getParameter()方法来获取表单的代码

猜你喜欢

转载自blog.csdn.net/weixin_44234912/article/details/87902054
今日推荐