尝试写了一个 JDBC 操作 SQLServer 的工具类,但是好像有问题,求大神帮忙指正

java新人,尝试写了一个 JDBC 操作 SQLServer 的工具类,但是好像有问题,调用 insert 指令没问题,而 select 指令出现如下报错:
com.microsoft.sqlserver.jdbc.SQLServerException: ')' 附近有语法错误。
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1515)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.doExecuteStatement(SQLServerStatement.java:792)
at com.microsoft.sqlserver.jdbc.SQLServerStatement$StmtExecCmd.doExecute(SQLServerStatement.java:689)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:180)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:155)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeQuery(SQLServerStatement.java:616)
at com.javaee.servletxm.comm.MSSQLJDBC.select(MSSQLJDBC.java:160)
at com.javaee.servletxm.comm.MSSQLJDBC.select(MSSQLJDBC.java:195)
at com.javaee.servletxm.comm.MSSQLJDBC.selectFirstValue(MSSQLJDBC.java:172)
at com.javaee.servletxm.comm.MSSQLJDBC.getPageNumber(MSSQLJDBC.java:221)
at com.javaee.servletxm.comm.MSSQLJDBC.selectByFY(MSSQLJDBC.java:259)
at com.javaee.servletxm.kqgl.KqManager.getAllKqxx(KqManager.java:38)
at com.javaee.servletxm.kqgl.Kqwh.doGet(Kqwh.java:47)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:879)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:617)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1760)
at java.lang.Thread.run(Thread.java:724)

这是具体的代码,求大神帮忙指正

package com.javaee.servletxm.comm;
/**

  • jdbc下 SQL Server 2005 数据库的封装类 */ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.Date; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.List; import java.util.Properties;

