JavaEE程序设计与应用开发

发布于 / 技术 / 1 条评论

遇到的坑及填坑方法

1、jsp提交表单数据采用POST方式时出现中文传值乱码。

解决方法,强制转换。形式如下:

String stuname=request.getParameter("stuname");
stuname = new String(stuname.getBytes("ISO-8859-1"),"utf-8");

2、request.getParameterValues(String   name)是获得如checkbox类(名字相同,但值有多个)的数据。   接收数组变量,如checkobx类型     
request.getParameter(String   name)是获得相应名的数据,如果有重复的名,则返回第一个的值 . 接收一般变量 ,如text类型

3、三种连接数据库方法

  1. JDBC-ODBC桥连接
    Class.forName("sun.jdbc.odbc.JdbcDriver");
    Connection conn = DriverManager.getConnection(jdbc:odbc:数据源名称);
  2. 使用厂商驱动进行数据库连接
    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
    conn = DriverManager.getConnection("jdbc:sqlserver://[IP]:1433;database=数据库名","用户名","密码");

     

  3. 使用连接池访问数据库
package tool;

import org.apache.commons.dbcp2.BasicDataSourceFactory;
import org.junit.Test;

import javax.sql.DataSource;
import java.sql.*;
import java.util.Properties;

public class DBCPUtils {
    private  static DataSource ds;//定义一个连接池对象
    static {
        try{
            Properties pro=new Properties();
            pro.load(DBCPUtils.class.getClassLoader().getResourceAsStream("dbcpconfig.properties"));
            ds= BasicDataSourceFactory.createDataSource(pro);//得到一个连接池对象
        }catch (Exception e){
            throw new ExceptionInInitializerError("初始化连接错误,请检查配置文件");
        }
    }
    //从池中获取一个连接
    public static Connection getConnection()throws SQLException {
        return ds.getConnection();
    }

