从入门到入土Java EE(七)——servlet编程(GET请求和POST请求)

342 阅读4分钟

servlet的重要工作就是处理请求, 因此Sevlet编程就是围绕处理HTTP GET请求或POST请求来进行,包括处理request和response对象。

请求和响应API

我们已经知道,接收到客户端请求后,容器会创建request(请求)对象和response(响应)对象,根据HTTP请求类型,调用相应的doGet().doPost()等方法,并将request 对象和response对象作为参数传递给这些方法。也就是说,这些方法都需要处理request对象和response对象。
ServletRequest接口隶属于javax.servlet包,是HttpServletRequest接口的父接口,后者隶属于javax.servlet.http包,主要处理有关HTTP的内容,如Cookie、Header 和Session。
HttpServletRequest接口添加了与HTTP协议相关的方法,Servlet 使用这些内容与客户端浏览器进行通信。

使用GET和POST请求

HTTP GET 和HTTP POST是开发web应用的两种最重要的请求方法。两者的区别是POST有体(body),而GET没有。

POST与GET不同:

  • POST没有查询字符串,请求行后面的几行都是请求头。长度不受请求行的限制。
  • 如果用户希望能够收藏网页,GET能够请求收藏,但POST请求不能
  • 两者的安全性也不同,GET将请求信息放在URL,POST放在报文体中
  • 具体用途不同,GET请求意味着获取信息,进行简单的、周期性的检索。POST请求亦为之发送需要处理的信息,去更新          

GET和POST请求的编程

POST请求需要表单,在<form>标签中使用method属性指定HTTP方法为POST,使用action属性指定表单提交的地址。

代码:

<body>
<h1 style="text-align:center">我的第一个HTML页面</h1>
	<form action="login.do" method="post">
		姓名:<input type="text" name="username" /><br>
		密码:<input type="text" name="userpwd" /><br><br><br>
		<input style="margin-left:80px" type="submit" value="登录" /><br>
	</form>
</body>

GET请求可以使用两种方式:

第一种方式直接使用超链接,超链接总是使用GET请求,代码如下:

<a href="https://www.baidu.com">点击</a>

第二种方法使用表单,既可以不指定<form>标签的method属性,也可以明确指定<form>标签的method属性为GET,代码如下:

<body>
<h1 style="text-align:center">我的第一个HTML页面</h1>
	<form action="login.do" method="GET">
		姓名:<input type="text" name="username" /><br>
		密码:<input type="text" name="userpwd" /><br><br><br>
		<input style="margin-left:80px" type="submit" value="登录" /><br>
		<a href="https://www.baidu.com">点击</a>
	</form>
</body>

 

使用参数

Servlet编程中的一个重要环节是接收用户的输入参数,然后才能进行后面的处理环节。接收输入参数的具体方法是调用request对象的getParameter()方法,该方法的输入参数是一个字符串变量,指定参数的名称,该名称对应表单输入组件的name属性。例如,对于前面的login.html,接收参数的代码片段如下:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setCharacterEncoding("UTF-8");
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		//获取参数
		String username = request.getParameter("username");
		String userpwd = request.getParameter("userpwd");
		String gender = request.getParameter("gender");
		String email = request.getParameter("email");
		String resume = request.getParameter("resume");
		String[] hobbies = request.getParameterValues("hobbies");
	}

大部分的表单输入参数都只有单个值,都可以采用上述方法获取参数。但也有例外的情况,如复选框,一个参数可以有多个值。 在这种情况下,就不能再使用只返回单个字符串的getParameterf()方法,而是要使用getParameterValues()方法,返回一个字符串数组。
例如,如果表单使用如下的复选框,用户就可以选择多个值。也就是说,单个参数hobbies就可以有多个值,具体值的个数取决于用户选中的选项数:

<form action="login.do" >
		爱好:<input type="checkbox" name="hobbies" value="dance"/>跳舞
		<input type="checkbox" name="hobbies" value="sing"/>唱歌
		<input type="checkbox" name="hobbies" value="music"/>音乐
		<input type="checkbox" name="hobbies" value="swim"/>游泳
		<input type="checkbox" name="hobbies" value="football"/>足球
		<br><br><br>
		<input style="margin-left:80px" type="submit" value="登录" /><br>
	</form>

 

具体实例:

创建一个HTML页面,命名为login,创建一个servlet,命名为doLogin。

login.html代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>我的登录页面</title>
</head>
<body>
<h1 style="text-align:center">我的第一个HTML页面</h1>
	<form action="login.do" >
		姓名:<input type="text" name="username" /><br>
		密码:<input type="password" name="userpwd" /><br>
		性别:<input type="radio" name="gender" value="男"/><input type="radio" name="gender" value="女"/><br>
		电子邮件:<input type="text" name="email" /><br>
		简历:<textarea rows="5" cols="25" name="resume" ></textarea><br>
		爱好:<input type="checkbox" name="hobbies" value="dance"/>跳舞
		<input type="checkbox" name="hobbies" value="sing"/>唱歌
		<input type="checkbox" name="hobbies" value="music"/>音乐
		<input type="checkbox" name="hobbies" value="swim"/>游泳
		<input type="checkbox" name="hobbies" value="football"/>足球
		<br><br><br>
		<input style="margin-left:80px" type="submit" value="登录" /><br>
	</form>
</body>
</html>

servlet代码如下:

package com.re;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.jasper.tagplugins.jstl.core.Out;

/**
 * Servlet implementation class doLogin
 */
@WebServlet("/login.do")
public class doLogin extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public doLogin() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setCharacterEncoding("UTF-8");
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//设置编码
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Content-type", "text/html;charset=utf-8");
		
		//获取参数
		String username = request.getParameter("username");
		String userpwd = request.getParameter("userpwd");
		String gender = request.getParameter("gender");
		String email = request.getParameter("email");
		String resume = request.getParameter("resume");
		String[] hobbies = request.getParameterValues("hobbies");
		
		//页面输出		
		PrintWriter out= response.getWriter();
		out.println("<br/>");
		out.println("姓名:"+username+"<br/>");
		out.println("密码: "+userpwd+"<br/>");
		out.println("性别: "+gender+"<br/>");
		out.println("电子邮箱: "+email+"<br/>");
		out.println("简历: "+resume+"<br/>");
		out.println("爱好:");
		for(int i=0;i<hobbies.length;i++) {
			out.println("&nbsp"+hobbies[i]);
		}
	}

}

先复制程序的地址,将程序复制在360浏览器中运行:

按下F12按钮,跳出开发人员工具,点击network,输入login.do查看GET请求

 

点击登录按钮之后可以获取表单数据并显示

 

一起学习,一起进步 -.- ,如有错误,可以发评论