首先是web.xml文件的配置
<servlet>
<servlet-name>HelloWorld</servlet-name> //标记名称
<servlet-class>com.bestnet.servlet.Helloworld</servlet-class> //这个是文件地址
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/com/bestnet/Helloworld</url-pattern> //这个是访问地址
</servlet-mapping>
servlet的文件配置
package com.bestnet.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Helloworld extends HttpServlet{
private String message; //成员变量
public void init() throws ServletException{ //初始化方法
message="Hello World!!";
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException{
// 设置响应内容类型
response.setCharacterEncoding("utf-8"); //设置编码格式
response.setContentType("text/xml;charset=utf-8");
// 设置刷新自动加载时间为 5 秒
response.setIntHeader("Refresh", 5); //设置自动刷新时间
// response.sendError(407, "Need authentication!!!" ); //设置错误代码和信息
Calendar calendar = new GregorianCalendar();
String am_pm;
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";
else
am_pm = "PM";
String CT = hour+":"+ minute +":"+ second +" "+ am_pm;
PrintWriter out = response.getWriter(); //创建out对象
String title = "使用 GET 方法读取表单数据";
out.println( //拼接页面内容
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<p>当前时间是:" + CT + "</p>\n"+
"<ul>\n" +
" <li><b>数学标识:</b>: "
+ request.getParameter("maths") + "\n" +
" <li><b>物理标识:</b>: "
+ request.getParameter("physics") + "\n" +
" <li><b>化学标识:</b>: "
+ request.getParameter("chemistry") + "\n" +
"</ul>\n" +
"</body></html>");
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
// public void destory(){
//
// }
}