    public static void closeAll(ResultSet rs, Statement stmt,Connection conn){
        if(rs!=null){
            try{
                rs.close();
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
        if(stmt!=null){
            try{
                stmt.close();
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try{
                conn.close();//关闭
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
    }

    @Test
    public void testDBCP()throws Exception{
        Connection conn=getConnection();
        String sql="select * from info where eno=?";
        PreparedStatement ps=conn.prepareStatement(sql);
        ps.setString(1,"15051146");
        ResultSet result=ps.executeQuery();
        while(result.next()){
            String no=result.getString("eno");
            String name=result.getString("ename");
            String sex=result.getString("sex");
            System.out.println(no+" "+name+" "+sex);
        }
        ps.close();
        conn.close();
    }
}

 

#基本的设置
driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
url=jdbc:sqlserver://[IP]:1433;database=数据库名
username=sa
password=xuke19971217

#初始化时连接池中connection数量
initialSize=10

#最大连接数量
maxActive=50

#最大的空闲连接数量
maxIdle=20

#最小的空闲链接数量
minIdle=5

#最大的等待时间,单位是毫秒
maxWait=60000
#建立连接时的附加参数,如果指定的编码不一致数据库中会出现乱码
connectionProperties=useUnicode=true;characterEncoding=utf8

#是否开启自动提交,跟事务的控制有关
defaultAutoCommit=true

#指定由连接池所创建的连接的事务隔离级别(TransactionIsolation)。
defaultTransactionIsolation=REPEATABLE_READ

4、Ajax

<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2017/10/2
  Time: 18:29
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>ajax测试</title>
</head>
<body>
<script>
    function showInfo(){
        var xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");//1
        xmlHttp.open("get","info.jsp",true);
        xmlHttp.onreadystatechange=function () {
            if(xmlHttp.readyState==4){
                infoDiv.innerHTML=xmlHttp.responseText;
            }
        }
        xmlHttp.send();
    }
</script>
欢迎来到本系统
<hr>
<input type="button" value="显示公司信息" onclick="showInfo()">
<idv id="infoDiv"></idv>
</body>
</html>
<%--
  Created by IntelliJ IDEA.
  User: admin
  Date: 2017/10/2
  Time: 18:09
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>信息</title>
</head>
<body>
地址:北京市朝阳门外
<br>
电话:010-89765434
</body>
</html>

错误信息:

Uncaught ReferenceError: ActiveXObject is not defined
    at showInfo (welcome2.jsp:10)
    at HTMLInputElement.onclick (welcome2.jsp:22)
showInfo @ welcome2.jsp:10
onclick @ welcome2.jsp:22

解决方法:1、此对象为IE特有,请用IE打开测试ajax吧。反正没卵用。

2、将注释1处代码修改为:

var xmlHttp=new XMLHttpRequest();

4.1Ajax优点

  • 减轻服务器负担,避免整个浏览器窗口刷新时造成的重复请求。
  • 带来更好的用户体验。
  • 进一步促进页面呈现和数据本身的分离等。

4.2Ajax缺点

  • 对浏览器具有一定的限制,对于不兼容的浏览器可能无法使用。
  • Ajax没有刷新页面,浏览器上的“后退”按钮是失效的,因此,客户经常无法回退到以前的操作等。(Pjax解决)

5、DOM

  • flowers.xml
    <?xml version="1.0" encoding="gb2312"?>
    <flowers>
        <flower id="1">
            <name>玫瑰</name>
            <price>10</price>
        </flower>
        <flower id="2">
            <name>百合</name>
            <price>20</price>
        </flower>
        <flower id="3">
            <name>兰花</name>
            <price>15</price>
        </flower>
    </flowers>

     

  • 载入文档LoadXML.java
    package dom;
    
    import org.xml.sax.SAXException;
    import org.w3c.dom.Document;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import java.io.IOException;
    
    public class LoadXML {
        public static void main(String[] args) {
            DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
            DocumentBuilder db;
            try{
                db=dbf.newDocumentBuilder();
                Document doc=db.parse("flowers.xml");
                System.out.println("载入成功");
            }catch(ParserConfigurationException e){
                e.printStackTrace();
            }catch(SAXException e){
                e.printStackTrace();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
    

     

  • 利用DOM读取数据
  1. 利用Node读取数据ReadNode.java
    package dom;
    import  org.w3c.dom.Document;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    
    public class ReadNode {
        public static void main(String[] args) throws Exception{
            DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
            DocumentBuilder db=dbf.newDocumentBuilder();
            Document doc=db.parse("flowers.xml");
            //获取文档中的第一个子节点(即根节点)
            Node root=doc.getFirstChild();
            //打印结点名称
            System.out.println("根节点的名称为:"+root.getNodeName());
            //打印结点类型
            System.out.println("根结点类型为:"+root.getNodeType());
            //显示所有子节点
            NodeList list=root.getChildNodes();
            for(int i=0;i<list.getLength();i++){
                Node node=list.item(i);
                if(!(node.getNodeType()==Node.TEXT_NODE&&node.getTextContent().trim().length()==0)){
                    System.out.println("结点名称:"+node.getNodeName());
                }
            }
    
        }
    }
    

     

  2. 利用Document读取数据ReadDocument.java
    package dom;
    
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    
    public class ReadDocument {
        public static void main(String[] args) throws Exception{
            DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
            DocumentBuilder db=dbf.newDocumentBuilder();
            Document doc=db.parse("flowers.xml");
            //查询所有鲜花名称
            NodeList list=doc.getElementsByTagName("name");
            for(int i=0;i<list.getLength();i++){
                Node node=list.item(i);
                System.out.println(node.getTextContent());
            }
        }
    }
    

     

  3. 利用Element读取数据
    package dom;
    
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    
    public class ReadElement {
        public static void main(String[] args) throws Exception{
            DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
            DocumentBuilder db=dbf.newDocumentBuilder();
            Document doc=db.parse("flowers.xml");
            //查询所有鲜花
            NodeList list=doc.getElementsByTagName("flower");
            for(int i=0;i<list.getLength();i++){
                Element flower=(Element)list.item(i);
                Node priceNode=flower.getElementsByTagName("price").item(0);
                String strPrice=priceNode.getTextContent();
                double price=Double.parseDouble(strPrice);
                if(price>=10){
                    String id=flower.getAttribute("id");
                    Node nameNode=
                            flower.getElementsByTagName("name").item(0);
                    String name=nameNode.getTextContent();
                    System.out.println("id:"+id);
                    System.out.println("name:"+name);
                    System.out.println("price:"+price);
                    System.out.println("---------");
                }
            }
        }
    }
    

     

  • 利用DOM修改数据
  1. XML文件保存
    package dom;
    
    import org.w3c.dom.Document;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import java.io.File;
    
    public class WriteXML {
        public static void main(String[] args) throws Exception{
            //载入文件
            DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
            DocumentBuilder db=dbf.newDocumentBuilder();
            Document doc=db.parse("flowers.xml");
            //保存文件
            TransformerFactory tf=TransformerFactory.newInstance();
            Transformer transformer=tf.newTransformer();
            transformer.setOutputProperty("encoding","gb2312");
            DOMSource source=new DOMSource(doc);
            File file=new File("newFlowers.xml");
            StreamResult result=new StreamResult(file);
            transformer.transform(source,result);
            System.out.println("保存成功");
        }
    }
    

     

  2. 利用Node修改数据WriteNode.java
    package dom;
    
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import java.io.File;
    import java.util.ArrayList;
    
    public class WriteNode {
        public static void main(String[] args) throws Exception{
            DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
            DocumentBuilder db=dbf.newDocumentBuilder();
            Document doc=db.parse("flowers.xml");
            //查询所有价格
            NodeList list=doc.getElementsByTagName("price");
            ArrayList arrayList=new ArrayList();
            Node flowers=null;
            for(int i=0;i<list.getLength();i++){
                Node priceNode=list.item(i);
                String strPrice=priceNode.getTextContent();
                double price=Double.parseDouble(strPrice);
                //获取该价格的父节点(flower)
                Node flower=priceNode.getParentNode();
                //获取flower的父节点flowers
                flowers=flower.getParentNode();
                if(price>15){
                    arrayList.add(flower);
                }else{
                    //修改价格
                    String newPrice=String.valueOf(price-5);
                    priceNode.setTextContent(newPrice);
                }
            }
            for(int j=0;j<arrayList.size();j++){
                Node flower=(Node)arrayList.get(j);
                //从flowers中删除flower
                flowers.removeChild(flower);
            }
            //保存入文件
            TransformerFactory tf=TransformerFactory.newInstance();
            Transformer transformer=tf.newTransformer();
            transformer.setOutputProperty("encoding","gb2312");
            DOMSource source=new DOMSource(doc);
            File file=new File("newFlowers.xml");
            StreamResult result=new StreamResult(file);
            transformer.transform(source,result);
        }
    }
    

     

  3. 利用Document修改数据
  4. 利用Element修改数据WriteElement.java
    package dom;
    
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.NodeList;
    
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import java.io.File;
    
    public class WriteElement {
        public static void main(String[] args) throws Exception{
            //载入文件
            DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
            DocumentBuilder db=dbf.newDocumentBuilder();
            Document doc=db.parse("flowers.xml");
            //查询所有flower
            NodeList list=doc.getElementsByTagName("flower");
            for(int i=0;i<list.getLength();i++){
                Element flowerElement=(Element)list.item(i);
                //获取id属性
                String id=flowerElement.getAttribute("id");
                //删除id属性
                flowerElement.removeAttribute("id");
                //添加"编号"属性,值为原先的id属性
                flowerElement.setAttribute("编号",id);
            }
            //创建一个新元素
            Element newFlower=doc.createElement("flower");
            newFlower.setAttribute("编号","4");
            Element newName=doc.createElement("name");
            newName.setTextContent("康乃馨");
            newFlower.appendChild(newName);
            Element newPrice=doc.createElement("price");
            newPrice.setTextContent("23");
            newFlower.appendChild(newPrice);
            //得到根节点
            Element root=doc.getDocumentElement();
            //在根节点中添加newFlower
            root.appendChild(newFlower);
            //保存入文件
            TransformerFactory tf=TransformerFactory.newInstance();
            Transformer transformer=tf.newTransformer();
            transformer.setOutputProperty("encoding","gb2312");
            DOMSource source=new DOMSource(doc);
            File file=new File("newFlowers.xml");
            StreamResult result=new StreamResult(file);
            transformer.transform(source,result);
        }
    }
    

     

6、SAX

  1. SAX介绍
  • Simple API for XML的简称,和DOM相比,用SAX解析文档,无需将文档读入内存
  • 优点:节省内存,效率较高。
  • 缺点:编码不直观,只能对XML文件进行读,无法进行修改等。

2.载入文档SAXStartDocument.java

package sax;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

public class SAXStartDocument {
    public static void main(String[] args) throws Exception{
        SAXParserFactory spf=SAXParserFactory.newInstance();
        SAXParser saxParser=spf.newSAXParser();
        saxParser.parse("flowers.xml",new SAXParse1());
    }
}
class SAXParse1 extends DefaultHandler{
    public void startDocument() throws SAXException{
        System.out.println("开始解析文件");
    }
}
  • void startElement()
  • 当元素开始时,自动调用
    package sax;
    
    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;
    
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    
    public class SAXStartElement {
        public static void main(String[] args) throws Exception{
            SAXParserFactory spf=SAXParserFactory.newInstance();
            SAXParser saxParser=spf.newSAXParser();
            saxParser.parse("flowers.xml",new SAXParse2());
        }
    }
    class SAXParse2 extends DefaultHandler{
        public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException{
            System.out.println("发现元素,标签名称为:"+qName+"     ");
            for(int i=0;i<atts.getLength();i++){
                String attName=atts.getQName(i);
                String attValue=atts.getValue(attName);
                System.out.println(attName+"="+attValue+"    ");
            }
            System.out.println();
        }
    }
    

     

  • void characters()
  • 当遇到元素中字符数据时,自动调用。
    package sax;
    
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;
    
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    
    public class SAXCharacters {
        public static void main(String[] args) throws Exception{
            SAXParserFactory spf=SAXParserFactory.newInstance();
            SAXParser saxParser=spf.newSAXParser();
            saxParser.parse("flowers.xml",new SAXParse3());
        }
    }
    class SAXParse3 extends DefaultHandler{
        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
            String data=new String(ch,start,length).trim();
            if(data.length()!=0){
                System.out.println("发现一个字符串:"+data);
            }
        }
    }
    

     

  • void endElement()
  • 元素结束时,自动调用。
  • void endDocument()
  • 文档结束时,自动调用。

3.实现解析ReadFlowers.java

package sax;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import java.lang.String;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

public class ReadFlowers {
    public static void main(String[] args) throws Exception{
        SAXParserFactory spf=SAXParserFactory.newInstance();
        SAXParser saxParser=spf.newSAXParser();
        saxParser.parse("flowers.xml",new SAXParseFlower());
    }
}
class SAXParseFlower extends DefaultHandler{
    public void startDocument() throws SAXException{
        System.out.println("<?xml version='1.0' encoding='gb2312'?>");
    }

    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        System.out.print("<"+qName);
        for(int i=0;i<attributes.getLength();i++){
            String attName=attributes.getQName(i);
            String attValue=attributes.getValue(attName);
            System.out.print(" "+attName+"='"+attValue+"'");
        }
        System.out.print(">");
    }

    public void endElement(String uri, String localName, String qName) throws SAXException {
        System.out.print("</"+qName+">");
    }

    public void characters(char[] ch, int start, int length) {
        System.out.print(new String(ch,start,length).trim());
    }
}

运行结果:

<?xml version='1.0' encoding='gb2312'?>
<flowers><flower id='1'><name>玫瑰</name><price>10</price></flower><flower id='2'><name>百合</name><price>20</price></flower><flower id='3'><name>兰花</name><price>15</price></flower></flowers>
Process finished with exit code 0

 

  1. avatar

    Posologie Viagra 50 cialis Viagra 100 Wiki