JavaWeb入门—Get与Post请求方法

版权声明:. https://blog.csdn.net/WildestDeram/article/details/87120291

Get与Post请求方式

Get方式是将数据通过在URL附加数据显性向服务器发送数据

http://localhost:8080/FirstServletDemo/stud?name=jack

Post方式会将数据存放在"请求体"中隐性向服务器发送数据

http://localhost:8080/FirstServletDemo/stud
请求体:name=jack

在实际开发中Get和Post请求是要分开进行处理。service权力最高,因为所有的请求方式都会被service接收到,Get和Post都会被一视同仁的处理。

Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>ServletDemo1</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
  	<servlet-name>student</servlet-name>
  	<servlet-class>javaDemo.RequestMethodServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>student</servlet-name>
  	<url-pattern>/stu</url-pattern>
  </servlet-mapping>

</web-app>

Student.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>学习管理系统</title>
</head>
<body>
	<h1>学生管理系统</h1>
    <!-- method请求方式,如果Get请求则返回绿色字体,如果Post请求则返回红色字体 -->
	<form action="/ServletDemo1/stu" method="post">
		姓名:<input name="name"/><br/><br/>
		年龄:<input name="age"/><br/><br/>
		性别:<select name="sex">
			<option value="man">男</option>
			<option value="women">女</option>	
		</select><br><br>
		
		兴趣:
		<input name="spec" type="checkbox" />篮球
		<input name="spec" type="checkbox" />足球
		<input name="spec" type="checkbox" />羽毛球
		<br><br>
		<input type="submit" value="提交">
	</form>
</body>
</html>

RequestMethodServlet.java

package javaDemo;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RequestMethodServlet extends HttpServlet{
	/**
	 * 处理Get请求的方法
	 * @throws IOException 
	 */
	public void doGet(HttpServletRequest request,HttpServletResponse response) 
            throws IOException {
		String name = request.getParameter("name");
		response.getWriter().println("<h1 style='color:green'>"+name+"</h1>");
	}
	/**
	 * 处理Post请求的方法
	 */
	public void doPost(HttpServletRequest request,HttpServletResponse response) 
            throws IOException {
		String name = request.getParameter("name");
		response.getWriter().println("<h1 style='color:red'>"+name+"</h1>");
	}
}

总结:以后的开发中经常遇到Get和Post处理的事情是不同的。两者在传输数据方面的格式是相同的,只是传输的方式不同,Get是通过URL来传递,而Post是通过隐式"请求体"来传递。

猜你喜欢

转载自blog.csdn.net/WildestDeram/article/details/87120291