JSP程序
首先,写一个JSP程序,提交表单:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'login.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form action="Login" method="post">
username: <input type="text" name="username"><br>
password: <input type="password" name="password"><br>
<input type="submit" value="submit">
<input type="reset" value="reset">
</form>
</body>
</html>
注意action中是web.xml中的url-pattern,(这里给出相对路径),这样,提交之后才能启动相应的Servlet程序。
Servlet程序
然后,写一个Servlet程序,将收到的数据显示出来:
package demo;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
processLogin(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
processLogin(req, resp);
}
private void processLogin(HttpServletRequest req, HttpServletResponse resp)
throws IOException
{
String username = req.getParameter("username");
String password = req.getParameter("password");
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println("<html><head><title>Login Result</title></head>");
out.println("<body> username: " + username + "<br>");
out.println("password: " + password + "</body></html>");
out.flush();
}
}
web.xml
在web.xml中建立好映射关系:
<servlet>
<servlet-name>LoginResult</servlet-name>
<servlet-class>demo.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginResult</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
启动浏览器,输入:http://localhost:8050/WebApi2d/Login.jsp
提交后,地址栏中显示的是:http://localhost:8050/WebApi2d/Login
后面没有用户名和密码信息。这是POST方法
get与post方法之间的差别:
1.浏览器地址栏呈现的结果不同(表象);
2.通过浏览器进行文件上传时,一定要使用post方式而绝不能使用get方式。
3.通过浏览器地址栏输入网址的方式来访问服务器端资源,全部使用的是get方法请求的。