public class MSSQLJDBC {
// 配置文件名称
private String iniFileName = MSSQLJDBC.class.getClassLoader().getResource("/com/javaee/servletxm/comm").getPath()+ "mssql.properties";
// 连接数据库
private String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private String url = "jdbc:sqlserver://localhost;DatabaseName=jdms";
private String user = "sa";
private String password = "";

// 定义连接属性
private Connection connect = null;

// 与连接有关三个通道
private Statement stmt = null;
private PreparedStatement pstmt = null;
private CallableStatement cstmt = null;

public static final String stmtType = "stmt";
public static final String pstmtType = "pstmt";
public static final String cstmtType = "cstmt";

// 定义参数类型的静态常量值
public static final String varCharType = "varchar";
public static final String intType = "int";
public static final String doubleType = "decimal";
public static final String dateType = "datetime";
public static final String timeType = "timestamp";

// 定义全局的结果集
private ResultSet rs = null;

// 在构造方法中对属性进行初始化赋值操作
public MSSQLJDBC() {
    // 读取配置文件
    readIni();
    // 初始化连接
    initConnect();
}

// 可配置文件 .properties
// 读取配置文件
private void readIni() {
    File file = new File(iniFileName);
    if (!file.exists()) {
        // 创建一个文件
        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 判断文件是否有值
    if (file.length() == 0) {// 说明是一个空文件
        // 初始化值
        try {
            Properties p = new Properties();
            p.put("driver", driver);
            p.put("url", url);
            p.put("user", user);
            p.put("password", password);
            FileOutputStream fos = new FileOutputStream(file);
            p.store(fos, "配置文件信息");
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {// 如果有值
        // 将信息读取出来
        try {
            FileInputStream fis = new FileInputStream(file);
            Properties p = new Properties();
            p.load(fis);
            this.driver = p.getProperty("driver");
            this.url = p.getProperty("url");
            this.user = p.getProperty("user");
            this.password = p.getProperty("password");
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

// 建立连接
private void initConnect() {
    try {
        Class.forName(driver);
        this.connect = DriverManager.getConnection(url, user, password);
        this.connect.setAutoCommit(false);// 设置手动提交事务
        this.stmt = connect.createStatement();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

/*/ 从tomcat缓冲池获取连接
private void initConnectFromDataSource() {
    try {
        InitialContext ic = new InitialContext();
        DataSource ds = (DataSource) ic.lookup("java:comp/env/jdbc/oracleds");
        this.connect = ds.getConnection();
        this.connect.setAutoCommit(false);
        this.stmt = connect.createStatement();
    } catch (NamingException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}*/

// 需要调用者控制事务的两个方法
// 提交方法
private void commit() {
    try {
        this.connect.commit();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

// 回滚事务
private void rollBack() {
    try {
        this.connect.rollback();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

// 定义一组与操作有关的方法
// 使用普通通道执行的select
public ResultSet select(String sql) {
    ResultSet prs = null;
    if (stmt != null) {
        try {
            prs = stmt.executeQuery(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    return prs;
}

// 根据传入的sql直接获取单一值
// 使用此方法的时候sql语句返回的单一的值
public String selectFirstValue(String sql, String type, List<String> csList) {
    String rstr = "";
    rs = select(sql, type, csList);// 确定此结果集只有一条记录
    if (rs != null) {// 说明结果集有值,且只有一条记录
        try {
            ResultSetMetaData rsmd = rs.getMetaData();
            if (rs.next()) { // 移动到第一条记录
                String p_type = rsmd.getColumnTypeName(1);
                rstr = getResultSetValue(rs, 1, p_type);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    return rstr;
}

// 使用普通通道执行的select
/**
 * sql 参数 type 使用通道的类型 stmt pstmt cstmt List<String> csList 预编通道执行的参数队列
 * String 最少必须满足如下条件的字符串 数据类型 ,数据值 数据类型定义说明 字符串 数字(整数、小数) 日期(DATE、TIMESTAMP)
 */
public ResultSet select(String sql, String type, List<String> csList) {
    ResultSet prs = null;
    if (type.equals(stmtType)) {// 说明使用普通通道来执行
        prs = select(sql);
    } else if (type.equals(pstmtType)) {// 说明使用预编译通道来执行
        if (connect != null) {
            try {
                pstmt = connect.prepareStatement(sql);
                // 验证传入的参数和sql中的参数个数一致

                setPrepareStatement(pstmt, csList);// 将参数设置进当前的预编译通道

                prs = pstmt.executeQuery();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    return prs;
}

// 获取 总页数
public int getPageNumber(String sql, String type, List<String> csList,
        int pageSize) {
    // 处理总页数
    int pageNumber = 0;

    // 第一步获取sql总记录数
    String psql = "select count(*) from (" + sql + ")";
    String result = selectFirstValue(psql, type, csList);
    int rows = 0;
    if (result != null && result.trim() != "") {
        rows = Integer.valueOf(result);
    }

    if (rows % pageSize == 0) {
        pageNumber = rows / pageSize;
    } else {
        pageNumber = rows / pageSize + 1;
    }
    return pageNumber;
}

/**
 * 自动添加分页查询方法
 * 
 * @param sql
 *            要执行的sql
 * @param type
 *            执行方式
 * @param csList
 *            参数列表
 * @param curPage
 *            当前页数
 * @param pageSize
 *            每页记录数 默认为10
 * @return
 */
public ResultSet selectByFY(String sql, String type, List<String> csList,
        int curPage, int pageSize) {
    ResultSet prs = null;

    // 处理 每页记录数
    if (pageSize <= 0) {
        pageSize = 10;// 默认页面10条记录
    }

    int pageNumber = getPageNumber(sql, type, csList, pageSize);

    // 处理当前页数
    if (curPage < 0) {
        curPage = 1;// 默认第一页
    }
    if (curPage > pageNumber) {
        curPage = pageNumber;
    }

    String psql = "select tmpaa.* from (select tmpa.*,(select (ROW_NUMBER() over (order by id))) as rn from ("
            + sql + ") tmpa where (select (ROW_NUMBER() over (order by id))) <= " + (curPage * pageSize)
            + ") tmpaa where tmpaa.rn >= " + ((curPage - 1) * pageSize + 1);
    prs = select(psql, type, csList);

    return prs;
}

// 将预编通道执行的参数队列按照指定规则设置进通道中
private void setPrepareStatement(PreparedStatement p, List<String> csList)
        throws Exception {
    if (csList != null && csList.size() > 0) {
        for (int i = 0; i < csList.size(); i++) {
            // 此处的str是数据类型 ,数据值
            // 解析出数据类型和数据值
            String[] s = csList.get(i).split(",");
            String sType = s[0];
            String sData = s[1];
            if (varCharType.equals(sType)) {
                p.setString(i + 1, sData);
            } else if (intType.equals(sType)) {
                p.setInt(i + 1, Integer.valueOf(sData));
            } else if(doubleType.equals(sType)){
                p.setDouble(i+1, Double.valueOf(sData));
            } else if (dateType.equals(sType)) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
                java.util.Date d = sdf.parse(sData);
                p.setDate(i + 1, new Date(d.getTime()));
            } else if (timeType.equals(sType)) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
                java.util.Date d = sdf.parse(sData);
                p.setTimestamp(i + 1, new Timestamp(d.getTime()));
            }
        }
    }
}

// 定义一个执行insert update delete的方法
public int iudSql(String sql) {
    int ri = -1;
    if (stmt != null) {
        try {
            ri = stmt.executeUpdate(sql);
            commit();
        } catch (SQLException e) {
            e.printStackTrace();
            rollBack();
        }
    }
    return ri;
}

public int iudSql(String sql, String type, List<String> csList) {
    int ri = -1;
    if (stmtType.equals(type)) {
        ri = iudSql(sql);
    } else if (pstmtType.equals(type)) {
        if (connect != null) {
            try {
                pstmt = connect.prepareStatement(sql);
                setPrepareStatement(pstmt, csList);
                ri = pstmt.executeUpdate();
                commit();
            } catch (Exception e) {
                e.printStackTrace();
                rollBack();
            }
        }
    }
    return ri;
}

/**
 * 编写一个通用的遍历ResultSet结果集的方法
 */
public void iteratorResultSet(ResultSet rs) {
    try {
        if (rs != null) {// 说明有值
            // ResultSetMetaData 此对象里封装了与结果集有关所有信息
            // 此结果有几列组成,每列的列名,每列的数据类型
            ResultSetMetaData rsmd = rs.getMetaData();
            // 得到结果集列数
            int columnCount = rsmd.getColumnCount();
            // 输出此结果集的所有列名
            for (int i = 1; i <= columnCount; i++) {
                System.out.print(rsmd.getColumnName(i) + "\t");
            }
            System.out.println("");
            // 遍历输出所有的数据
            while (rs.next()) {
                // 如何在获取rs中的数据?
                for (int i = 1; i <= columnCount; i++) {
                    String type = rsmd.getColumnTypeName(i);
                    System.out.print(getResultSetValue(rs, i, type) + "\t");
                }
                System.out.println("");
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

// 从ResultSet中根据数据类型来得到数据值的方法
// 先处理常用的sqlserver的数据类型的对应
private String getResultSetValue(ResultSet rs, int index, String type) {
    String rstr = "";
    try {
        if (rs != null && !"".equals(type) && index > 0) {
            if ("char".equals(type.trim()) || "varchar".equals(type.trim())) {
                if (rs.getString(index) != null) {
                    rstr = rs.getString(index);
                }
            } else if ("int".equals(type.trim())) {
                    rstr = rs.getInt(index) + "";
            } else if ("decimal".equals(type.trim())) {
                    rstr = String.valueOf(rs.getDouble(index));
            } else if ("date".equals(type.trim())) {
                Date date = rs.getDate(index);
                if (date != null) {
                    rstr = new SimpleDateFormat("yyyy年MM月dd日").format(date);
                }
            } else if ("timestamp".equals(type.trim()) || "datetime".equals(type.trim())) {
                Timestamp tt = rs.getTimestamp(index);
                if (tt != null) {
                    rstr = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒").format(tt);
                }
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return rstr;
}

/*
//统一事务管理的批量sql的封装 
public boolean iudSql(List<String> sqlList){ 
    int ri = -1; 
    if(stmt!=null){ 
        try { 
            ri = stmt.executeUpdate(sql); 
            commit(); 
        } catch (SQLException e) { 
            e.printStackTrace(); 
            rollBack(); 
        } 
    } 
    return ri; 
}*/


// 关闭连接
public void close() {
    try {
        // 关闭所有的与数据库有关的对象
        if (rs != null) {
            rs.close();
            rs = null;
        }
        if (stmt != null) {
            stmt.close();
            stmt = null;
        }
        if (pstmt != null) {
            pstmt.close();
            pstmt = null;
        }
        if (cstmt != null) {
            cstmt.close();
            cstmt = null;
        }
        if (connect != null) {
            connect.close();
            connect = null;
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

}

1个回答

-_-!
查询语句有问题
每次执行sql前把sql语句打印出来,仔细排查下

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
怎样用java做一个分页工具类

每页显示10,20,50,100条数据。因为好几个页面都需要用到分页,因此希望抽取出来,怎么做呢

java用ant.jar工具类执行sql脚本遇到问题

最近在研究用工具类ant.jar执行sql脚本文件,一般对数据和字段的操作都无问题,但当要执行生成触发器或者存储过程时却出错,有大神做过这方面的吗?或者用其他方法可以执行能生成存储过程和触发器的sql脚本?求解!新人无币,望见谅~ ``` Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1 at org.apache.tools.ant.taskdefs.SQLExec.execute(SQLExec.java:672) at execSQL.AntExecSql.main(AntExecSql.java:38) Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:526) at com.mysql.jdbc.Util.handleNewInstance(Util.java:409) at com.mysql.jdbc.Util.getInstance(Util.java:384) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3562) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3494) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1960) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2114) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2690) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2619) at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:783) at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:626) at org.apache.tools.ant.taskdefs.SQLExec.execSQL(SQLExec.java:775) at org.apache.tools.ant.taskdefs.SQLExec.runStatements(SQLExec.java:745) at org.apache.tools.ant.taskdefs.SQLExec$Transaction.runTransaction(SQLExec.java:1055) at org.apache.tools.ant.taskdefs.SQLExec$Transaction.access$000(SQLExec.java:985) at org.apache.tools.ant.taskdefs.SQLExec.execute(SQLExec.java:653) ... 1 more ```

关于maven项目导入jdbc驱动的问题

这是我在maven项目下创建的一个工具类,想要在某些操作后向mysql数据库导入信息 ![图片说明](https://img-ask.csdn.net/upload/201806/28/1530166852_26878.png) 运行之前我导入过mysql的包 ![图片说明](https://img-ask.csdn.net/upload/201806/28/1530166919_122838.png) 但是运行时,jdbc的驱动一直无法加载成功,代码没有被运行 后来我在网上查了查,当修改pom.xml时又会报错 ![图片说明](https://img-ask.csdn.net/upload/201806/28/1530167308_912958.png) 想问问还有没有什么办法能加载起jdbc的驱动?

关于preparedstatement.executeUpdate方法

我在自己写一个JDBC工具类。但卡在了update方法的实现。工具类目前的代码如下: public final class HDBTools { // 数据库url,username,password private static String URL = "jdbc:mysql://localhost:3306/shiyan?" + "useUnicode=true&characterEncoding=UTF8"; private static String URN = "root"; private static String PSW = "root"; private static HDBTools hdb = null; private HDBTools(){} // 单例模式 public static HDBTools getHDBTools() { // 延迟加载 if (hdb == null) { // 双重锁,防止多个线程同时访问 synchronized (HDBTools.class) { // 双重锁,调度程序的偶然情况 if (hdb == null) { hdb = new HDBTools(); } } } return hdb; } // 静态代码块 static { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } // 链接 private Connection conn = null; // 结果集 private ResultSet resultSet = null; // 语句 private PreparedStatement preparedstatement = null; //get the connection of database private Connection getConn() throws SQLException { return DriverManager.getConnection(URL, URN, PSW); } public List<Map<String,Object>> findAll(String sql,Object[] objs) throws SQLException{ List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); conn = getConn(); preparedstatement = (PreparedStatement) conn.prepareStatement(sql); for(int i = 0;i<objs.length;i++){ preparedstatement.setObject(i+1, objs[i]); } resultSet = (ResultSet) preparedstatement.executeQuery(); ResultSetMetaData rsmd = preparedstatement.getMetaData(); // 取得结果集列数 int columnCount = rsmd.getColumnCount(); Map<String, Object> data = null; while(resultSet.next()){ data = new HashMap<String, Object>(); // 每循环一条将列名和列值存入Map for (int i = 1; i < columnCount; i++) { data.put(rsmd.getColumnLabel(i), resultSet.getObject(rsmd.getColumnLabel(i))); } // 将整条数据的Map存入到List中 list.add(data); } close(resultSet, preparedstatement, conn); return list; } public int update(String sql,Object[] objs) throws SQLException{ conn = getConn(); preparedstatement = (PreparedStatement) conn.prepareStatement(sql); for(int i = 0;i<objs.length;i++){ preparedstatement.setObject(i+1, objs[i]); } System.out.println(preparedstatement); int rows = preparedstatement.executeUpdate(sql); close(resultSet, preparedstatement, conn); return rows; } public void close(ResultSet rs, PreparedStatement pst, Connection conn) { try { if (rs != null) { rs.close(); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (pst != null) { pst.close(); } } catch (SQLException e) { e.printStackTrace(); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } } } 测试代码如下: HDBTools hdbt = HDBTools.getHDBTools(); int i = hdbt.update("insert into stu (name,address,money) values (?,?,?)", new Object[]{"hanshuai","changchun",10000}); System.out.println(i); 运行测试代码,预处理完成的SQL语句以及出现的异常如下: com.mysql.jdbc.PreparedStatement@14b2db7: insert into stu (name,address,money) values ('hanshuai','changchun',10000) Exception in thread "main" com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?,?,?)' at line 1 at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2941) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1623) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1715) at com.mysql.jdbc.Connection.execSQL(Connection.java:3243) at com.mysql.jdbc.Statement.executeUpdate(Statement.java:1343) at com.mysql.jdbc.Statement.executeUpdate(Statement.java:1260) at com.shuai.utils.jdbc.HDBTools.update(HDBTools.java:101) at com.shuai.utils.jdbc.Demo.main(Demo.java:12) 异常说,我的SQL 语句有问题,但是我将预处理后的SQL语句输出到控制台(见控制台结果第一行),将控制台SQL语句拷贝到SQL yang 中,运行数据添加成功。也就是说SQL语句没有问题。我感觉是我对preparedstatement.executeUpdate方法的理解出现了问题。希望各路大神不吝赐教。

请问大神在数据库中可以执行的sql语句,为什么通过java类连接数据库执行报错

报错信息: java.sql.SQLException: Already closed.

我用Eclipse开发birt报表时数据源连接不上数据库同事却可以 望大神看看

驱动也加了的 ![图片说明](https://img-ask.csdn.net/upload/201607/13/1468373073_365575.png) 点击test Connection 报 java.lang.NoClassDefFoundError: sun/io/UnknownCharacterException at com.ibm.db2.jcc.b.a.<init>(a.java:238) at com.ibm.db2.jcc.b.b.a(b.java:1624) at com.ibm.db2.jcc.c.p.a(p.java:350) at com.ibm.db2.jcc.c.p.<init>(p.java:404) at com.ibm.db2.jcc.b.b.<init>(b.java:256) at com.ibm.db2.jcc.DB2Driver.connect(DB2Driver.java:163) at org.eclipse.birt.report.data.oda.jdbc.JDBCDriverManager$WrappedDriver.connect(JDBCDriverManager.java:1271) at org.eclipse.birt.report.data.oda.jdbc.JDBCDriverManager.doConnect(JDBCDriverManager.java:306) at org.eclipse.birt.report.data.oda.jdbc.JDBCDriverManager.getConnection(JDBCDriverManager.java:209) at org.eclipse.birt.report.data.oda.jdbc.JDBCDriverManager.tryCreateConnection(JDBCDriverManager.java:824) at org.eclipse.birt.report.data.oda.jdbc.JDBCDriverManager.testConnection(JDBCDriverManager.java:745) at org.eclipse.birt.report.data.oda.jdbc.JDBCDriverManager.testConnection(JDBCDriverManager.java:641) at org.eclipse.birt.report.data.oda.jdbc.JDBCDriverManager.testConnection(JDBCDriverManager.java:613) at org.eclipse.birt.report.data.oda.jdbc.JDBCDriverManager.testConnection(JDBCDriverManager.java:681) at org.eclipse.birt.report.data.oda.jdbc.ui.util.DriverLoader.testConnection(DriverLoader.java:147) at org.eclipse.birt.report.data.oda.jdbc.ui.util.DriverLoader.testConnection(DriverLoader.java:175) at org.eclipse.birt.report.data.oda.jdbc.ui.profile.JDBCSelectionPageHelper.testConnection(JDBCSelectionPageHelper.java:961) at org.eclipse.birt.report.data.oda.jdbc.ui.profile.JDBCSelectionPageHelper.access$11(JDBCSelectionPageHelper.java:929) at org.eclipse.birt.report.data.oda.jdbc.ui.profile.JDBCSelectionPageHelper$8.widgetSelected(JDBCSelectionPageHelper.java:852) at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:248) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4353) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1061) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4172) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3761) at org.eclipse.jface.window.Window.runEventLoop(Window.java:832) at org.eclipse.jface.window.Window.open(Window.java:808) at org.eclipse.birt.report.designer.ui.dialogs.BaseDialog.open(BaseDialog.java:111) at org.eclipse.birt.report.designer.data.ui.providers.EditableDataSourceNodeProvider.performEdit(EditableDataSourceNodeProvider.java:73) at org.eclipse.birt.report.designer.internal.ui.views.DefaultNodeProvider.performRequest(DefaultNodeProvider.java:472) at org.eclipse.birt.report.designer.internal.ui.views.actions.EditAction.doAction(EditAction.java:85) at org.eclipse.birt.report.designer.internal.ui.views.actions.AbstractElementAction.run(AbstractElementAction.java:70) at org.eclipse.birt.report.designer.internal.ui.views.RenameListener.doubleClick(RenameListener.java:214) at org.eclipse.jface.viewers.StructuredViewer$1.run(StructuredViewer.java:831) at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42) at org.eclipse.ui.internal.JFaceUtil$1.run(JFaceUtil.java:50) at org.eclipse.jface.util.SafeRunnable.run(SafeRunnable.java:178) at org.eclipse.jface.viewers.StructuredViewer.fireDoubleClick(StructuredViewer.java:828) at org.eclipse.jface.viewers.AbstractTreeViewer.handleDoubleSelect(AbstractTreeViewer.java:1472) at org.eclipse.jface.viewers.StructuredViewer$4.widgetDefaultSelected(StructuredViewer.java:1237) at org.eclipse.jface.util.OpenStrategy.fireDefaultSelectionEvent(OpenStrategy.java:252) at org.eclipse.jface.util.OpenStrategy.access$0(OpenStrategy.java:249) at org.eclipse.jface.util.OpenStrategy$1.handleEvent(OpenStrategy.java:311) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4353) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1061) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4172) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3761) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$9.run(PartRenderingEngine.java:1151) at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1032) at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:148) at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:636) at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:579) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:150) at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:135) at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:382) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:236) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:648) at org.eclipse.equinox.launcher.Main.basicRun(Main.java:603) at org.eclipse.equinox.launcher.Main.run(Main.java:1465) Caused by: java.lang.ClassNotFoundException: sun.io.UnknownCharacterException at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) ... 69 more

Hibernate的根据实体自动生成表

刚学hibernate,有很多地方不是很懂,跟着视频敲,但那个视频用的是ecplise,我用的是Myecplise,然后 他可以创建一个hbm.xml指明映射关系,然后我不行,我只能根据实体创建出表,然后我在Hibernate.cfg.xml中加入了 <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="connection.url">jdbc:mysql://localhost:3306/websourse</property> <property name="connection.username">root</property> <property name="connection.password">123456</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="myeclipse.connection.profile">TTT</property> <property name="show_sql">true</property> <property name="format_sql">true</property> <property name="hibernate.hbm2ddl.auto">create</property> <mapping class="Students"></mapping> 然后在websource中也没见到这张表![不知道哪里有问题](https://img-ask.csdn.net/upload/201701/10/1484045291_40259.png)

发现一个神奇的问题 prepareStatement setString方法的问题

import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class noSelect_Test { /* * 非查询sql语句 */ public static int nonSelect(String sql,String...args){ System.out.println( args.length); //通过工具类获取数据库连接 Connection conn=DBUtils.getConnection(); PreparedStatement ps=null; int rs = 0; try { ps= conn.prepareStatement(sql); for(int i=1;i<=args.length;i++){ int c=i; /* System.out.println( args.length); System.out.println(i); System.out.println(u); ps.setString(i++, u);*/ System.out.println(i); System.out.println(args[c-1]); ps.setString(i, args[c-1]); } rs=ps.executeUpdate(sql); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ DBUtils.close(null, ps, conn); } return rs; } public static void main(String args[]){ String sql="insert into t_login (username,userpwd)values(?,?)"; nonSelect(sql,"57656","25456"); } } 以上是操作 下面是 2 kaishi 1 57656 57656 2 25456 25456 com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?,?)' at line 1 at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:526) at com.mysql.jdbc.Util.handleNewInstance(Util.java:409) at com.mysql.jdbc.Util.getInstance(Util.java:384) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3566) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3498) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2113) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2562) at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1664) at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1583) at com.vince.jdbc.noSelect_Test.nonSelect(noSelect_Test.java:35) at com.vince.jdbc.noSelect_Test.main(noSelect_Test.java:49) 你们说该怎么搞

java.io.StreamCorruptedException: invalid stream header: 77327070是什么情况如何解决?

springboot+datajpa+sqlserver报Caused by: invalid stream header: 77327070是什么情况如何解决? 刚接触springboot+jpa的小白,拜求各路大神的帮忙: 开发工具是eclipse: 没写controller层,先用junit测试crud(即增删改查)中其中的修改和删除,不能用,代码如下: 实体编译好后 1.首先JpaRepository层用的完全是继承JpaRepository的借口自带方法,出查询外没用自定义任何修改: @Repository @Transactional public interface sd extends JpaRepository<sd, String>{ Page<sd> findAll(Pageable pageable); } ```2.service 层是: @Override @Modifying @Transactional public void delete(String pid) { // TODO Auto-generated method stub cd.deleteById(pid); } @Override public boolean update(sd sf) { // TODO Auto-generated method stub cd.save(cfb); return true; } 3.测试类中: @Test @Modifying @Transactional public void deletepro() { cps.delete("fef232"); } @Test public void querypro() { /* int page=1,size=10; Sort sort = new Sort(Direction.DESC, "pid"); Pageable pageable = new PageRequest(page, size, sort); System.out.println(cps.findByPages(pageable));*/ } ``4.具体报错为: **org.hibernate.type.SerializationException: could not deserialize** at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_191] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_191] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_191] .......(太长了懒得粘了省略) **Caused by: java.io.StreamCorruptedException: invalid stream header: 77327070 ** at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:866) ~[na:1.8.0_191] at java.io.ObjectInputStream.<init>(ObjectInputStream.java:358) ~[na:1.8.0_191] at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:309) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final] at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:299) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final] at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:218) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final] ... 110 common frames omitted 5,配置用的是:application.properties 具体是: #port is update server.port=8080 #connection spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver spring.datasource.url=jdbc:sqlserver://localhost:1433;DatabaseName=tzc12 spring.datasource.username=sa1 spring.datasource.password=qq hibernate.dialect=org.hibernate.dialect.SQLServerDialect spring.jpa.properties.hibernate.show_sql=true spring.jpa.hibernate.ddl-auto = update # Naming strategy spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy #controller spring.mvc.view.prefix=/ spring.mvc.view.suffix=.jsp #Connection Pool spring.datasource.initialSize=5 spring.datasource.minIdle=5 spring.datasource.maxActive=20 spring.datasource.maxWait=60000 spring.datasource.timeBetweenEvictionRunsMillis=60000 spring.datasource.minEvictableIdleTimeMillis=300000 spring.datasource.validationQuery=SELECT 1 FROM DUAL spring.datasource.testWhileIdle=true spring.datasource.testOnBorrow=false spring.datasource.testOnReturn=false ``` 除外,测试查询方法时junit未报错,但出现了以下情况是什么原因?如何解决: JpaRepository层看最上面 service层: @Override public Page<sd> findByPages(Pageable pageable) { // TODO Auto-generated method stub return cd.findAll(pageable); } @Test public void querypro() { int page=1,size=10; Sort sort = new Sort(Direction.DESC, "pid"); Pageable pageable = new PageRequest(page, size, sort); System.out.println(cps.findByPages(pageable)); } 结果出来为: Page 2 of 1 containing UNKNOWN instances 更新后: 实体类: sd为主表,cds为附表,即cds 的主键是sd的外键。 @Entity @Table(name="cftbiop") public class sd implements Serializable{ /** * */ private static final long serialVersionUID = 8786038170195933216L; @Id private String pid=(UUID.randomUUID().toString()) ; private String pname ; private String introduction; private String marque; private String showcase; private String waytoraise ; private int suppot; private int raisefunds ; private int goalnum ; private cds showid; @ManyToOne @JoinColumn(name="showid") public cds getShowid() { return showid; } public void setShowid(CFShowProspecification showid) { this.showid = showid; } private boolean homepagedisplay; private int price; 其余getter,setter省略不粘了,都已getter,setter, 测试查询方法,把page改为0后,报了和删除,修改一样的错误

java.lang.NoClassDefFoundError

package hx.nan.JDBCUtils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ResourceBundle; public class DBConnection { public static String URL; public static String USERNAME; public static String PASSWORD; public static String DRIVER; private DBConnection(){} static{ ResourceBundle rb = ResourceBundle.getBundle("JDBCUtils.jdbc_config"); URL = rb.getString("URL"); USERNAME = rb.getString("USERNAME"); PASSWORD = rb.getString("PASSWORD"); DRIVER = rb.getString("DRIVER"); try { Class.forName(DRIVER); } catch (ClassNotFoundException e) { System.out.println("驱动加载失败"); e.printStackTrace(); } } public static Connection getConnection(){ Connection con = null; try { con = DriverManager.getConnection(URL,USERNAME,PASSWORD); } catch (SQLException e) { e.printStackTrace(); System.out.println("获取数据库连接失败"); } return con; } public static void close(ResultSet rs,Statement state,Connection con){ try { if(rs!=null){ rs.close(); } state.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); } } } java.lang.NoClassDefFoundError: Could not initialize class hx.nan.JDBCUtils.DBConnection hx.nan.JDBCUtils.JdbcTemplete.update(JdbcTemplete.java:30) hx.nan.Dao.UserDaoImp.add(UserDaoImp.java:33) hx.nan.action.RegisterAction.doPost(RegisterAction.java:29) javax.servlet.http.HttpServlet.service(HttpServlet.java:648) javax.servlet.http.HttpServlet.service(HttpServlet.java:729) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) 如果没有静态块的话不会报错,正常运行,这是怎么回事?而且try catch也没有捕获到异常

使用spring时,无法注入(提示:java.lang.NullPointerException)

异常信息如下: org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:408) org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:360) javax.servlet.http.HttpServlet.service(HttpServlet.java:710) javax.servlet.http.HttpServlet.service(HttpServlet.java:803) org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:78) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:77) root cause java.lang.NullPointerException com.test.dao.jdbc.UserDAO.insert(UserDAO.java:11) com.test.controller.LoginController.onSubmit(LoginController.java:21) org.springframework.web.servlet.mvc.SimpleFormController.onSubmit(SimpleFormController.java:408) org.springframework.web.servlet.mvc.SimpleFormController.onSubmit(SimpleFormController.java:380) org.springframework.web.servlet.mvc.SimpleFormController.processFormSubmission(SimpleFormController.java:267) org.springframework.web.servlet.mvc.AbstractFormController.handleRequestInternal(AbstractFormController.java:250) org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:153) org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter.handle(SimpleControllerHandlerAdapter.java:45) org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:820) org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:755) org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:396) org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:360) javax.servlet.http.HttpServlet.service(HttpServlet.java:710) javax.servlet.http.HttpServlet.service(HttpServlet.java:803) org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:78) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:77) web.xml &lt;display-name&gt;TestDemo&lt;/display-name&gt; &lt;context-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt;/WEB-INF/applicationContext.xml&lt;/param-value&gt; &lt;/context-param&gt; &lt;servlet&gt; &lt;servlet-name&gt;context&lt;/servlet-name&gt; &lt;servlet-class&gt;org.springframework.web.context.ContextLoaderServlet&lt;/servlet-class&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;filter&gt; &lt;filter-name&gt;encodingFilter&lt;/filter-name&gt; &lt;filter-class&gt; org.springframework.web.filter.CharacterEncodingFilter &lt;/filter-class&gt; &lt;init-param&gt; &lt;param-name&gt;encoding&lt;/param-name&gt; &lt;param-value&gt;UTF-8&lt;/param-value&gt; &lt;/init-param&gt; &lt;/filter&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;encodingFilter&lt;/filter-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;servlet&gt; &lt;servlet-name&gt;dispatcherServlet&lt;/servlet-name&gt; &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;dispatcherServlet&lt;/servlet-name&gt; &lt;url-pattern&gt;*.do&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; applicationContext.xml: &lt;bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt; &lt;property name="driverClassName" value="com.microsoft.jdbc.sqlserver.SQLServerDriver"&gt; &lt;property name="url" value="jdbc:sqlserver://localhost:1433;databaseName=test"&gt; &lt;property name="username" value="sa"&gt; &lt;property name="password" value=""&gt; &lt;/bean&gt; &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"&gt; &lt;property name="dataSource" ref="dataSource"&gt;&lt;/property&gt; &lt;property name="mappingResources"&gt; &lt;list&gt; &lt;value&gt;com/test/domain/User.hbm.xml&lt;/value&gt; &lt;/list&gt; &lt;/property&gt; &lt;property name="hibernateProperties"&gt; &lt;props&gt; &lt;prop key="hibernate.dialect"&gt;org.hibernate.dialect.SQLServerDialect&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="userDAO" class="com.test.dao.jdbc.UserDAO"&gt; &lt;property name="sessionFactory" ref="sessionFactory"&gt; &lt;/bean&gt; dispatcherServlet-servlet.xml: &lt;bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt; &lt;property name="prefix" value="/"&gt;&lt;/property&gt; &lt;property name="suffix" value=".jsp"&gt;&lt;/property&gt; &lt;/bean&gt; &lt;bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"&gt; &lt;property name="mappings"&gt; &lt;props&gt; &lt;prop key="/login.do"&gt;loginController&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="loginController" class="com.test.controller.LoginController"&gt; &lt;property name="successView" value="/admin/success"&gt;&lt;/property&gt; &lt;property name="formView" value="/admin/login"&gt;&lt;/property&gt; &lt;/bean&gt; UserDAO.java: public class UserDAO extends BaseDao implements IUserDAO { public void insert(User user) { System.out.println("hibernateTemplate: " + this.getHibernateTemplate()); this.getHibernateTemplate().update("INSERT INTO USERPASS (USERNAME, PASSWORDS) VALUES ('" + user.getUserName() +"', '" + user.getPassword() + "')"); } public User find(Integer id) { List rows = this.getHibernateTemplate().find("SELECT * FROM USERPASS WHERE ID=" + id.intValue()); Iterator it = rows.iterator(); if(it.hasNext()) { Map userMap = (Map)it.next(); User user = new User(); user.setUserName(userMap.get("USERNAME").toString()); user.setPassword(userMap.get("PASSWORDS").toString()); return user; } return null; } }

Spring 注入为空

在一个SSH的项目中遇到一个问题,我有一个dao的接口BaseJdbcDao,和一个dao的实现类BaseJdbcDaoImpl,实现类已经通过注解提交给容器进行管理,然后有一个工具类MailHelper想通过自动装配载入dao的实现类,可是每次都没有装配成功,代码如下,请教各位: [code="java"] package base; import java.util.List; import java.util.Map; import org.springframework.jdbc.support.rowset.SqlRowSet; public interface BaseJdbcDao { public abstract List queryForList(String sql); public abstract int queryForInt(String sql); public abstract SqlRowSet queryForRowSet(String sql); public abstract int update(String sql); public abstract Map queryForMap(String sql); public abstract void delete(String sql); public abstract void insert(String sql); } [/code] [code="java"] package base.impl; import java.util.List; import java.util.Map; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.support.rowset.SqlRowSet; import base.BaseJdbcDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; @Repository("basejdbcdao") public class BaseJdbcDaoImpl implements BaseJdbcDao { private JdbcTemplate jdbcTemplate; public JdbcTemplate getJdbcTemplate() { return jdbcTemplate; } @Autowired public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public List queryForList(String sql){ System.out.println(sql); return this.getJdbcTemplate().queryForList(sql); } public int queryForInt(String sql){ System.out.println(sql); return this.getJdbcTemplate().queryForInt(sql); } public SqlRowSet queryForRowSet(String sql){ System.out.println(sql); return this.getJdbcTemplate().queryForRowSet(sql); } public int update(String sql){ System.out.println(sql); return this.getJdbcTemplate().update(sql); } public Map queryForMap(String sql){ System.out.println(sql); return this.getJdbcTemplate().queryForMap(sql); } public void delete(String sql){ System.out.println(sql); this.getJdbcTemplate().update(sql); } public void insert(String sql){ System.out.println(sql); this.getJdbcTemplate().execute(sql); } } [/code] [code="java"]package util; import java.io.IOException; import java.util.HashMap; import java.util.Properties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.jdbc.support.rowset.SqlRowSet; import java.util.Date; import javax.activation.DataHandler; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import util.ByteArrayDataSource; import javax.mail.PasswordAuthentication; import base.BaseJdbcDao; import base.impl.BaseJdbcDaoImpl; public class MailHelper { @Autowired @Qualifier("basejdbcdao") private BaseJdbcDao dao; private String email; private String mobile; private String school; private String name; private String remark; private String appstr; public MailHelper(String school,String name,String mobile,String email,String remark,String appstr){ this.email = email; this.mobile = mobile; this.school = school; this.name = name; this.remark = remark; this.appstr = appstr; } public MailHelper(){}; public void sendMail(){ this.insertData(school,name,mobile,email,remark,appstr); } /** * 帐号申请的功能 * @param template * @param pschool * @param pname * @param pmobile * @param pemail * @param premark */ public void insertData(String pschool,String pname,String pmobile,String pemail,String premark,String appstr){ String email = changeContent( pemail); String mobile = changeContent( pmobile); String school =changeContent (pschool); String name =changeContent (pname); String remark = changeContent (premark); String to = "test@163.com"; String subject = "申请"; StringBuilder sb = new StringBuilder("insert into maillist(linkman,school,mobile,mail,remark)values('"+name+"','"+school+"','"+mobile+"','"+email+"','"+remark+"')"); dao.update(sb.toString()); remark = "内容略。。"; this.send( to, subject, remark); } /** * Sending a mail with given values.<br> * content parameter means the main email text,it refers to a html file. * * @param smtpServer * @param to * @param from * @param subject * @param content * @param emailUsername * @param emailUserpass * @author WYQ */ private String send(String to,String subject,String content) { try { HashMap<String,String> map = readParamters(); String smtpserver = map.get("smtpserver"); String publicaccount = map.get("publicaccount"); String publicpwd = map.get("publicpwd"); String from = map.get("publicmail"); Properties props = System.getProperties(); props.put("mail.smtp.port", "25"); props.put("mail.smtp.starttls.enable","false"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.host", smtpserver); Session session = null; session = Session.getDefaultInstance(props,new PasswordAuthenticator(publicaccount,publicpwd)); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse( to, false)); msg.setSubject(subject); msg.setDataHandler(new DataHandler(new ByteArrayDataSource(content,"text/html; charset=\"utf-8\""))); msg.setHeader("X-Mailer", "XML-Mail"); msg.setSentDate(new Date()); // -- Send the message -- Transport.send(msg); return "success"; } catch (Exception ex) { return "Error" + ex; } } private HashMap<String,String> readParamters(){ HashMap<String,String> map = new HashMap<String,String>(); Properties properties =new Properties(); try { properties.load(MailHelper.class.getClassLoader().getResourceAsStream("mail.properties")); map.put("smtpserver", properties.getProperty("smtpserver")); map.put("publicmail", properties.getProperty("publicmail")); map.put("publicaccount", properties.getProperty("publicaccount")); map.put("publicpwd", properties.getProperty("publicpwd")); } catch (IOException e) { e.printStackTrace(); } return map; } } class PasswordAuthenticator extends Authenticator { private String username; private String password; public PasswordAuthenticator(String username, String password) { this.username = username; this.password = password; } protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication (username, password); } } [/code] 然后我在struts的action类中调用MailHelper的send方法进行邮件发送时,打印的dao总是为空,action的代码是: [code="java"] /** * 帐号申请-邮件发送 * @return */ public String sendMail(){ MailHelper mh = new MailHelper(); mh.sendMail(); success = true; return SUCCESS; } [/code] spring的自动扫描和注解配置已经开启,也已经把dao的package路径和MailHelper的package路径加入到基类中了, [code="java"] <context:component-scan base-package="action,service,dao,base,util,tools"/> [/code] 现在就是弄不明白,为什么通过new出来的MailHelper对象中注入的dao总是为空呢。

Spring boot controller类加入@Autowired注解启动报错

![图片说明](https://img-ask.csdn.net/upload/201904/11/1554974904_886024.png) 工程结构 ``` //下面是全部的代码,最下面时错误日志。第一次提问,不知道插入代码片的格式是不是这样的,跪求大神指导,已经看了很多解决方案,但都无法解决我的问题,注释掉Autowired或者@注释掉Autowired(required=false)虽然可以启动项目,但是程序执行时又会发生错误,问题是逃避不了的。再次跪求大神指导。 //controller package controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import bean.AppMessage; import service.AppMessageService; @RestController @RequestMapping("/appmessage") public class AppMessageController { @Autowired/*(required=false)*/ private AppMessageService service; @RequestMapping("/getThree") public List<AppMessage> getThreeForMessage(){ List<AppMessage> list = service.getMessage(); return list; } @RequestMapping("/getAll") public List<AppMessage> getAllMessage(){ List<AppMessage> list = service.getAllMessage(); int num = list.size(); if(null!=list && num>3){ for (int i = 0; i < num-3; i++) { list.remove(0); } } return list; } @RequestMapping("/getByID") public List<AppMessage> getMessageById(@RequestParam("id") String id){ List<AppMessage> list = service.getMessageById(id); int num = list.size(); if(null!=list && num>5){ for (int i = 0; i < num-5; i++) { list.remove(0); } } return list; } @RequestMapping(value = "/add",method = RequestMethod.POST) public int addMessage(@RequestBody AppMessage appMessage){ return service.addMessage(appMessage); } @RequestMapping(value="/delMessageById",method=RequestMethod.POST) public int delMessageById(@RequestParam("id") String id){ return service.delMessage(id); } } ``` ``` //Service package service; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import bean.AppMessage; import mapper.AppMessageMapper; @Transactional @Service("appMessageService") public class AppMessageService { @Autowired private AppMessageMapper mapper; public List<AppMessage> getMessage(){ List<AppMessage> list = new ArrayList<AppMessage>(); list.add(mapper.selectByPrimaryKey("xtt")); //list = mapper.selectAll(); return list; } public List<AppMessage> getAllMessage(){ List<AppMessage> list = new ArrayList<AppMessage>(); list = mapper.selectAll(); return list; } public int addMessage(AppMessage appMessage) { return mapper.insert(appMessage); } public List<AppMessage> getMessageById(String id) { return mapper.getMessById(id); } public int delMessage(String id) { return mapper.deleteByPrimaryKey(id); } } ``` ``` //Mapper 接口,映射到mapper.xml package mapper; import java.util.List; import bean.AppMessage; public interface AppMessageMapper { int deleteByPrimaryKey(String id); int insert(AppMessage record); int insertSelective(AppMessage record); AppMessage selectByPrimaryKey(String id); int updateByPrimaryKeySelective(AppMessage record); int updateByPrimaryKey(AppMessage record); List<AppMessage> selectAll(); List<AppMessage> getMessById(String id); } ``` ``` <!-- Mapper.xml文件 --> <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="mapper.AppMessageMapper" > <!-- 对应mapper接口的位置 --> <resultMap id="BaseResultMap" type="bean.AppMessage" > <id column="id" property="id" jdbcType="VARCHAR" /> <result column="message" property="message" jdbcType="VARCHAR" /> <result column="senddate" property="senddate" jdbcType="TIMESTAMP" /> </resultMap> <sql id="Base_Column_List" > id, message, senddate </sql> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String" > select <include refid="Base_Column_List" /> from appuser_message where id = #{id,jdbcType=VARCHAR} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.String" > delete from appuser_message where id = #{id,jdbcType=VARCHAR} </delete> <insert id="insert" parameterType="bean.AppMessage" > insert into appuser_message (id, message, senddate ) values (#{id,jdbcType=VARCHAR}, #{message,jdbcType=VARCHAR}, #{senddate,jdbcType=TIMESTAMP} ) </insert> <insert id="insertSelective" parameterType="bean.AppMessage" > insert into appuser_message <trim prefix="(" suffix=")" suffixOverrides="," > <if test="id != null" > id, </if> <if test="message != null" > message, </if> <if test="senddate != null" > senddate, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides="," > <if test="id != null" > #{id,jdbcType=VARCHAR}, </if> <if test="message != null" > #{message,jdbcType=VARCHAR}, </if> <if test="senddate != null" > #{senddate,jdbcType=TIMESTAMP}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="bean.AppMessage" > update appuser_message <set > <if test="message != null" > message = #{message,jdbcType=VARCHAR}, </if> <if test="senddate != null" > senddate = #{senddate,jdbcType=TIMESTAMP}, </if> </set> where id = #{id,jdbcType=VARCHAR} </update> <update id="updateByPrimaryKey" parameterType="bean.AppMessage" > update appuser_message set message = #{message,jdbcType=VARCHAR}, senddate = #{senddate,jdbcType=TIMESTAMP} where id = #{id,jdbcType=VARCHAR} </update> <select id="selectAll" resultMap="BaseResultMap"> select id, message, senddate from appuser_message order by senddate </select> <select id="getMessById" resultMap="BaseResultMap" parameterType="java.lang.String"> select id, message, senddate from appuser_message where id = #{id,jdbcType=VARCHAR} order by senddate asc </select> </mapper> ``` ``` //实体类 package bean; import java.util.Date; public class AppMessage { private String id; private String message; private Date senddate; public String getId() { return id; } public void setId(String id) { this.id = id == null ? null : id.trim(); } public String getMessage() { return message; } public void setMessage(String message) { this.message = message == null ? null : message.trim(); } public Date getSenddate() { return senddate; } public void setSenddate(Date senddate) { this.senddate = senddate; } } ``` ``` //启动类 package com.shuai.spring_boot_1; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; /** * Hello world! * */ @ComponentScan(basePackages="controller") @SpringBootApplication public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } } ``` ``` pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.5.RELEASE</version> </parent> <groupId>com.shuai</groupId> <artifactId>spring-boot-1</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>spring-boot-1</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <!--web应用基本环境配置 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.jayway.jsonpath</groupId> <artifactId>json-path</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.0.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <version>1.3.5.RELEASE</version> </dependency> --> </dependencies> <build> <plugins> <!-- spring-boot-maven-plugin插件就是打包spring boot应用的 --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> ``` ``` #properties文件 spring.datasource.url=jdbc:mysql://localhost:3306/world spring.datasource.username=root spring.datasource.password=000000 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.max-idle=10 spring.datasource.max-wait=10000 spring.datasource.min-idle=5 spring.datasource.initial-size=5 server.port=8012 server.session.timeout=10 server.tomcat.uri-encoding=UTF-8 # mybatis.config= classpath:mybatis-config.xml mybatis.mapperLocations=classpath:mappers/*.xml # domain object's package #mybatis.typeAliasesPackage=com.lgp.SpringBoot.bean mybatis.typeAliasesPackage=bean # handler's package # mybatis.typeHandlersPackage= # check the mybatis configuration exists # mybatis.check-config-location= # mode of execution. Default is SIMPLE # mybatis.executorType= ``` ![图片说明](https://img-ask.csdn.net/upload/201904/11/1554976465_217387.png) 错误日志

使用druid连接mysql报错,搞不清楚是哪里的问题,求解答!!!

报错如下: 04-Dec-2019 19:16:27.521 淇℃伅 [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory 鎶妛eb 搴旂敤绋嬪簭閮ㄧ讲鍒扮洰褰� [D:\javaEE\tomcat\webapps\manager] 04-Dec-2019 19:16:27.537 淇℃伅 [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [D:\javaEE\tomcat\webapps\manager] has finished in [16] ms 04-Dec-2019 19:16:40.134 淇℃伅 [http-nio-80-exec-9] com.alibaba.druid.support.logging.JakartaCommonsLoggingImpl.info {dataSource-1} inited org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0 at org.springframework.dao.support.DataAccessUtils.requiredSingleResult(DataAccessUtils.java:71) at org.springframework.jdbc.core.JdbcTemplate.queryForObject(JdbcTemplate.java:797) at dao.UserDaoImpl.UserDaoImpl.findUserByUsernameAndPassword(UserDaoImpl.java:19) at service.impl.UserServiceImpl.login(UserServiceImpl.java:13) at Servlet.LoginServlet.doPost(LoginServlet.java:55) at javax.servlet.http.HttpServlet.service(HttpServlet.java:660) at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:528) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:798) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:810) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:748) 配置文件: driverClassName=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/day17 username=root password=root initialSize=5 maxActive=10 maxWait=3000 validationQuery:SELECT 1 testWhileIdle:true testOnBorrow:false testOnReturn:false 工具类如下: /** * JDBC工具类 使用Durid连接池 */ public class JDBCUtils { private static DataSource ds ; static { try { //1.加载配置文件 Properties pro = new Properties(); //使用ClassLoader加载配置文件,获取字节输入流 InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"); pro.load(is); //2.初始化连接池对象 ds = DruidDataSourceFactory.createDataSource(pro); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } /** * 获取连接池对象 */ public static DataSource getDataSource(){ return ds; } /** * 获取连接Connection对象 */ public static Connection getConnection() throws SQLException { return ds.getConnection(); } }

struts2注解url没跳转到action里的方法,没报错也没跳转

我补下图片: ![图片说明](https://img-ask.csdn.net/upload/201509/21/1442781387_310218.png) package com.AppServer.action; import javax.annotation.Resource; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.ExceptionMapping; import org.apache.struts2.convention.annotation.ExceptionMappings; import org.apache.struts2.convention.annotation.Namespace; import org.apache.struts2.convention.annotation.ParentPackage; import org.apache.struts2.convention.annotation.Result; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.stereotype.Service; import com.AppServer.bean.User; import com.AppServer.dao.UserDAO; import com.AppServer.service.UserService; import com.demo.interceptor.MethodCacheInterceptor; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; @Controller @ParentPackage("struts-default") @Namespace(value = "msgAction") @ExceptionMappings({ @ExceptionMapping(exception = "java.lange.RuntimeException", result = "error") }) public class MsgAction extends ActionSupport { private String username; private String password; @Resource private UserService userService; @Action(value = "msg" , results = { @Result(name = "success", location = "/success.jsp"), @Result(name = "failure", location = "/failure.jsp"), @Result(name = "error", location = "/login.jsp")}) //获取用户信息 public String getInfo() { System.out.println("进来玩"); return SUCCESS; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } } url访问如下:http://127.0.0.1:8080/AppServer_1.1/msgAction/msg.do 访问之后没报错,没进去getInfo这个方法 struts2.xml: <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <!-- 指定Web应用的默认编码,相当于调用request的setCharacterEncoding方法 --> <constant name="struts.i18n.encoding" value="UTF-8" /> <!-- 设置浏览器是否缓存静态内容,默认值为true(生产环境下使用),开发阶段最好关闭 --> <constant name="struts.serve.static.browserCache" value="false" /> <!-- 当Struts2的配置文件修改后,系统是否自动重新加载配置文件,默认值为false(生产环境下使用),开发阶段最好打开 --> <constant name="struts.configuration.xml.reload" value="true" /> <!-- 开发模式下使用,这样可以打印出更详细的日志信息 --> <constant name="struts.devMode" value="true" /> <!-- 默认的视图主题 --> <constant name="struts.ui.theme" value="simple" /> <!-- 把Action对象交给Spring创建和管理 --> <constant name="struts.objectFactory" value="spring" /> <!-- Struts2处理的请求后缀,默认值是action --> <constant name="struts.action.extension" value="do" /> <!-- 国际化资源文件 <constant name="struts.custom.i18n.resources" value="globalMessages" /> --> <package name="msg" extends="struts-default"> <default-action-ref name="indexPage" /> <global-results> <result name="exceptionPage">/error/exceptionPage.jsp</result> </global-results> <global-exception-mappings> <exception-mapping result="exceptionPage" exception="java.lang.Exception" /> </global-exception-mappings> <action name="indexPage"> <result>/login.jsp</result> </action> <!-- <action name="msg" method="getInfo" class="com.AppServer.action.MsgAction"> <result name="success">/success.jsp</result> <result name="failure">/failure.jsp</result> <result name="error">/login.jsp</result> </action> --> </package> </struts> application.xml: <?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd" default-autowire="byName" default-lazy-init="true"> <!-- 说明:下面有的Bean配置提供了多种方案,请根据需要采用某一种(别忘了注释掉其他同类方案) --> <!-- 自动扫描Spring注解配置 并保证@Required,@Autowired的属性被注入--> <context:component-scan base-package="com" /> <!-- 自动加载属性配置文件 --> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 配置数据源:方法一,使用C3P0方式(推荐) --> <!-- <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" --> <!-- destroy-method="close" --> <!-- p:driverClass="${jdbc.driverClassName}" --> <!-- p:jdbcUrl="${jdbc.url}" --> <!-- p:user="${jdbc.username}" --> <!-- p:password="${jdbc.password}" /> --> <!-- <context:property-placeholder location="classpath:jdbc.properties"/> --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <!-- property池启动时的初始值 --> <property name="password" value="${jdbc.password}"/> <!-- 连接name="initialSize" value="${initialSize}"/>--> <property name="initialSize" value="1"/> <!-- 连接池的最大值 --> <property name="maxActive" value="500"/> <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 --> <property name="maxIdle" value="2"/> <!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 --> <property name="minIdle" value="1"/> </bean> <!-- 配置数据源:方法二,使用DBCP方式(不推荐) --> <!-- <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}" p:username="${jdbc.username}" p:password="${jdbc.password}" /> --> <!-- 配置数据源:方法三,使用JNDI方式 --> <!-- <jee:jndi-lookup id="dataSource" jndi-name="${jndi.name}" /> --> <!-- 配置Hibernate的数据源代理工厂:方法一,使用p属性通配符,按文件名搜索匹配的映射文件 --> <!-- <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" p:dataSource-ref="dataSource" > <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop> <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop> <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop> </props> </property> 加载hibernate的jpa注解形式实体 <property name="packagesToScan"> <list> <value>com.xmm.demo.domain*</value> </list> </property> </bean> --> <!-- 配置Hibernate的数据源代理工厂:方法二,使用list集合,按文件名搜索匹配的映射文件 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" p:dataSource-ref="dataSource"> <property name="mappingLocations"> <list> <value>classpath*:/com/**/*.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop> <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop> <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop> </props> </property> </bean> <!-- 配置Hibernate的数据源代理工厂:方法三,使用p属性通配符,按目录搜索映射文件 --> <!-- <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" p:dataSource-ref="dataSource" p:mappingDirectoryLocations="classpath*:/com/**/domain"> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.format_sql">${hibernate.format_sql}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop> <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop> <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop> </props> </property> </bean> --> <!-- 配置Hibernate的数据源代理工厂:方法四,使用hibernate.cfg.xml --> <!-- <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" p:dataSource-ref="dataSource" p:configLocation="classpath:hibernate.cfg.xml"> </bean> --> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" p:sessionFactory-ref="sessionFactory" /> <!-- 配置声明式事务:方法一,在Service实现类或者public实现方法上使用注解@Transactional,则此类或方法就会启用事务机制 --> <!-- <tx:annotation-driven transaction-manager="transactionManager" /> --> <!-- 配置声明式事务:方法二,使用tx/aop命名空间的配置(其实还有方法三,由于快要过时不推荐使用了,这里就不给出方法三的配置了) --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="edit*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="new*" propagation="REQUIRED" /> <tx:method name="set*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="change*" propagation="REQUIRED" /> <tx:method name="get*" propagation="REQUIRED" read-only="true" /> <tx:method name="find*" propagation="REQUIRED" read-only="true" /> <tx:method name="load*" propagation="REQUIRED" read-only="true" /> <tx:method name="search*" propagation="REQUIRED" read-only="true" /> <tx:method name="*" propagation="REQUIRED" read-only="true" /> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="mypointcut" expression="execution(* com.**.service..*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="mypointcut" /> </aop:config> <!-- 下面三个Bean的配置可有可无,但配置后用处更大,通常用于BaseDao类、其他Dao类或特殊工具类中 --> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate" p:sessionFactory-ref="sessionFactory" /> <bean id="hibernateDaoSupport" class="org.springframework.orm.hibernate4.support.HibernateDaoSupport" p:hibernateTemplate-ref="hibernateTemplate" abstract="true"/> <bean id="sessionFactoryUtils" class="org.springframework.orm.hibernate4.SessionFactoryUtils" abstract="true"/> </beans> tomcat6.0:服务器运行正常: 九月 21, 2015 4:22:24 上午 org.apache.catalina.core.AprLifecycleListener init 信息: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: D:\Java\jdk1.7.0\bin;E:\tomcat6\bin 九月 21, 2015 4:22:25 上午 org.apache.coyote.http11.Http11Protocol init 信息: Initializing Coyote HTTP/1.1 on http-8080 九月 21, 2015 4:22:25 上午 org.apache.catalina.startup.Catalina load 信息: Initialization processed in 516 ms 九月 21, 2015 4:22:25 上午 org.apache.catalina.core.StandardService start 信息: Starting service Catalina 九月 21, 2015 4:22:25 上午 org.apache.catalina.core.StandardEngine start 信息: Starting Servlet Engine: Apache Tomcat/6.0.41 九月 21, 2015 4:22:25 上午 org.apache.catalina.startup.HostConfig deployDirectory 信息: Deploying web application directory AppServer_1.1 九月 21, 2015 4:22:25 上午 org.apache.catalina.loader.WebappClassLoader validateJarFile 信息: validateJarFile(E:\tomcat6\webapps\AppServer_1.1\WEB-INF\lib\servlet-api.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class 九月 21, 2015 4:22:26 上午 org.apache.catalina.core.ApplicationContext log 信息: Set web app root system property: 'webapp.root' = [E:\tomcat6\webapps\AppServer_1.1\] 九月 21, 2015 4:22:26 上午 org.apache.catalina.core.ApplicationContext log 信息: Initializing log4j from [classpath:log4j.properties] 九月 21, 2015 4:22:26 上午 org.apache.catalina.core.ApplicationContext log 信息: Initializing Spring root WebApplicationContext 九月 21, 2015 4:22:34 上午 org.apache.coyote.http11.Http11Protocol start 信息: Starting Coyote HTTP/1.1 on http-8080 九月 21, 2015 4:22:34 上午 org.apache.jk.common.ChannelSocket init 信息: JK: ajp13 listening on /0.0.0.0:8009 九月 21, 2015 4:22:34 上午 org.apache.jk.server.JkMain start 信息: Jk running ID=0 time=0/23 config=null 九月 21, 2015 4:22:34 上午 org.apache.catalina.startup.Catalina start 信息: Server startup in 9364 ms 测试定时任务:2015-09-21 04:30:00:074 测试定时任务:2015-09-21 04:40:00:004 url访问地址:http://127.0.0.1:8080/AppServer_1.1/msgAction/msg.do 没有进去action的getinfo方法,这是为什么?而且也没有任何的报错!!!!!!!!!!!

晕死,有人见过类似的错误没?关于的hibernate的

我没分了 5......... 先来错误提示(首先说明不是简单的表不存在,所有的映射文件都没有映射过company表[至少没有显式引用]) [code="java"]ERROR 2009-09-10 13:31:58.343 JDBCExceptionReporter:logExceptions - Table 'bfw_utf8.company' doesn't exist org.springframework.jdbc.BadSqlGrammarException: Hibernate operation: could not insert: [com.bafang.pojos.SiteAd]; bad SQL grammar [insert into site_ad (subsite_id, site_ad_location_id, site_ad_location_name, site_ad_keyword_id, site_ad_keyword, company_id, company_name, txt, url, media_type, media_file, type, charge, start_time, end_time, item_order, enabled) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)]; nested exception is com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Table 'bfw_utf8.company' doesn't exist Caused by: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Table 'bfw_utf8.company' doesn't exist at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2870) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1573) at com.mysql.jdbc.ServerPreparedStatement.serverExecute(ServerPreparedStatement.java:1160) at com.mysql.jdbc.ServerPreparedStatement.executeInternal(ServerPreparedStatement.java:685) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1400) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1314) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1299) at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:105) at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:73) at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:33) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2158) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2638) at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:48) at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:248) at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:298) at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:181) at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:107) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:187) at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:172) at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70) at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:535) at org.hibernate.impl.SessionImpl.save(SessionImpl.java:523) at org.hibernate.impl.SessionImpl.save(SessionImpl.java:519) at org.springframework.orm.hibernate3.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:598) at org.springframework.orm.hibernate3.HibernateTemplate.execute(HibernateTemplate.java:358) at org.springframework.orm.hibernate3.HibernateTemplate.save(HibernateTemplate.java:595) at com.bafang.pojos.base._BaseRootDAO.save(_BaseRootDAO.java:25) at com.bafang.pojos.base.BaseSiteAdDAO.save(BaseSiteAdDAO.java:20) at com.bafang.pojos.base.BaseSiteAdDAO$$FastClassByCGLIB$$33c630a7.invoke(<generated>) at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:149) at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:609) at com.bafang.pojos.dao.SiteAdDAO$$EnhancerByCGLIB$$29bf5095.save(<generated>) at com.bafang.web.action.admin.main.AdAction.add(AdAction.java:107) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:269) at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:170) at org.springframework.web.struts.DelegatingActionProxy.execute(DelegatingActionProxy.java:106) at org.apache.struts.chain.commands.servlet.ExecuteAction.execute(ExecuteAction.java:58) at org.apache.struts.chain.commands.AbstractExecuteAction.execute(AbstractExecuteAction.java:67) at org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:51) at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:190) at org.apache.commons.chain.generic.LookupCommand.execute(LookupCommand.java:304) at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:190) at org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:283) at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913) at com.bafang.web.servlet.BFActionServlet.process(BFActionServlet.java:26) at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462) at javax.servlet.http.HttpServlet.service(HttpServlet.java:709) at javax.servlet.http.HttpServlet.service(HttpServlet.java:802) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:237) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157) at com.bafang.web.filters.HTMLFilter.synthesisURI(HTMLFilter.java:85) at com.bafang.web.filters.HTMLFilter.doFilter(HTMLFilter.java:60) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:186) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157) at com.bafang.web.filters.AdminFilter.doFilter(AdminFilter.java:41) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:186) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157) at com.bafang.web.filters.SubsiteFilter.doFilter(SubsiteFilter.java:35) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:186) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:214) at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520) at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:198) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:152) at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137) at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:118) at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:102) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520) at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:929) at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:160) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:799) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:705) at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:577) at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:683) at java.lang.Thread.run(Thread.java:619)[/code] 相关hibernate映射文件 SiteAd.hbm.xml [code="xml"]<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" > <hibernate-mapping package="com.bafang.pojos"> <class name="SiteAd" table="site_ad"> <id name="id" type="integer" column="id"> <generator class="identity" /> </id> <property name="subsiteId" column="subsite_id" type="integer" not-null="false" length="11" /> <property name="siteAdLocationId" column="site_ad_location_id" type="string" not-null="false" length="50" /> <property name="siteAdLocationName" column="site_ad_location_name" type="string" not-null="false" length="255" /> <many-to-one name="siteAdLocation" column="site_ad_location_id" class="SiteAdLocation" not-null="false" insert="false" update="false" /> <property name="siteAdKeywordId" column="site_ad_keyword_id" type="integer" not-null="false" length="11" /> <property name="siteAdKeyword" column="site_ad_keyword" type="string" not-null="false" length="255" /> <property name="companyId" column="company_id" type="integer" not-null="false" length="11" /> <property name="companyName" column="company_name" type="string" not-null="false" length="255" /> <!--<many-to-one name="company" column="company_id" class="Store" not-null="false" insert="false" update="false" />--> <property name="txt" column="txt" type="string" not-null="false" length="255" /> <property name="url" column="url" type="string" not-null="false" length="255" /> <property name="mediaType" column="media_type" type="string" not-null="false" length="255" /> <property name="mediaFile" column="media_file" type="string" not-null="false" length="255" /> <property name="type" column="type" type="string" not-null="false" length="100" /> <property name="charge" column="charge" type="java.lang.Float" not-null="false" length="12" /> <property name="startTime" column="start_time" type="timestamp" not-null="false" length="19" /> <property name="endTime" column="end_time" type="timestamp" not-null="false" length="19" /> <property name="itemOrder" column="item_order" type="integer" not-null="false" length="11" /> <property name="enabled" column="enabled" type="boolean" not-null="false" length="1" /> </class> </hibernate-mapping>[/code] pojo相关类 com.bafang.pojos.SiteAd.java [code="java"]package com.bafang.pojos; import com.bafang.pojos.base.BaseSiteAd; public class SiteAd extends BaseSiteAd { private static final long serialVersionUID = 7092206885096359130L; public SiteAd () { } public String getTypeName(){ if("1".equals(getType())) return "多媒体广告"; else if("2".equals(getType())) return "连接广告"; else if("3".equals(getType())) return "店铺广告"; else if("4".equals(getType())) return "店铺评论广告"; else return "其它广告"; } }[/code] com.bafang.pojos.base.BaseSiteAd.java [code="java"]package com.bafang.pojos.base; import java.io.Serializable; public abstract class BaseSiteAd implements Serializable { protected Integer id; protected Integer subsiteId; protected String siteAdLocationId; protected String siteAdLocationName; protected Integer siteAdKeywordId; protected String siteAdKeyword; protected Integer companyId; protected String companyName; protected String txt; protected String url; protected String mediaType; protected String mediaFile; protected String type; protected Float charge; protected java.util.Date startTime; protected java.util.Date endTime; protected Integer itemOrder; protected Boolean enabled; protected com.bafang.pojos.SiteAdLocation siteAdLocation; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getSubsiteId() { return subsiteId; } public void setSubsiteId(Integer subsiteId) { this.subsiteId = subsiteId; } public String getSiteAdLocationId() { return siteAdLocationId; } public void setSiteAdLocationId(String siteAdLocationId) { this.siteAdLocationId = siteAdLocationId; } public String getSiteAdLocationName() { return siteAdLocationName; } public void setSiteAdLocationName(String siteAdLocationName) { this.siteAdLocationName = siteAdLocationName; } public Integer getSiteAdKeywordId() { return siteAdKeywordId; } public void setSiteAdKeywordId(Integer siteAdKeywordId) { this.siteAdKeywordId = siteAdKeywordId; } public String getSiteAdKeyword() { return siteAdKeyword; } public void setSiteAdKeyword(String siteAdKeyword) { this.siteAdKeyword = siteAdKeyword; } public Integer getCompanyId() { return companyId; } public void setCompanyId(Integer companyId) { this.companyId = companyId; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public String getTxt() { return txt; } public void setTxt(String txt) { this.txt = txt; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getMediaType() { return mediaType; } public void setMediaType(String mediaType) { this.mediaType = mediaType; } public String getMediaFile() { return mediaFile; } public void setMediaFile(String mediaFile) { this.mediaFile = mediaFile; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Float getCharge() { return charge; } public void setCharge(Float charge) { this.charge = charge; } public java.util.Date getStartTime() { return startTime; } public void setStartTime(java.util.Date startTime) { this.startTime = startTime; } public java.util.Date getEndTime() { return endTime; } public void setEndTime(java.util.Date endTime) { this.endTime = endTime; } public Integer getItemOrder() { return itemOrder; } public void setItemOrder(Integer itemOrder) { this.itemOrder = itemOrder; } public Boolean getEnabled() { return enabled; } public void setEnabled(Boolean enabled) { this.enabled = enabled; } public com.bafang.pojos.SiteAdLocation getSiteAdLocation() { return siteAdLocation; } public void setSiteAdLocation(com.bafang.pojos.SiteAdLocation siteAdLocation) { this.siteAdLocation = siteAdLocation; } }[/code] 保存动作是直接调用spring的工具类 org.springframework.orm.hibernate3.support.HibernateDaoSupport.save(Object obj); 我debug过,就是保存的动作后报的错 数据库query 日志 [code="java"]090910 13:31:50 2 Query SET autocommit=0 2 Prepare select siteadloca0_.id as id17_, siteadloca0_.subsite_id as subsite2_17_, siteadloca0_.name as name17_, siteadloca0_.type as type17_, siteadloca0_.width as width17_, siteadloca0_.height as height17_, siteadloca0_.item_count as item7_17_, siteadloca0_.url as url17_, siteadloca0_.enabled as enabled17_ from site_ad_location siteadloca0_ where 1=1 and siteadloca0_.subsite_id=1 limit ? 2 Execute select siteadloca0_.id as id17_, siteadloca0_.subsite_id as subsite2_17_, siteadloca0_.name as name17_, siteadloca0_.type as type17_, siteadloca0_.width as width17_, siteadloca0_.height as height17_, siteadloca0_.item_count as item7_17_, siteadloca0_.url as url17_, siteadloca0_.enabled as enabled17_ from site_ad_location siteadloca0_ where 1=1 and siteadloca0_.subsite_id=1 limit 20 2 Close stmt 2 Query commit 2 Query SET autocommit=1 2 Query SET autocommit=0 2 Prepare select count(*) as col_0_0_ from site_ad_location siteadloca0_ where 1=1 and siteadloca0_.subsite_id=? 2 Execute select count(*) as col_0_0_ from site_ad_location siteadloca0_ where 1=1 and siteadloca0_.subsite_id=1 2 Close stmt 2 Query commit 2 Query SET autocommit=1 090910 13:31:58 2 Prepare insert into site_ad (subsite_id, site_ad_location_id, site_ad_location_name, site_ad_keyword_id, site_ad_keyword, company_id, company_name, txt, url, media_type, media_file, type, charge, start_time, end_time, item_order, enabled) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) 2 Query select name into str from site_ad_location where id=new.site_ad_location_id 2 Query select name into str from company where id=new.company_id 2 Query SELECT 1 2 Close stmt D:\Program Files\MySQL\MySQL Server 5.1\bin\mysqld, Version: 5.1.37-community-log (MySQL Community Server (GPL)). started with: TCP Port: 3306, Named Pipe: (null) Time Id Command Argument 090910 13:33:15 1 Connect root@localhost on 1 Query SET NAMES utf8 2 Connect root@localhost on 2 Query SELECT @@sql_mode 2 Query SET SESSION sql_mode='STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION' 2 Query SET NAMES utf8 2 Quit 090910 13:33:17 1 Quit 3 Connect root@localhost on 3 Query SELECT @@sql_mode 3 Query SET SESSION sql_mode='STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION' 3 Query SET NAMES utf8[/code] [b]问题补充:[/b] [quote]dwangel[/quote]已经清理过项目 还是一样 谢谢啊 已经找到问题了 以前写成的程序员 弄了个触发器在数据库里 刚刚发现的 谢谢了 分不多都给你了

做了一个简单的SSH应用,但启动tomcat时总抛NoClassDefFoundError异常

做了一个简单的SSH应用,但启动tomcat时总抛NoClassDefFoundError异常。 <br />会有<pre name="code" class="java">java.lang.ClassNotFoundException: javax.transaction.TransactionManager</pre> <br />各位一定要帮看看啊!(ssh未入门级) <br /> <br />开发工具:Eclipse3.2+Tomcat5.5+Mysql5.0 <br />建表 <br /><pre name="code" class="java">CREATE TABLE `people` ( `id` int(11) NOT NULL auto_increment, `name` varchar(100) default NULL, `location` varchar(100) default NULL, PRIMARY KEY (`id`) ) </pre> <br /> <br />首先,建立工程和package,以下是我的工程目录 <br />  action <br />      DeletePeopleAction.java     //删除人员action <br />      EditPeopleAction.java         //编辑人员action第一步,读取需要修改的人员资料 <br />       EditPeopleActionDo.java   //修改人员action <br />      ListPeopleAction.javaSave   //显示人员列表action <br />      SavePeopleAction.java         //新增人员action <br />      SearchPeopleAction.java     //查找人员action <br />dao <br />      IDAO.java    //数据库操作接口 <br />       StudentDAOImpl.java  //数据库操作实现 <br />domain <br />      AbstractPeople.java   //实体抽象类 <br />       People.hbm.xml         //数据库映射 <br />       People.java                 //实体类 <br />service <br />      IService.java   //服务层接口 <br />       StudentManagerImpl.java   //服务层实现 <br />util <br />     Character.java   //字符编码过滤器 <br />      PageSupport.java   //分页 <br />applicationContext.xml   //Spring配置文件(hibernate部分和Service部分) <br /> <br />JSP:不详细些了。 <br />   addStudent.jsp <br />   editStudent.jsp <br />   searchList.jsp <br />   searchStudent.jsp <br />   studentList.jsp <br /> <br />我觉得问题就出在 Spring 的xml部署上, <br />或者是我引入的包有冲突,要么就是根本不对。 <br />下面是应用的配置信息: <br />1.web.xml <br /><pre name="code" class="java"><!----> &lt;web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemalocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"&gt; &lt;context-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt;/WEB-INF/classes/applicationContext.xml&lt;/param-value&gt; &lt;/context-param&gt; &lt;resource-ref&gt; &lt;description&gt;SqlServer Datasource example&lt;/description&gt; &lt;res-ref-name&gt;jdbc/StudentManager&lt;/res-ref-name&gt; &lt;res-type&gt;javax.sql.DataSource&lt;/res-type&gt; &lt;res-auth&gt;Container&lt;/res-auth&gt; &lt;/resource-ref&gt; &lt;filter&gt; &lt;filter-name&gt;hibernateFilter&lt;/filter-name&gt; &lt;filter-class&gt; org.springframework.orm.hibernate3.support.OpenSessionInViewFilter &lt;/filter-class&gt; &lt;init-param&gt; &lt;param-name&gt;singleSession&lt;/param-name&gt; &lt;param-value&gt;true&lt;/param-value&gt; &lt;/init-param&gt; &lt;/filter&gt; &lt;filter-mapping&gt; &lt;filter-name&gt;hibernateFilter&lt;/filter-name&gt; &lt;url-pattern&gt;*.do&lt;/url-pattern&gt; &lt;/filter-mapping&gt; &lt;servlet&gt; &lt;servlet-name&gt;SpringContextServlet&lt;/servlet-name&gt; &lt;servlet-class&gt; org.springframework.web.context.ContextLoaderServlet&lt;/servlet-class&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet&gt; &lt;servlet-name&gt;SpringLog4jConfigServlet&lt;/servlet-name&gt; &lt;servlet-class&gt; org.springframework.web.util.Log4jConfigServlet &lt;/servlet-class&gt; &lt;/servlet&gt; &lt;servlet&gt; &lt;servlet-name&gt;web&lt;/servlet-name&gt; &lt;servlet-class&gt; org.springframework.web.servlet.DispatcherServlet &lt;/servlet-class&gt; &lt;/servlet&gt; &lt;servlet&gt; &lt;servlet-name&gt;action&lt;/servlet-name&gt; &lt;servlet-class&gt;org.apache.struts.action.ActionServlet&lt;/servlet-class&gt; &lt;init-param&gt; &lt;param-name&gt;config&lt;/param-name&gt; &lt;param-value&gt;/WEB-INF/struts-config.xml&lt;/param-value&gt; &lt;/init-param&gt; &lt;init-param&gt; &lt;param-name&gt;debug&lt;/param-name&gt; &lt;param-value&gt;2&lt;/param-value&gt; &lt;/init-param&gt; &lt;init-param&gt; &lt;param-name&gt;detail&lt;/param-name&gt; &lt;param-value&gt;2&lt;/param-value&gt; &lt;/init-param&gt; &lt;load-on-startup&gt;2&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;action&lt;/servlet-name&gt; &lt;url-pattern&gt;*.do&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;/WEB-INF/jsp/index.jsp&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;taglib&gt; &lt;taglib-uri&gt;/WEB-INF/struts-bean.tld&lt;/taglib-uri&gt; &lt;taglib-location&gt;/WEB-INF/struts-bean.tld&lt;/taglib-location&gt; &lt;/taglib&gt; &lt;taglib&gt; &lt;taglib-uri&gt;/WEB-INF/struts-html.tld&lt;/taglib-uri&gt; &lt;taglib-location&gt;/WEB-INF/struts-html.tld&lt;/taglib-location&gt; &lt;/taglib&gt; &lt;taglib&gt; &lt;taglib-uri&gt;/WEB-INF/struts-logic.tld&lt;/taglib-uri&gt; &lt;taglib-location&gt;/WEB-INF/struts-logic.tld&lt;/taglib-location&gt; &lt;/taglib&gt; &lt;taglib&gt; &lt;taglib-uri&gt;/WEB-INF/struts-nested.tld&lt;/taglib-uri&gt; &lt;taglib-location&gt;/WEB-INF/struts-nested.tld&lt;/taglib-location&gt; &lt;/taglib&gt; &lt;/web-app&gt; </pre> <br /> <br />2.struts-config.xml <br /><pre name="code" class="java"><!----> &lt;struts-config&gt; &lt;data-sources&gt; &lt;form-beans&gt; &lt;form-bean name="people" type="domain.People"&gt;&lt;/form-bean&gt; &lt;/form-beans&gt; &lt;global-exceptions&gt; &lt;global-forwards&gt; &lt;action-mappings&gt; &lt;action path="/savePeople" name="people" type="action.SavePeopleAction" scope="session" parameter="method"&gt; &lt;forward name="success" path="/listPeople.do"&gt;&lt;/forward&gt; &lt;/action&gt; &lt;action path="/listPeople" name="people" type="action.ListPeopleAction"&gt; &lt;forward name="success" path="/studentList.jsp"&gt;&lt;/forward&gt; &lt;/action&gt; &lt;action path="/deletePeople" name="people" type="action.DeletePeopleAction"&gt; &lt;forward name="success" path="/studentList.jsp"&gt;&lt;/forward&gt; &lt;/action&gt; &lt;action path="/editPeople" name="people" type="action.EditPeopleAction"&gt; &lt;forward name="success" path="/editStudent.jsp"&gt;&lt;/forward&gt; &lt;/action&gt; &lt;action path="/editPeopleDo" name="people" type="action.EditPeopleActionDo"&gt; &lt;forward name="success" path="/studentList.jsp"&gt;&lt;/forward&gt; &lt;/action&gt; &lt;action path="/searchPeople" name="people" type="action.SearchPeopleAction"&gt; &lt;forward name="success" path="/searchList.jsp"&gt;&lt;/forward&gt; &lt;/action&gt; &lt;action path="/test" name="people" type="action.Test"&gt;&lt;/action&gt; &lt;/action-mappings&gt; &lt;controller locale="true"&gt; &lt;message-resources parameter=""&gt; <!----> &lt;/struts-config&gt; </pre> <br /> <br /> <br />3.applicationContext.xml <br /><pre name="code" class="java"><!----> &lt;beans&gt; <!----> &lt;bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" depends-on="sessionFactory"&gt; &lt;property name="sessionFactory"&gt; &lt;ref bean="sessionFactory"&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="studentManager" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"&gt; &lt;property name="transactionManager"&gt; &lt;ref bean="transactionManager"&gt;&lt;/ref&gt; &lt;/property&gt; &lt;property name="target"&gt; &lt;bean class="service.StudentManagerImpl"&gt; &lt;property name="studentDAO"&gt; &lt;ref bean="StudentDAO"&gt; &lt;/property&gt; &lt;/bean&gt; &lt;/property&gt; &lt;property name="transactionAttributes"&gt; &lt;props&gt; &lt;prop key="save*"&gt;PROPAGATION_REQUIRED&lt;/prop&gt; &lt;prop key="list*"&gt;PROPAGATION_REQUIRED,readOnly&lt;/prop&gt; &lt;prop key="delete*"&gt;PROPAGATION_REQUIRED&lt;/prop&gt; &lt;prop key="get*"&gt;PROPAGATION_REQUIRED,readOnly&lt;/prop&gt; &lt;prop key="edit*"&gt;PROPAGATION_REQUIRED&lt;/prop&gt; &lt;prop key="search*"&gt;PROPAGATION_REQUIRED&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; &lt;property name="proxyTargetClass"&gt; &lt;value&gt;true&lt;/value&gt; &lt;/property&gt; &lt;/bean&gt; <!----> &lt;bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt; &lt;property name="driverClassName"&gt; &lt;value&gt;com.mysql.jdbc.Driver&lt;/value&gt; &lt;/property&gt; &lt;property name="url"&gt; &lt;value&gt;jdbc:mysql://localhost:3306/dbjee&lt;/value&gt; &lt;/property&gt; &lt;property name="username"&gt; &lt;value&gt;root&lt;/value&gt; &lt;/property&gt; &lt;property name="password"&gt; &lt;value&gt;123456&lt;/value&gt; &lt;/property&gt; &lt;/bean&gt; <!----> &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"&gt; &lt;property name="dataSource"&gt; &lt;ref local="dataSource"&gt; &lt;/property&gt; &lt;property name="hibernateProperties"&gt; &lt;props&gt; &lt;prop key="hibernate.dialect"&gt;org.hibernate.dialect.MySQLDialect&lt;/prop&gt; &lt;prop key="hibernate.show_sql"&gt;true&lt;/prop&gt; &lt;prop key="hibernate.cache.use_query_cache"&gt;true&lt;/prop&gt; &lt;prop key="hibernate.cache.provider_class"&gt; org.hibernate.cache.HashtableCacheProvider&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; <!----> &lt;property name="mappingResources"&gt; &lt;list&gt; &lt;value&gt;domain/People.hbm.xml&lt;/value&gt; &lt;/list&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="StudentDAO" class="dao.StudentDAOImpl"&gt; &lt;property name="sessionFactory"&gt; &lt;ref local="sessionFactory"&gt; &lt;/property&gt; &lt;/bean&gt; &lt;/beans&gt; </pre> <br /> <br />4.People.hbm.xml <br /><pre name="code" class="java"><!----> <!----> &lt;hibernate-mapping package="domain"&gt; &lt;class name="People" table="people"&gt; &lt;id name="id" type="java.lang.Integer"&gt; &lt;column name="id"&gt; &lt;generator class="increment"&gt;&lt;/generator&gt; &lt;/id&gt; &lt;property name="name" type="java.lang.String"&gt; &lt;column name="name" length="100"&gt; &lt;/property&gt; &lt;property name="location" type="java.lang.String"&gt; &lt;column name="location" length="100"&gt; &lt;/property&gt; &lt;/class&gt; &lt;/hibernate-mapping&gt; </pre> <br /> <br /> <br /><span style="font-size: large;">附件里是我引入的jar包。 <br />希望各位能帮帮忙,困扰我2天,一直出不来。</span> <br /> <br />最后把启动Tomcat时报的错误也贴出来。 <br /><pre name="code" class="java">严重: Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/classes/applicationContext.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: javax/transaction/TransactionManager java.lang.NoClassDefFoundError: javax/transaction/TransactionManager at java.lang.Class.getDeclaredMethods0(Native Method) at java.lang.Class.privateGetDeclaredMethods(Unknown Source) at java.lang.Class.getDeclaredMethods(Unknown Source) at java.beans.Introspector$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.beans.Introspector.getPublicDeclaredMethods(Unknown Source) at java.beans.Introspector.getTargetMethodInfo(Unknown Source) at java.beans.Introspector.getBeanInfo(Unknown Source) at java.beans.Introspector.getBeanInfo(Unknown Source) at org.springframework.beans.CachedIntrospectionResults.&lt;init&gt;(CachedIntrospectionResults.java:149) at org.springframework.beans.CachedIntrospectionResults.forClass(CachedIntrospectionResults.java:85) at org.springframework.beans.BeanWrapperImpl.setIntrospectionClass(BeanWrapperImpl.java:234) at org.springframework.beans.BeanWrapperImpl.setWrappedInstance(BeanWrapperImpl.java:192) at org.springframework.beans.BeanWrapperImpl.setWrappedInstance(BeanWrapperImpl.java:176) at org.springframework.beans.BeanWrapperImpl.&lt;init&gt;(BeanWrapperImpl.java:129) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:491) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:366) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:234) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:144) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:330) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:234) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:144) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:283) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:321) at org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.refresh(AbstractRefreshableWebApplicationContext.java:139) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:252) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:190) at org.springframework.web.context.ContextLoaderServlet.init(ContextLoaderServlet.java:83) at javax.servlet.GenericServlet.init(GenericServlet.java:212) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1139) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:966) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:3956) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4230) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:760) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:740) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:544) at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:626) at org.apache.catalina.startup.HostConfig.deployDescriptors(HostConfig.java:553) at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:488) at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1150) at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:120) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1022) at org.apache.catalina.core.StandardHost.start(StandardHost.java:736) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1014) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443) at org.apache.catalina.core.StandardService.start(StandardService.java:448) at org.apache.catalina.core.StandardServer.start(StandardServer.java:700) at org.apache.catalina.startup.Catalina.start(Catalina.java:552) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:295) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:433) Caused by: java.lang.ClassNotFoundException: javax.transaction.TransactionManager at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1386) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1232) at java.lang.ClassLoader.loadClassInternal(Unknown Source) ... 55 more 2008-11-14 20:08:31 org.apache.catalina.core.ApplicationContext log 严重: StandardWrapper.Throwable org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/classes/applicationContext.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: javax/transaction/TransactionManager java.lang.NoClassDefFoundError: javax/transaction/TransactionManager at java.lang.Class.getDeclaredMethods0(Native Method) at java.lang.Class.privateGetDeclaredMethods(Unknown Source) at java.lang.Class.getDeclaredMethods(Unknown Source) at java.beans.Introspector$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.beans.Introspector.getPublicDeclaredMethods(Unknown Source) at java.beans.Introspector.getTargetMethodInfo(Unknown Source) at java.beans.Introspector.getBeanInfo(Unknown Source) at java.beans.Introspector.getBeanInfo(Unknown Source) at org.springframework.beans.CachedIntrospectionResults.&lt;init&gt;(CachedIntrospectionResults.java:149) at org.springframework.beans.CachedIntrospectionResults.forClass(CachedIntrospectionResults.java:85) at org.springframework.beans.BeanWrapperImpl.setIntrospectionClass(BeanWrapperImpl.java:234) at org.springframework.beans.BeanWrapperImpl.setWrappedInstance(BeanWrapperImpl.java:192) at org.springframework.beans.BeanWrapperImpl.setWrappedInstance(BeanWrapperImpl.java:176) at org.springframework.beans.BeanWrapperImpl.&lt;init&gt;(BeanWrapperImpl.java:129) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:491) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:366) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:234) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:144) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:330) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:234) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:144) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:283) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:321) at org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.refresh(AbstractRefreshableWebApplicationContext.java:139) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:252) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:190) at org.springframework.web.context.ContextLoaderServlet.init(ContextLoaderServlet.java:83) at javax.servlet.GenericServlet.init(GenericServlet.java:212) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1139) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:966) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:3956) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4230) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:760) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:740) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:544) at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:626) at org.apache.catalina.startup.HostConfig.deployDescriptors(HostConfig.java:553) at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:488) at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1150) at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:120) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1022) at org.apache.catalina.core.StandardHost.start(StandardHost.java:736) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1014) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443) at org.apache.catalina.core.StandardService.start(StandardService.java:448) at org.apache.catalina.core.StandardServer.start(StandardServer.java:700) at org.apache.catalina.startup.Catalina.start(Catalina.java:552) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:295) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:433) Caused by: java.lang.ClassNotFoundException: javax.transaction.TransactionManager at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1386) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1232) at java.lang.ClassLoader.loadClassInternal(Unknown Source) ... 55 more 2008-11-14 20:08:31 org.apache.catalina.core.StandardContext loadOnStartup 严重: Servlet /SSHDemo threw load() exception java.lang.ClassNotFoundException: javax.transaction.TransactionManager at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1386) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1232) at java.lang.ClassLoader.loadClassInternal(Unknown Source) at java.lang.Class.getDeclaredMethods0(Native Method) at java.lang.Class.privateGetDeclaredMethods(Unknown Source) at java.lang.Class.getDeclaredMethods(Unknown Source) at java.beans.Introspector$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.beans.Introspector.getPublicDeclaredMethods(Unknown Source) at java.beans.Introspector.getTargetMethodInfo(Unknown Source) at java.beans.Introspector.getBeanInfo(Unknown Source) at java.beans.Introspector.getBeanInfo(Unknown Source) at org.springframework.beans.CachedIntrospectionResults.&lt;init&gt;(CachedIntrospectionResults.java:149) at org.springframework.beans.CachedIntrospectionResults.forClass(CachedIntrospectionResults.java:85) at org.springframework.beans.BeanWrapperImpl.setIntrospectionClass(BeanWrapperImpl.java:234) at org.springframework.beans.BeanWrapperImpl.setWrappedInstance(BeanWrapperImpl.java:192) at org.springframework.beans.BeanWrapperImpl.setWrappedInstance(BeanWrapperImpl.java:176) at org.springframework.beans.BeanWrapperImpl.&lt;init&gt;(BeanWrapperImpl.java:129) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:491) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:366) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:234) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:144) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:330) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:234) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:144) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:283) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:321) at org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.refresh(AbstractRefreshableWebApplicationContext.java:139) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:252) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:190) at org.springframework.web.context.ContextLoaderServlet.init(ContextLoaderServlet.java:83) at javax.servlet.GenericServlet.init(GenericServlet.java:212) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1139) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:966) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:3956) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4230) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:760) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:740) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:544) at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:626) at org.apache.catalina.startup.HostConfig.deployDescriptors(HostConfig.java:553) at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:488) at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1150) at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:120) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1022) at org.apache.catalina.core.StandardHost.start(StandardHost.java:736) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1014) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443) at org.apache.catalina.core.StandardService.start(StandardService.java:448) at org.apache.catalina.core.StandardServer.start(StandardServer.java:700) at org.apache.catalina.startup.Catalina.start(Catalina.java:552) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:295) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:433) 2008-11-14 20:08:32 org.apache.coyote.http11.Http11BaseProtocol start 信息: Starting Coyote HTTP/1.1 on http-8888 2008-11-14 20:08:32 org.apache.jk.common.ChannelSocket init </pre><br /><strong>问题补充</strong><br /><div class="quote_title">zzxplayful 写道</div><div class="quote_div">没有这个包 <br />java.lang.ClassNotFoundException: javax.transaction.TransactionManager  </div> <br />这段异常我看得懂, <br />包括下面的: <br /><pre name="code" class="java">org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/classes/applicationContext.xml]: Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: javax/transaction/TransactionManager</pre> <br /> <br />都看得懂,我想知道的是解决办法。 <br />比如 <br />javax.transaction.TransactionManager <br />在什么包里? <br />要怎样解决?<br /><strong>问题补充</strong><br /><div class="quote_title">fywcc 写道</div><div class="quote_div">这个是spring里面的  你把SPRING的jar包重新覆盖进去试试</div> <br /> <br />我在Spring包里看了啊, <br />源码都是以 org.springframework.×××× 开始的啊, <br />没有 javax.transcation.** 啊, <br />怎么办?还是需要什么别的包,要么是我的包冲突了。 <br /> <br />我引入了: <br />antlr <br />commons-beanutils.jar <br />commons-digester.jar <br />commons-fileupload.jar <br />commons-logging.jar <br />commons-validator.jar <br />jakarta-oro.jar <br />struts.jar <br /> <br />spring.jar <br /> <br />hibernate3.jar<br /><strong>问题补充</strong><br /><div class="quote_title">jones 写道</div><div class="quote_div">放入jta.jar就行了,找找吧,spring里面应该有,要不就是Hibernate里面有</div> <br />谢谢你。 <br />我把缺少的包都放上了,终于启动Tomcat时候不抛异常,而且也能打开welcome页面了。 <br /> <br />但还有其他问题,明天搞。 <br /> <br />第一次搞SSH,多谢指点啊!

移动端app后台框架,springmvc+spring+mybatis占用服务器内存太大是什么原因

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd" default-lazy-init="true"> <!-- Annotation Config --> <context:annotation-config/> <!-- <mvc:annotation-driven/> --> <!-- 扫描Service --> <context:component-scan base-package="smart.service" /> <context:component-scan base-package="scott.service.*" /> <!-- jdbcTemplate --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource" /> </bean> <!-- spring Task --> <!-- <task:scheduled-tasks> <task:scheduled ref="taskJob" method="" cron=""/> </task:scheduled-tasks> <context:component-scan base-package=""></context:component-scan> --> <!-- spring Task Annotation --> <context:component-scan base-package="smart.smartutil.*"></context:component-scan> <task:annotation-driven scheduler="myScheduler"/> <task:scheduler id="myScheduler" pool-size="5"/> <!-- ***************配置数据源************** --> <!-- <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jeecg/template/jeecg_database.properties"></property> </bean> --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name = "driverClassName" value = "com.microsoft.sqlserver.jdbc.SQLServerDriver" /> <property name="url" value=""></property> <property name="username"><value> </value></property> <property name="password"><value></value></property> <!-- 初始化连接大小 --> <!-- 连接池最大使用连接数量 --> <property name="maxActive" value="10" /> <!-- 连接池最大空闲 --> <property name="maxIdle" value="10" /> <!-- 连接池最小空闲 --> <property name="minIdle" value="0" /> <!-- 获取连接最大等待时间 --> <property name="maxWait" value="90000" /> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <property name="timeBetweenEvictionRunsMillis" value="60000" /> <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 --> <property name="minEvictableIdleTimeMillis" value="25200000" /> </bean> <!-- ***************事务配置************** --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <aop:config> <aop:advisor pointcut="execution(* com.jeecg.service.*.*(..))" advice-ref="txAdvice" /> <aop:advisor pointcut="execution(* smart.service.*.*(..))" advice-ref="txAdvice" /> <aop:advisor pointcut="execution(* scott.service.*.*(..))" advice-ref="txAdvice" /> <!-- <aop:aspect id="LogAspect" ref="logBean"> <aop:pointcut id="smartService" expression="execution(* smart.service.*.*(..))" /> <aop:pointcut id="baseService" expression="execution(* com.base.service.*.*(..))" /> <aop:pointcut id="jeecgService" expression="execution(* com.jeecg.service.*.*(..))" /> --> <!-- <aop:before pointcut-ref="smartService" method="doBefore"/> --> <!-- <aop:after pointcut-ref="smartService" method="doAfter"/> --> <!-- <aop:around pointcut-ref="smartService" method="doAround"/> <aop:around pointcut-ref="baseService" method="doAround"/> <aop:around pointcut-ref="jeecgService" method="doAround"/> --> <!-- <aop:after-throwing pointcut-ref="smartService" method="doThrowing" throwing="ex"/> --> <!-- </aop:aspect> --> </aop:config> <bean id="logBean" class="com.base.util.LogAspect" /> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="get*" read-only="true" /> <tx:method name="query*" read-only="true" /> <tx:method name="find*" read-only="true" /> <tx:method name="load*" read-only="true" /> <tx:method name="select*" read-only="true" /> <tx:method name="*" propagation="REQUIRED" rollback-for="Exception" /> </tx:attributes> </tx:advice> <!-- 扫描 MyBatis Sql --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="mapperLocations"> <list> <!-- <value>classpath:com/jeecg/mapper/*Mapper.xml</value> <value>classpath:scott/mapper/*/*Mapper.xml</value> --> <value>classpath:smart/mapper/*Mapper.xml</value> </list> </property> <property name="configLocation" value="classpath:mybatis-config.xml" /> </bean> <!-- 扫描mapper.java --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" autowire="byName"> <property name="basePackage" value="com.jeecg.dao,scott.dao.*,smart.dao" /> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean> <!-- Spring 工具类 --> <bean id="springContextUtil" class="com.base.util.SpringContextUtil" /> </beans>

Sping 构造方法注入 错误 java.lang.IllegalStateException: Failed to load ApplicationContext

错误信息 Mon Oct 08 10:39:48 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification. Mon Oct 08 10:39:48 CST 2018 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification. 10:39:48,985 ERROR TestContextManager:314 - Caught exception while allowing TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener@d4602a] to prepare test instance [org.konghao.cms.service.TestIndexService@21ae6e73] java.lang.IllegalStateException: Failed to load ApplicationContext at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99) at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:122) at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:105) at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:74) at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:312) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:284) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:538) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:760) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:460) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:206) Caused by: java.lang.IllegalArgumentException at org.springframework.asm.ClassReader.<init>(Unknown Source) at org.springframework.asm.ClassReader.<init>(Unknown Source) at org.springframework.asm.ClassReader.<init>(Unknown Source) at org.springframework.core.LocalVariableTableParameterNameDiscoverer.inspectClass(LocalVariableTableParameterNameDiscoverer.java:110) at org.springframework.core.LocalVariableTableParameterNameDiscoverer.getParameterNames(LocalVariableTableParameterNameDiscoverer.java:85) at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:193) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1051) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:955) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:490) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:910) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:853) at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768) at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:795) at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:723) at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:196) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1051) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:955) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:490) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:461) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:626) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479) at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:120) at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60) at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:100) at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:248) at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContextInternal(CacheAwareContextLoaderDelegate.java:64) at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:91) ... 25 more 测试类代码 package org.konghao.cms.service; import javax.inject.Inject; import org.junit.Test; import org.junit.runner.RunWith; import org.konghao.basic.model.SystemContext; import org.konghao.cms.service.IIndexService; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("/beans.xml") public class TestIndexService { @Inject private IIndexService indexService; private String rp="D:\\teach_source\\class2\\j2EE\\cms2013\\cms-web\\src\\main\\webapp"; @Test public void testGenerateTop() { SystemContext.setRealPath(rp); indexService.generateTop(); } } package org.konghao.cms.service; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.inject.Inject; import org.konghao.basic.model.SystemContext; import org.konghao.basic.util.FreemarkerUtil; import org.konghao.cms.model.Channel; import org.konghao.cms.web.BaseInfoUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service("indexService") public class IndexService implements IIndexService { private String ftlPath; private String outPath; private FreemarkerUtil util; @Autowired(required=true) public IndexService(String ftlPath, String outPath) { super(); if(util==null) { this.ftlPath = ftlPath; this.outPath = outPath; util=FreemarkerUtil.getInstance(ftlPath); } } private IChannelService channelService; public IChannelService getChannelService() { return channelService; } @Inject public void setChannelService(IChannelService channelService) { this.channelService = channelService; } @Override public void generateTop() { List<Channel> cs = channelService.listTopNavChannel(); Map<String, Object>root = new HashMap<String, Object>(); root.put("navs", cs); String outfile =SystemContext.getRealPath()+outPath+"/top.jsp"; util.fprint(root,"/top.ftl",outfile); } } bean.xml 文件 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <!-- 打开Spring的Annotation支持 --> <context:annotation-config /> <!-- 设定Spring 去哪些包中找Annotation --> <context:component-scan base-package="org.konghao" /> <bean id="ftlPath" class="java.lang.String"> <constructor-arg value="/ftl"/> </bean> <bean id="outPath" class="java.lang.String"> <constructor-arg value="/jsp/template"/> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- 配置连接池的初始值 --> <property name="initialSize" value="1" /> <!-- 连接池的最大值 --> <!-- <property name="maxActive" value="500"/> --> <!-- 最大空闲时,当经过一个高峰之后,连接池可以将一些用不到的连接释放,一直减少到maxIdle为止 --> <!-- <property name="maxIdle" value="2"/> --> <!-- 当最小空闲时,当连接少于minIdle时会自动去申请一些连接 --> <property name="minIdle" value="1" /> <property name="maxActive" value="100" /> <property name="maxIdle" value="20" /> <property name="maxWait" value="1000" /> </bean> <!--创建Spring的SessionFactory工厂 --> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- 和hibernate4整合没有提供专门的针对Annotation的类,直接在LocalSessionFactoryBean中已经集成 --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <!-- 注入数据源 --> <property name="dataSource" ref="dataSource" /> <!-- 设置Spring取那个包中查找相应的实体类 --> <property name="packagesToScan"> <value>org.konghao.cms.model</value> </property> <property name="hibernateProperties"> <!-- <value> hibernate.dialect=org.hibernate.dialect.HSQLDialect </value> --> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.format_sql">false</prop> </props> </property> </bean> <!-- 配置Spring的事务处理 --> <!-- 创建事务管理器--> <bean id="txManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <!-- 配置AOP,Spring是通过AOP来进行事务管理的 --> <aop:config> <!-- 设置pointCut表示哪些方法要加入事务处理 --> <!-- 以下的事务是声明在DAO中,但是通常都会在Service来处理多个业务对象逻辑的关系,注入删除,更新等,此时如果在执行了一个步骤之后抛出异常 就会导致数据不完整,所以事务不应该在DAO层处理,而应该在service,这也就是Spring所提供的一个非常方便的工具,声明式事务 --> <aop:pointcut id="allMethods" expression="execution(* org.konghao.cms.service.*.*(..))" /> <!-- 通过advisor来确定具体要加入事务控制的方法 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="allMethods" /> </aop:config> <!-- 配置哪些方法要加入事务控制 --> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <!-- 让所有的方法都加入事务管理,为了提高效率,可以把一些查询之类的方法设置为只读的事务 --> <tx:method name="*" propagation="REQUIRED" read-only="true"/> <!-- 以下方法都是可能设计修改的方法,就无法设置为只读 --> <tx:method name="add*" propagation="REQUIRED"/> <tx:method name="del*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="save*" propagation="REQUIRED"/> <tx:method name="clear*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <!-- <aop:config> <aop:aspect ref="indexService"> <aop:pointcut id="generateTopPoint" expression="execution(* org.kongkao.cms.service.channelService.add*(..))|| execution(* org.konghao.cms.service.ChannelService.del*(..))|| execution(* org.konghao.cms.service.ChannelService.update*(..))"/> <aop:after method="generteTop" pointcut-ref="generateTopPoint"/> </aop:aspect> </aop:config> --> </beans>

在中国程序员是青春饭吗?

今年,我也32了 ,为了不给大家误导,咨询了猎头、圈内好友,以及年过35岁的几位老程序员……舍了老脸去揭人家伤疤……希望能给大家以帮助,记得帮我点赞哦。 目录: 你以为的人生 一次又一次的伤害 猎头界的真相 如何应对互联网行业的「中年危机」 一、你以为的人生 刚入行时,拿着傲人的工资,想着好好干,以为我们的人生是这样的: 等真到了那一天,你会发现,你的人生很可能是这样的: ...

程序员请照顾好自己,周末病魔差点一套带走我。

程序员在一个周末的时间,得了重病,差点当场去世,还好及时挽救回来了。

和黑客斗争的 6 天!

互联网公司工作,很难避免不和黑客们打交道,我呆过的两家互联网公司,几乎每月每天每分钟都有黑客在公司网站上扫描。有的是寻找 Sql 注入的缺口,有的是寻找线上服务器可能存在的漏洞,大部分都...

搜狗输入法也在挑战国人的智商!

故事总是一个接着一个到来...上周写完《鲁大师已经彻底沦为一款垃圾流氓软件!》这篇文章之后,鲁大师的市场工作人员就找到了我,希望把这篇文章删除掉。经过一番沟通我先把这篇文章从公号中删除了...

总结了 150 余个神奇网站,你不来瞅瞅吗?

原博客再更新,可能就没了,之后将持续更新本篇博客。

副业收入是我做程序媛的3倍,工作外的B面人生是怎样的?

提到“程序员”,多数人脑海里首先想到的大约是:为人木讷、薪水超高、工作枯燥…… 然而,当离开工作岗位,撕去层层标签,脱下“程序员”这身外套,有的人生动又有趣,马上展现出了完全不同的A/B面人生! 不论是简单的爱好,还是正经的副业,他们都干得同样出色。偶尔,还能和程序员的特质结合,产生奇妙的“化学反应”。 @Charlotte:平日素颜示人,周末美妆博主 大家都以为程序媛也个个不修边幅,但我们也许...

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

如果你是老板,你会不会踢了这样的员工?

有个好朋友ZS,是技术总监,昨天问我:“有一个老下属,跟了我很多年,做事勤勤恳恳,主动性也很好。但随着公司的发展,他的进步速度,跟不上团队的步伐了,有点...

我入职阿里后,才知道原来简历这么写

私下里,有不少读者问我:“二哥,如何才能写出一份专业的技术简历呢?我总感觉自己写的简历太烂了,所以投了无数份,都石沉大海了。”说实话,我自己好多年没有写过简历了,但我认识的一个同行,他在阿里,给我说了一些他当年写简历的方法论,我感觉太牛逼了,实在是忍不住,就分享了出来,希望能够帮助到你。 01、简历的本质 作为简历的撰写者,你必须要搞清楚一点,简历的本质是什么,它就是为了来销售你的价值主张的。往深...

