您的位置:首页 > 其它

Servlet学习日记(一)——什么是Servlet及手动编写一个简单的servlet

2017-06-19 22:21 375 查看
1.什么是Servlet?

Servlet是在服务器上运行的小程序,一个Servlet就是一个java类,这个java类使用了Java Servlet应用程序设计接口(API)及相关类和方法。除了Java Servlet API,Servlet还可以使用用以扩展和添加到API的Java类软件包。客户端(浏览器)可以通过“请求—响应”来访问驻留在服务器的Servlet小程序。

2.手工编写一个一个简单的servlet

手工编写servlet有三个步骤:

创建一个java类并且继承HttpServlet

重写doGet()或者doPost()方法

在web.xml里注册servlet

核心代码:

index.jsp

在jsp页面里添加一个a标签

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
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 'index.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>
<a href="servlet/MyServlet">doGet</a>
</body>
</html>


servlet代码:

public class MyServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("doGet");
PrintWriter out = response.getWriter();
out.println("<h1>hello doGet</h1>");
}

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
}

}


web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>MyWeb</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>MyServlet</servlet-name>
<servlet-class>servlet.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/servlet/MyServlet</url-pattern>
</servlet-mapping>
</web-app>


启动服务器,通过a标签的链接,对应到web.xml文件里的servlet-mapping中的url-pattern,然后找到对应servlet的名字,再通过名字找到了处理该请求的servlet类。

最后附上效果图:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: