日期:2014-05-16  浏览次数:20509 次

jsp 调用spring 执行sql语句方法

利用spring sessionfactory连接数据库管理实务

?

<%@ page language="java" import="java.sql.*,org.hibernate.Transaction" pageEncoding="UTF-8"%>
<%@ page import="org.springframework.context.ApplicationContext"%>
<%@ page import="org.springframework.web.context.support.WebApplicationContextUtils"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
String sql = request.getParameter("sql");
if (sql != null && sql.length() > 0){
?//out.print(sql);
?//上面的CategoryService引用是我自己的东西
//applicationContext.xml中一定要有完整的依赖链,从dataSource到CategoryService

?ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
?BaseServicecs = (BaseService) ctx.getBean("BaseService");

?
?
??Connection conn = cs.getSystemUserDAO().getSessionFactory().openSession().connection();

?Transaction trn = cs.getSystemUserDAO().getSessionFactory().openSession().beginTransaction();
?try {
?
?
??trn.begin();
??
??Statement stmt = conn.createStatement();
??stmt.execute(sql);

??
??trn.commit();
??
??out.print("执行成功");
?} catch (Exception ex) {
??out.print("执行失败,失败原因:" + ex.getMessage());
??trn.rollback();
?}
}
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
? <head>
??? <title>My JSP 'exec_sql.jsp' starting page</title>
???
?<meta http-equiv="pragma" content="no-cache">
?<meta http-equiv="cache-control" content="no-cache">
?<meta http-equiv="expires" content="0">???
?<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
?<meta http-equiv="description" content="This is my page">
?<!--
?<link rel="stylesheet" type="text/css" href="styles.css">
?-->

? </head>
?
? <body>
??? <form action="exec_sql.jsp" method="post">
??? ?<textarea style="width:90%;" rows="30" name="sql"></textarea>
??? ?<br/><br/>
??? ?<input type="submit"/>
??? </form>
? </body>
</html>