Servlet是Sun公司提供的一门用于开发动态web网页的技术。Servlet是在服务端运行的小程序。
现在,编写一个pc服务端应用Servlet接口,客户端使用Android系统的HTTP通信的程序。
1.新建一个Java web工程,在src目录下新建一个servlet,命名为loadMessage。
public class loadMessage extends HttpServlet {
/**
* Constructor of the object.
*/
public loadMessage() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.print("使用post方法访问服务器成功!");
System.out.println("访问成功");
String type = request.getParameter("type");//获取访问信息类型,0 授权信息,1 刷卡信息
if(type.equals("0")){
System.out.println("开始处理授权信息……");
String seatId = request.getParameter("seatId");
System.out.println(seatId);
SignAuthAction saa = new SignAuthAction();
String jsonstr = saa.test();
out.print(jsonstr);
}else if(type.equals("1")){
System.out.println("开始处理签入信息……");
/*BufferedReader br=new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
System.out.println(br);*/
}else if(type.equals("2")){
System.out.println("开始处理签出信息……");
}
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
2.在webroot下的WEB-INF的web.xml,进行servlet配置。
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>loadMessage</servlet-name>
<servlet-class>com.Cherie.server.loadMessage</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loadMessage</servlet-name>
<url-pattern>/servlet/loadMessage</url-pattern>
</servlet-mapping>
3.新建Java类SignAuth与SignAuthAction,进行Java对象与JSON数据的转换。
public class signAuth {
public String roomId;
public String studentId;
public String name;
public long cardId;
public int seatId;
public long startTime;
public long endTime;
public String getRoomId() {
return roomId;
}
public void setRoomId(String roomId) {
this.roomId = roomId;
}
public String getStudentId() {
return studentId;
}
public class SignAuthAction {
public String test(){
signAuth sa = new signAuth();
List<signAuth> list = new ArrayList<signAuth>();
sa.setRoomId("202");
sa.setCardId(1234);
sa.setName("申一");
sa.setSeatId(5);
sa.setStudentId("s2016");
sa.setStartTime(123456789);
sa.setEndTime(12333);
signAuth sa1 = new signAuth();
sa1.setRoomId("202");
sa1.setCardId(1234);
sa1.setName("张三");
sa1.setSeatId(4);
sa1.setStudentId("s2016");
sa1.setStartTime(123456789);
sa1.setEndTime(12333);
list.add(sa);
list.add(sa1);
//JSONArray jsonarr = JSONArray.fromObject(list);
JSONObject jsonobj = new JSONObject();
jsonobj.put("signAuth", list);
System.out.println(jsonobj.toString());
return jsonobj.toString();
}
}
4.启动tomcat服务器,在浏览器中输入url,就可以看到运行结果了。或者由Android客户端使用request访问。
注:外部添加的jar包一定要放在WEB-INF的lib文件夹下,保证部署工程后tomcat的webapp中也有此jar包。
url:http://IP:8080/项目名/servlet/loadMessage?type=1
实例demo:点击打开链接
———————————————————————————————————————————————————
Servlet基础
1.Servlet接口实现类
(1)FacesServlet是一个用于管理利用JSF(JavaServer Faces)构建用户界面的web应用程序请求处理生命周期的Servlet。(FacesServletis a servlet that manages the request processing lifecycle for web applications that are utilizing JavaServer Faces to construct the user interface.)
(2)GenericServlet是HttpServlet的父类,包含了servlet的常用方法。GenericServlet使得程序员写servlets更加简单,它提供了初始化和销毁生命周期的方法,以及实现了写日志文件的方法。
(3)HttpServlet指能够处理HTTP请求的servlet。这是开发人员在编写Servlet时,通常应继承这个类即可。
2.Servlet部署
客户端通过URL地址访问web服务器中的资源,所以若想访问Servlet必须要把servlet程序映射到一个URL地址上,在web.xml文件中使用<servlet>元素和<servlet-mapping>元素完成,如上面的实例。
*<servlet>用于注册Servlet,包含了<servlet-name>和<servlet-class>两个子元素,分别用于设置servlet的名称以及servlet的类名。
*<servlet-mapping>用于映射上面<servlet>中的对外访问路径,同样包含<servlet-name>和<url-pattern>两个元素,分别用于设置servlet的名称以及servlet的对外访问路径。
在servlet映射到URL有两种格式:
1.“*.扩展名”
2.以正斜杠(/)开头并以“/*”结尾。
3.Web服务器调用Servlet过程(Servlet生命周期)
servlet程序是由web服务器调用,web服务器实现了对servlet生命周期的管理。servlet的生命周期分为四步:
1)实例化以及加载servlet,new的过程。
2)初始化init(ServletConfig)。
3)处理请求,调用servlet的service,doget,dopost方法将Request和Response,作为参数传递。
4)退出服务,调用destory方法释放资源。
注意:servlet只实例化一次,init方法也只执行一次。
4.Servlet线程问题
当多个客户端并发访问同一个Servlet时,web服务器会为每一个客户端的访问请求创建一个线程,并在这个线程上调用service方法,因此,service方法内如果访问了同一个资源的话,就有可能引发线程安全问题。
(1) Servlet是单实例多线程的,如果存在可以修改的成员变量将会出现线程安全问题。
(2) 使用Servlet最好保证Servlet是无状态的,也就是没有可以修改的成员变量。