优雅的替换if-else语句

场景 日常开发,if-else语句写的不少吧??当逻辑分支非常多的时候,if-else套了一层又一层,虽然业务功能倒是实现了,但是看起来是真的很不优雅,尤其是对于我这种有强迫症的程序"猿",看到这么多if-else,脑袋瓜子就嗡嗡的,总想着解锁新姿势:干掉过多的if-else!!!本文将介绍三板斧手段: 优先判断条件,条件不满足的,逻辑及时中断返回; 采用策略模式+工厂模式; 结合注解,锦...

离职半年了,老东家又发 offer,回不回?

有小伙伴问松哥这个问题,他在上海某公司,在离职了几个月后,前公司的领导联系到他,希望他能够返聘回去,他很纠结要不要回去? 俗话说好马不吃回头草,但是这个小伙伴既然感到纠结了,我觉得至少说明了两个问题:1.曾经的公司还不错;2.现在的日子也不是很如意。否则应该就不会纠结了。 老实说,松哥之前也有过类似的经历,今天就来和小伙伴们聊聊回头草到底吃不吃。 首先一个基本观点,就是离职了也没必要和老东家弄的苦...

2020阿里全球数学大赛:3万名高手、4道题、2天2夜未交卷

阿里巴巴全球数学竞赛( Alibaba Global Mathematics Competition)由马云发起,由中国科学技术协会、阿里巴巴基金会、阿里巴巴达摩院共同举办。大赛不设报名门槛,全世界爱好数学的人都可参与,不论是否出身数学专业、是否投身数学研究。 2020年阿里巴巴达摩院邀请北京大学、剑桥大学、浙江大学等高校的顶尖数学教师组建了出题组。中科院院士、美国艺术与科学院院士、北京国际数学...

