《JavaWeb---Servlet的简单例子》---响应浏览器的请求,向浏览器输出数据

1.开发java web要有服务器来给我们提供服务。将我们的应用部署到服务器上。

我用的是tomcat服务器。点击下载

相关的配置可以在网上找到教程。

2.在我们的应用中建立必要的文件夹及文件。


3.在classes文件中创建.java文件,编写里面的代码。

(代码如下)

package com.fenghuo;
 
import java.io.*;
import javax.servlet.*;
 
public class FirstServlet extendsGenericServlet{
         publicvoid service(ServletRequest req, ServletResponse res) throws ServletException,java.io.IOException
         {
                   OutputStreamout = res.getOutputStream();
                   out.write("HelloServlet!!".getBytes());
         }
}


必须写相应的包名。(便于管理)

4.编译此代码,生成.class文件。

这里的编译有点麻烦,因为java中没有servlet相关的数据。我们可以查看tomcat的lib包里面有个servlet-api.jar包。我们就是用此包进行编译。

编译时你可以再cmd中配置classpath当然也可以在环境变量中配置,我建议在环境变量中配,这样以后用到了就不用配了。

配置好后就可以有javac进行编译了。


5.如果我们想访问此servlet文件还是不行的,还需要配置想要的对外访问路径。

配置文件我们放在web.xml文件中。配置如下:

<?xml version="1.0"encoding="ISO-8859-1"?>
<!--
 Licensed to the Apache Software Foundation (ASF) under one or more
 contributor license agreements. See the NOTICE file distributed with
 this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under theApache License, Version 2.0
 (the "License"); you may not use this file except incompliance with
  theLicense.  You may obtain a copy of theLicense at
 
     http://www.apache.org/licenses/LICENSE-2.0
 
  Unlessrequired by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS"BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  Seethe License for the specific language governing permissions and
 limitations under the License.
-->
<web-appxmlns="http://java.sun.com/xml/ns/j2ee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/j2eehttp://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
   version="2.4">
 
 
   <servlet>
       <servlet-name>FirstServlet</servlet-name>
       <servlet-class>com.fenghuo.FirstServlet</servlet-class>
   </servlet>
 
   <servlet-mapping>
       <servlet-name>FirstServlet</servlet-name>
       <url-pattern>/FirstServlet</url-pattern>
   </servlet-mapping>
 
 
</web-app>


6.这样一个简单的servlet就开发好了,下面就是开启服务器进行访问检测。

运行结果:


第一个servlet就这样完成了,当浏览器中输出Hello Servlet!!的时候还是有点小激动的。

努力了这么多天,熬了这么多天的夜。总算有回报了。

相关内容下载:

点击下载:tomcat服务器tomcat-5.5.28和tomcat-6.0.30及配置资料


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值