1.用url调用servlet
建 web project “HelloServlet”,在src下建包com.amaker.servlet,在包下建HelloServlet.java。
package com.amaker.servlet; 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;
//敲doGet alt+/,就会出现原来的方法
public class HelloServlet extends HttpServlet { /**
*
*/
private static final long serialVersionUID = 2733147315082601065L; protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
String url=request.getRequestURI().toString();
System.out.println(url);
PrintWriter out =response.getWriter();
out.println("hello");
} }
修改web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>helloa</servlet-name>
<servlet-class>com.amaker.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>helloa</servlet-name>
<url-pattern>/servlet/hello</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<login-config>
<auth-method>BASIC</auth-method>
</login-config>
</web-app>
2.用表单调用:
在WebRoot文件夹中,添加一个HTML文件,Tset.html
<!DOCTYPE html>
<html>
<head>
<title>Tset.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> </head> <body>
<form action="/HelloServlet/servlet/hello">
<input type="submit" value="Test">
</form>
</body>
</html>
3.用超级链接调用Servler
<hr>
<a href="/HelloServlet/servlet/hello">link...</a>
4.用javascript调用servlet
<!DOCTYPE html>
<html>
<head>
<title>Tset.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
<script type="text/javascript">
function test()
{
var f=document.forms[0];
f.action="/HelloServlet/servlet/hello";
f.submit(); }
</script>
</head> <body>
<form action="/HelloServlet/servlet/hello">
<input type="submit" value="Test">
<input type="button" value="click me" onclick="test()">
</form>
<hr>
<a href="/HelloServlet/servlet/hello">link...</a>
</body>
</html>]