男生更看重女生的身材脸蛋,还是思想?

往往,我们看不进去大段大段的逻辑。深刻的哲理,往往短而精悍,一阵见血。问:产品经理挺漂亮的,有点心动,但不知道合不合得来。男生更看重女生的身材脸蛋,还是...

程序员为什么千万不要瞎努力?

本文作者用对比非常鲜明的两个开发团队的故事,讲解了敏捷开发之道 —— 如果你的团队缺乏统一标准的环境,那么即使勤劳努力,不仅会极其耗时而且成果甚微,使用...

为什么程序员做外包会被瞧不起?

二哥,有个事想询问下您的意见,您觉得应届生值得去外包吗?公司虽然挺大的,中xx,但待遇感觉挺低,马上要报到,挺纠结的。

当HR压你价,说你只值7K,你该怎么回答?

当HR压你价,说你只值7K时,你可以流畅地回答,记住,是流畅,不能犹豫。 礼貌地说:“7K是吗?了解了。嗯~其实我对贵司的面试官印象很好。只不过,现在我的手头上已经有一份11K的offer。来面试,主要也是自己对贵司挺有兴趣的,所以过来看看……”(未完) 这段话主要是陪HR互诈的同时,从公司兴趣,公司职员印象上,都给予对方正面的肯定,既能提升HR的好感度,又能让谈判气氛融洽,为后面的发挥留足空间。...

