java servlet for sever send event
import java.io.*;
import java.util.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Enumeration;
public class aobm extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) {
response.setHeader("pragma", "no-cache,no-store");
response.setHeader("cache-control", "no-cache,no-store,max-age=0,max-stale=0");
response.setContentType("text/event-stream \n\n");
response.setCharacterEncoding("UTF-8"); //utf8
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
String _p = "";
String _return = "";
String Delimiter = "";
Enumeration en = request.getParameterNames();
String _r = "";
try {
PrintWriter pw = response.getWriter();
while (en.hasMoreElements()) {
String paramName = (String) en.nextElement();
_p = request.getParameter(paramName);
if (_p==null){_p="null";}
if (_p==""){_p="null";}
for (int rR=0;rR<1;rR++) {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager
.getConnection(
"jdbc:mysql://localhost/DataBaseName?useUnicode=true&characterEncoding=UTF8",
"root", "root");
stmt = con.createStatement();
rs = stmt.executeQuery(
"select field1,field2, field3,field4 from tableName where key=value ;");
String delimiter="&";
_r="";
while (rs.next()) {
String _1= "" ; if(rs.getObject(1)==null){_1="-";} else {_1=rs.getObject(1).toString();}
String _2= "" ; if(rs.getObject(2)==null){_2="-";} else {_2=rs.getObject(2).toString();}
String _3= "" ; if(rs.getObject(3)==null){_3="-";} else {_3=rs.getObject(3).toString();}
String _4= "" ; if(rs.getObject(4)==null){_4="-";} else {_4=rs.getObject(4).toString();}
_r = _r + delimiter+_1+","+ _2+","+ _3 +","+ _4 ; }
con.close();
} catch (SQLException e) {
throw new ServletException(
"Servlet Could not display records.", e);
} catch (ClassNotFoundException e) {
throw new ServletException("JDBC Driver not found.", e);
} catch (Exception e) {e.printStackTrace();}
Long date = System.currentTimeMillis();
_return = _return + Delimiter + paramName + "_" + _p + ":" + _r+"\n" + date.toString();
Delimiter = ",";
pw.write("retry: 101 \n\n");
Date datetime=new Date();
pw.write("data: datetime_"+datetime.toString()+"\n\n");
pw.write("data: " + _return + " \n\n");
pw.flush();
try{Thread.sleep(80);} catch (InterruptedException e) {}
}
}
} catch (Exception e) {e.printStackTrace();}
}
public void doGet(HttpServletRequest request, HttpServletResponse response) {
doPost(request, response);
}
}
沒有留言:
張貼留言