1 通过地址访问
在地址栏输入Servlet的URL直接访问Servlet。通过地址栏中访问,是GET方式,将调用doGet方法。
URL(外文名:Uniform Resource Locator,中文名:统一资源定位符),统一资源定位符是对可以从互联网上得到的资源的位置和访问方法的一种简洁的表示,是互联网上标准资源的地址。互联网上的每个文件都有一个唯一的URL,它包含的信息指出文件的位置以及浏览器应该怎么处理它。它最初是由蒂姆·伯纳斯·李发明用来作为万维网的地址。现在它已经被万维网联盟编制为互联网标准了。
格式:http://localhost:端口号/项目名称/url-pattern
例如:http://localhost:8888/JavaEE05Servlet/first
2 通过超链接进行访问
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="first">First</a>
</body>
</html>
其中,first即web.xml中配置的url-pattern,此处不需要/。
3 通过提交表单访问
把Servlet作为表单的响应事件,可以接受表单的数据,并进行操作。
index.jsp文件代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="first" method="post">
账号:<input name = "userId" type="text"><br>
密码:<input name = "pw" type="password"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
FirstServlet.java代码:
package com.company.project.servlet;
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;
public class FirstServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public FirstServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//测试get方法是否被调用
System.out.println("doGet...");
//设置相应内容类型
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
//通过getParameter(name)方法可以获取表单的数据
String userId = request.getParameter("userId");
String pw = request.getParameter("pw");
if(userId != null && userId != "" && pw != null && pw != "" ) {
System.out.println(userId);
System.out.println(pw);
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}