面试:第十六章:Java中级开发(16k)

HashMap底层实现原理,红黑树,B+树,B树的结构原理 Spring的AOP和IOC是什么?它们常见的使用场景有哪些?Spring事务,事务的属性,传播行为,数据库隔离级别 Spring和SpringMVC,MyBatis以及SpringBoot的注解分别有哪些?SpringMVC的工作原理,SpringBoot框架的优点,MyBatis框架的优点 SpringCould组件有哪些,他们...

面试阿里p7,被按在地上摩擦,鬼知道我经历了什么?

面试阿里p7被问到的问题(当时我只知道第一个):@Conditional是做什么的?@Conditional多个条件是什么逻辑关系?条件判断在什么时候执...

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

大三实习生,字节跳动面经分享,已拿Offer

说实话,自己的算法,我一个不会,太难了吧

程序员垃圾简历长什么样?

已经连续五年参加大厂校招、社招的技术面试工作,简历看的不下于万份 这篇文章会用实例告诉你,什么是差的程序员简历! 疫情快要结束了,各个公司也都开始春招了,作为即将红遍大江南北的新晋UP主,那当然要为小伙伴们做点事(手动狗头)。 就在公众号里公开征简历,义务帮大家看,并一一点评。《启舰:春招在即,义务帮大家看看简历吧》 一石激起千层浪,三天收到两百多封简历。 花光了两个星期的所有空闲时...

