Новичок
Профиль
Группа: Участник
Сообщений: 2
Регистрация: 31.3.2009
Репутация: нет Всего: нет
|
у меня написан класс requestServlet extends HttpServlet, который является родителем ещё десятка классов, например приведенного ниже CodeRMServlet. Многопоточность необходима. В куках или боди я присылаю параметры для хранимых процедур. По логу видно, что данные перекрываются и отсюда неправильная одновременная работа 2 сервлетов. Помогите пожалуйста. Код | public class requestServlet extends HttpServlet { public static final String NAME_USER_ATTRIBUTE = "userName"; public static final String USER_KEY_COOKIES = "userKey"; public static final String COOKIE_CODE_RM = "codeRM";
public static final String ValueNormalCodeErr = "200"; public static final String ValueNotDeterminCodeErr = "300";
public static final String GET_METHOD = "Get"; public static final String POST_METHOD = "Post";
public static Logger log = Logger.getLogger("GAIAPP_Error_Log"); public static Logger log_Login = Logger.getLogger("GAIAPP_Tomcat_Log");
public QueryTasks fireBirdLog_QueryTasks = null;
private HttpServletRequest request; private HttpServletResponse response; private String userName=""; public Hashtable<String, UserInfo> userActive;
protected String sessionID; protected HttpSession session;
protected Boolean enableGet; protected Boolean enablePost; protected Boolean checkUser;
private InputStream is; private OutputStream os; private UserInfo userInfo;
private BAOS textRequest;
private Vector<String> answer_Vector = null; private String sRecord; //код объекта private String tempParam; public requestServlet() { super(); this.is = null; this.os = null; this.request = null; this.response = null; this.session = null; this.sessionID = null; this.enableGet = false; this.enablePost = false; this.checkUser = true; this.sRecord = null; this.tempParam = null; this.answer_Vector = new Vector<String>(); fireBirdLog_QueryTasks = LifecycleListener.getFireBirdLog_QueryTasks(); textRequest=new BAOS();
// this.textRequest.setLength(0); //AnswerCodeErr = ValueNormalCodeErr; }
public void destroy() { if (answer_Vector != null) answer_Vector.clear(); userActive.clear(); if (userInfo != null) userInfo.destroy(); this.textRequest.setLength(0); super.destroy(); }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { this.request = request; this.response = response; try { try { if (!this.enablePost) exceptError("Метод Post запрещен",getClass().toString(), Application_Exception.UnAccess_Method); make_Request();
} catch (Application_Exception e) { answer_Vector.clear(); answer_Vector.add(e.toString()); } catch (NullPointerException e) {log.info(" nullPointEx"); answer_Vector.clear(); answer_Vector.add(e.toString()); } } finally {
makeAnswer(); } }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { this.request = request; this.response = response; try { try { if (!this.enableGet) exceptError("Метод Get запрещен",getClass().toString(), Application_Exception.UnAccess_Method); make_Request();
} catch (Application_Exception e) { answer_Vector.clear(); answer_Vector.add(e.toString()); // if (AnswerCodeErr.equals(ValueNormalCodeErr)) AnswerCodeErr=ValueNotDeterminCodeErr; // май 2008 } } finally { makeAnswer(); } }
public void make_Request() throws Application_Exception { int countByte; byte[] readBuffer = new byte[Consts.BUFFER_SIZE];
try { this.request.setCharacterEncoding("windows-1251"); this.response.setCharacterEncoding("windows-1251"); } catch(Exception e) { exceptError("Не возможно установить кодировку", getClass().toString(), Application_Exception.Character_Encoding, e); }
this.session = request.getSession(); this.sessionID = session.getId(); try { this.is = new BufferedInputStream(request.getInputStream()); } catch (IOException e) { exceptError("Не возможно получить выходной поток", getClass().toString(), Application_Exception.IOException, e); } try { this.os = new BufferedOutputStream(response.getOutputStream()); } catch (IOException e) { exceptError("Не возможно получить входной поток", getClass().toString(), Application_Exception.IOException, e); } setUserName(request.getRemoteUser()); setSessionAttribute(NAME_USER_ATTRIBUTE,userName); userActive = UserActive.getUserActive(); this.userInfo = userActive.get(userName);
if (this.userInfo!=null) { this.session.setAttribute(COOKIE_CODE_RM, this.userInfo.getRM()); } // else log.error("userInfo пуст для пользователя"+userName); this.textRequest.setLength(0);
try { while((countByte = this.is.read(readBuffer)) != -1) this.textRequest.write(readBuffer,0,countByte); } catch (IOException e) { exceptError("Ошибка чтения входного потока", getClass().toString(), Application_Exception.IOException, e); }
if ((checkUser) & (this.userInfo == null)) throw new Application_Exception("Пользователь "+getSessionAttribute(NAME_USER_ATTRIBUTE).toString() +" не зарегистрирован в системе", getClass().toString(), Application_Exception.UnLogged_User); }
public void makeAnswer() throws IOException { makeCookies(); for (String answer_Str : answer_Vector) this.os.write(answer_Str.getBytes()); answer_Vector.clear(); this.os.close(); }
public void makeCookies() { // Cookie cookie = new Cookie("SessionID",sessionID); задваивался // response.addCookie(cookie); }
public String getCookies(String cookieName) { String ret_Value = null; Cookie cookie; Cookie[] cookies = this.request.getCookies(); int length = cookies.length;
for (int i=0; i<length; i++) { cookie = cookies[i]; if (cookie.getName().equals(cookieName)) { ret_Value = cookie.getValue(); break; } } return ret_Value; }
public void setSessionAttribute(String nameAttribute, Object attribute) { session.setAttribute(nameAttribute,attribute); }
public Object getSessionAttribute(String nameAttribute) { return session.getAttribute(nameAttribute); }
// private void removeSessionAttribute(String nameAttribute) { // session.removeAttribute(nameAttribute); // } //
public void unlogged_HTML() { this.answer_Vector.clear(); this.answer_Vector.add("Пользователь "+getSessionAttribute(NAME_USER_ATTRIBUTE).toString() +" не зарегистрирован в системе"); }
public void setEnableGet(Boolean enableGet) { this.enableGet = enableGet; }
public void setEnablePost(Boolean enablePost) { this.enablePost = enablePost; }
public void setCheckUser(Boolean checkUser) { this.checkUser = checkUser; }
public void ParsStr(String strTable, Hashtable<String, String> dataPerform ) throws Application_Exception { // разбор строки int posp, posValue, posEndValue;
int startPosp = 0; String subStr, nameParam, valueParam; do { posp = strTable.indexOf("/",startPosp); posEndValue = strTable.indexOf("/",posp+1); if (posp>=0) { if (posEndValue>0) subStr = strTable.substring(posp,posEndValue); else subStr = strTable.substring(posp); posValue=subStr.indexOf("="); if (posValue > 0) { nameParam = subStr.substring(1,posValue); valueParam = subStr.substring(posValue+1); startPosp = posEndValue; dataPerform.put(nameParam, valueParam); } else exceptError("Неправильная структура (нет =) в "+subStr,getClass().toString(),Application_Exception.ErrorStructure); } } while (posEndValue > 0); }
public void exceptError(String msg) throws Application_Exception { throw new Application_Exception(msg); }
public void exceptError(String msg, String className) throws Application_Exception { throw new Application_Exception(msg, className); }
public void exceptError(String msg, String className, String typeException) throws Application_Exception { throw new Application_Exception(msg, className, typeException); } public void exceptError(String msg, String className, String typeException, Exception exception) throws Application_Exception { throw new Application_Exception(msg, className, typeException, exception); } public void setRecord (String recor ){ this.sRecord=recor; } public String getRecord ( ){ return this.sRecord; } public void setTempParam (String param ){ this.tempParam=param; } public String getTempParam ( ){ return this.tempParam; }
public void setUserName (String dd ){ this.userName=dd; } public String getUserName ( ){ return this.userName; } //из строки даты 04/25/2007 находится строка даты на год раньше public String yearBack (String dat ){ String baskYear= String.valueOf(Integer.parseInt(dat.substring(6,10).toString())-1); if (dat.substring(0,5).equals("02/29")) return "02/28/"+baskYear; else return dat.substring(0,5).toString()+"/"+baskYear; }
public void setTextRequest(BAOS textRequest) { this.textRequest = textRequest; } public BAOS getTextRequest() { return this.textRequest; } public void answer_VectorClear() {this.answer_Vector.clear();}
public void answer_VectorAdd(String dd) {this.answer_Vector.add(dd);}
public int answer_VectorSize() { return this.answer_Vector.size();}
public String answer_VectorGet() { return this.answer_Vector.toString();}
public void setUserInfo(UserInfo userInfo) { this.userInfo = userInfo; } public UserInfo getUserInfo() { return this.userInfo; }
}
|
в вышепрведенном классе родители мне больше всего подозрительно использование куков Код | public String getCookies(String cookieName) { String ret_Value = null; Cookie cookie; Cookie[] cookies = this.request.getCookies(); int length = cookies.length;
for (int i=0; i<length; i++) { cookie = cookies[i]; if (cookie.getName().equals(cookieName)) { ret_Value = cookie.getValue(); break; } } return ret_Value; }
|
Код | public class CodeRMServlet extends requestServlet { public CodeRMServlet() { super(); setEnablePost(true); }
public void make_Request() throws Application_Exception { ResultSet resultSet = null; Connection connect= null; PreparedStatement preparedStatement=null;
super.make_Request();
this.setRecord(getCookies("OBJ_KEY")); if (this.getRecord() == null) exceptError("Недостаточно данных: не задан OBJ_KEY.", getClass().toString(), Application_Exception.Cookie_Error); log_Login.info("Вызов сервлета CodeRMServlet ТС "+this.getRecord()+" c CodeRM="+getCookies("CODERM")); // Подготовка соединения с БД try{ try { connect = DbAccess.getDbAccess().getConnection(); preparedStatement = connect.prepareStatement("SELECT ANSWER FROM SP_UPDATE_OBJ_REC_CODERM(?,?)"); connect.setAutoCommit(false); connect.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED); answer_VectorClear();
preparedStatement.setObject(1, Integer.parseInt(this.getRecord())); preparedStatement.setObject(2, getCookies("CODERM"));
resultSet = preparedStatement.executeQuery();
if (resultSet.next()) { answer_VectorAdd(resultSet.getObject("ANSWER").toString()); } else exceptError("Ошибка выполнения хранимой процедуры", getClass().toString(), Application_Exception.Empty_Answer); connect.commit(); } finally { connect.rollback(); if (resultSet != null) resultSet.close(); if (preparedStatement != null) preparedStatement.close(); if (connect != null) connect.close(); } } catch (SQLException e) { exceptError("Ошибка выполнения запроса", getClass().toString(), Application_Exception.SQLException, e); } catch(NumberFormatException e) { exceptError("Ошибка код ТС не число ", getClass().toString(), Application_Exception.Cookie_Error); }
} }
|
|