JSP 中Servlet的自己实现
程序员文章站
2022-07-02 18:08:08
jsp 中servlet的自己实现
一 步骤
1、继承httpservlet
2、重写doget()或者dopost()方法
3、在web.xml中注册serv...
jsp 中servlet的自己实现
一 步骤
1、继承httpservlet
2、重写doget()或者dopost()方法
3、在web.xml中注册servlet
二 httpservlet类继承图
三 实例
1、创建myfirstservletdemo web project.
2、编辑index.jsp
<%@ page language="java" import="java.util.*" contenttype="text/html; charset=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%>" rel="external nofollow" > <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" rel="external nofollow" > --> </head> <body> <h1>第一个servlet小例子</h1> <a href="servlet/helloservlet" rel="external nofollow" >get方式请求helloservlet</a> <form action="servlet/helloservlet" method="post"> <input type="submit" value="post方式请求helloservlet"> </form> </body> </html>
3、编写helloservlet
package 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; //继承于httpservlet public class helloservlet extends httpservlet { @override protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { // todo auto-generated method stub system.out.println("处理get()请求..."); printwriter out = response.getwriter(); response.setcontenttype("text/html; charset=utf-8"); out.println("<strong>hello servlet!</strong><br>"); } @override protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { system.out.println("处理post()请求..."); printwriter out = response.getwriter(); response.setcontenttype("text/html; charset=utf-8"); out.println("<strong>hello servlet!</strong><br>"); } }
4、编写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";> <display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>helloservlet</servlet-name> <servlet-class>servlet.helloservlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>helloservlet</servlet-name> <url-pattern>/servlet/helloservlet</url-pattern> </servlet-mapping> </web-app>
四 运行结果
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!