Servlet 接受解析HTTP请求XML数据,返回XML
项目需要Servlet接受http提交过来的XML解析后,返回数据.
public void execute(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {Document document = null;SAXReader reader = new SAXReader();StringBuffer doc=new StringBuffer("<?xml version=");doc.append(request.getParameter("<?xml version"));InputStream inputStream = new ByteArrayInputStream(doc.toString().getBytes());XMLWriter writer = null; Document resDoc=null;try {document = reader.read(inputStream);if (document!= null) {Node objectType=document.selectSingleNode("//req/objectType");Node objectTitle=document.selectSingleNode("//req/objectTitle");if(objectTitle!=null&&objectType!=null&&objectType.getText().equals(Constants.VOTE.toString())){voteManager=(VoteManagerImpl)SpringWebUtils.getApplicationContext(request).getBean("voteManager");List votes=voteManager.loadAllByQuery(objectTitle.getText(),null, null, null, null, null, null);VoteDTO dto=null;if(votes.size()>0){dto=(VoteDTO)votes.get(0);dto=voteManager.load(dto.getVoteId());List<VoteOpt> opts=dto.getVoteOpts();resDoc = DocumentHelper.createDocument(); Element resElement = resDoc.addElement("res"); Element codeElement = resElement.addElement("code");codeElement.setText("0"); Element descElement =resElement.addElement("desc");descElement.setText("查询成功"); Element otElement =resElement.addElement("objectTitle");otElement.setText(dto.getVoteTitle()); Element optionsElement =resElement.addElement("options");for (Iterator iterator = opts.iterator(); iterator.hasNext();) {VoteOpt opt = (VoteOpt) iterator.next();Element optionElement =optionsElement.addElement("option");Element optValueElement =optionElement.addElement("optValue");optValueElement.setText(opt.getOptValue());Element optNameElement =optionElement.addElement("optName");optNameElement.setText(opt.getOptName());Element optCountElement =optionElement.addElement("optCount");optCountElement.setText(opt.getOptCount().toString());}}else{resDoc=getErrorDocument("没有此主题");}}else{resDoc=getErrorDocument("请求主题类型不正确");}}else{resDoc=getErrorDocument("请求报文格式错误");}} catch (Exception ex) {ex.printStackTrace();log.error(ex.toString());resDoc=getErrorDocument("请求处理出现错误:"+ex.toString());} finally {OutputFormat format = OutputFormat.createCompactFormat(); format.setEncoding("GBK"); writer = new XMLWriter(response.getOutputStream(), format); writer.write(resDoc); writer.close(); if (writer != null) {writer.close();}}}public Document getErrorDocument(String msg){Document resDoc = DocumentHelper.createDocument(); Element resElement = resDoc.addElement("res"); Element codeElement = resElement.addElement("code");codeElement.setText("-1"); Element descElement =resElement.addElement("desc");descElement.setText(msg); return resDoc;}1 楼 bmpbhg 2012-07-10 和你的类似,不过我这边报的是