《Oracle Java SE编程自学与面试指南》最佳学习路线图2020年最新版(进大厂必备)

正确选择比瞎努力更重要!

《Oracle Java SE编程自学与面试指南》最佳学习路线图(2020最新版)

正确选择比瞎努力更重要!

都前后端分离了,咱就别做页面跳转了!统统 JSON 交互

文章目录1. 无状态登录1.1 什么是有状态1.2 什么是无状态1.3 如何实现无状态1.4 各自优缺点2. 登录交互2.1 前后端分离的数据交互2.2 登录成功2.3 登录失败3. 未认证处理方案4. 注销登录 这是本系列的第四篇,有小伙伴找不到之前文章,松哥给大家列一个索引出来: 挖一个大坑,Spring Security 开搞! 松哥手把手带你入门 Spring Security,别再问密...

字节跳动面试官竟然问了我JDBC?

轻松等回家通知

面试官:你连SSO都不懂,就别来面试了

大厂竟然要考我SSO,卧槽。

阿里面试官让我用Zk(Zookeeper)实现分布式锁

他可能没想到,我当场手写出来了

终于,月薪过5万了!

来看几个问题想不想月薪超过5万?想不想进入公司架构组?想不想成为项目组的负责人?想不想成为spring的高手,超越99%的对手?那么本文内容是你必须要掌握的。本文主要详解bean的生命...

自从喜欢上了B站这12个UP主,我越来越觉得自己是个废柴了!

不怕告诉你,我自从喜欢上了这12个UP主,哔哩哔哩成为了我手机上最耗电的软件,几乎每天都会看,可是吧,看的越多,我就越觉得自己是个废柴,唉,老天不公啊,不信你看看…… 间接性踌躇满志,持续性混吃等死,都是因为你们……但是,自己的学习力在慢慢变强,这是不容忽视的,推荐给你们! 都说B站是个宝,可是有人不会挖啊,没事,今天咱挖好的送你一箩筐,首先啊,我在B站上最喜欢看这个家伙的视频了,为啥 ,咱撇...

代码注释如此沙雕,会玩还是你们程序员!

某站后端代码被“开源”,同时刷遍全网的,还有代码里的那些神注释。 我们这才知道,原来程序员个个都是段子手;这么多年来,我们也走过了他们的无数套路… 首先,产品经理,是永远永远吐槽不完的!网友的评论也非常扎心,说看这些代码就像在阅读程序员的日记,每一页都写满了对产品经理的恨。 然后,也要发出直击灵魂的质问:你是尊贵的付费大会员吗? 这不禁让人想起之前某音乐app的穷逼Vip,果然,穷逼在哪里都是...

立即提问
相关内容推荐