The First Time To Learning The Serverlet.

来源:互联网 发布:linux设置终端大小 编辑:程序博客网 时间:2024/06/09 17:49

一。了解Serverlet:

Servlet(Server Applet),全称Java Servlet,未有中文译文。是用Java编写的服务器端程序。其主要功能在于交互式地浏览和修改数据,生成动态Web内容。狭义的Servlet是指Java语言实现的一个接口,广义的Servlet是指任何实现了这个Servlet接口的类,一般情况下,人们将Servlet理解为后者。

二.实践:【例】首先创建一个javaweb项目,并在该项目下创建一个类,该类实现了服务器与客户端之间的一个简单的实现原理或者说是实现的步骤,下面是一个简单的代码阐述:

package st;
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 Sverlet extends HttpServlet {
@Override
public void init() throws ServletException {
System.out.println("kaishi");
}
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("yunxing");
response.setCharacterEncoding("GBK");
response.setContentType("text/html");
PrintWriter out=response.getWriter();
// out.print("哈哈<br/>");
String NAME=request.getParameter("name");
String PASSWORD=request.getParameter("password");
out.print(NAME);
out.print("<br/>");
out.print(PASSWORD);
}
@Override
public void destroy() {
System.out.println("jieshu");
}


}

//在该项目的webroot/webinf/lib路径下会有一个.jsp的文件和一个.xml的文件,我们分别需要在这两个文件下实现某些代码,如下所示:

//1.  .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>Sverlet</servlet-name>
<servlet-class>st.Sverlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Sverlet</servlet-name>
<url-pattern>/Sverlet</url-pattern>
</servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>



//2. .jsp

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%
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>
 <form method="get" action="Sverlet"> 
 
 s账号:<input type="text" name="name"/>
密码:<input type="password" name="password"/>
 <input type="submit" value="提交">
  </form>

</body>

</html>


原创粉丝点击