把页面上select控件上选中的值传给服务端得servlet。
postingXML.html.html的代码如下
处理客户端请求的java代码PostExamplePets.java
- package ajaxbook.chap3;
-
- import java.io.BufferedReader;
- import java.io.ByteArrayInputStream;
- import java.io.IOException;
-
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.xml.parsers.DocumentBuilderFactory;
- import javax.xml.parsers.ParserConfigurationException;
-
- import org.w3c.dom.Document;
- import org.w3c.dom.NodeList;
- import org.xml.sax.SAXException;
-
- public class PostExamplePets extends HttpServlet{
-
-
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
- // TODO Auto-generated method stub
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
- String result = this.getRequestPets(req);
- Document xmlDoc = null;
-
- try {
-
- xmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().
- parse(new ByteArrayInputStream(result.getBytes()));
-
-
- } catch (SAXException e) {
- e.printStackTrace();
- } catch (ParserConfigurationException e) {
- e.printStackTrace();
- }
-
- NodeList selectedPetsType = xmlDoc.getElementsByTagName("type");
- StringBuilder sb = new StringBuilder("selected pet type are : ");
-
- for (int i = 0 ; i < selectedPetsType.getLength() ;i ++ ){
- sb.append(selectedPetsType.item(i).getFirstChild().getNodeValue()).append(" ");
- }
-
- res.setContentType("text/xml");
- res.getWriter().print(sb.toString());
- }
-
- private String getRequestPets(HttpServletRequest req) {
-
- StringBuilder sb = new StringBuilder();
- BufferedReader bufferedReader = null;
- try {
- bufferedReader = req.getReader();
- String line ;
- while((line=bufferedReader.readLine()) != null) {
- sb.append(line);
- }
- }
- catch (IOException e) {
- e.printStackTrace();
- } finally{
- try {
- bufferedReader.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return sb.toString();
- }
-
- }
阅读(960) | 评论(0) | 转发(0) |