spring+servlet 简单演示

加载的jar有:

                           log4j-1.2.16.jar   

                           c3p0-0.9.1.2.jar

                           mysql-connector-java-5.1.14-bin.jar

                           org.springfaramework.asm-3.0.5.release.jar

                           org.springfaramework.beans-3.0.5.release.jar

                           org.springfaramework.context-3.0.5.release.jar

                          
org.springfaramework.core-3.0.5.release.jar

                           org.springfaramework.expression-3.0.5.release.jar

                           org.springfaramework.web-3.0.5.release.jar

                           commons-logging-1.1.1.jar

  

文件结构图如下:


代码如下:

DemoDao.java

package org.baicai.spring.dao;

import java.util.List;

public interface DemoDao {
public List<Object[]> query() throws Exception;

}


DemoDaoImpl.java

package org.baicai.spring.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.baicai.spring.dao.DemoDao;

public class DemoDaoImpl implements DemoDao {
private DataSource source;
 
public DataSource getSource()
{
return source;
}
public void setSource(DataSource source)
{
this.source=source;
}

@Override
public List<Object[]> query() throws Exception {
List<Object[]> list =new ArrayList<Object[]>();
Connection connection=source.getConnection();
PreparedStatement ps = connection.prepareStatement(” select * from User “);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
Object[] datas = new Object[3];
for (int i = 0; i < datas.length; i++) {
datas[i]=rs.getObject(i+1);
}
list.add(datas);
}
connection.close();
return list;
}

}

DemoServlet.java

package org.baicai.spring.servlet;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.baicai.spring.dao.DemoDao;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class DemoServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
private ApplicationContext  context;
private DemoDao dao;

@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
//由于servlet容器的生命周期不受spring管理,所以注入数据需要主动去spring容器内获取
   context = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
   dao=context.getBean(“demoDao”,DemoDao.class);
}


@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
req.setAttribute(“list”, dao.query());
req.getRequestDispatcher(“/Demo/demo.jsp”).forward(req, resp);
} catch (Exception e) {
throw new ServletException(e);
}
 
}

}

context.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”
xsi:schemaLocation=”http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd”>
      
   <bean id=”propertyPlaceholderConfigurer” class=”org.springframework.beans.factory.config.PropertyPlaceholderConfigurer”>
   <property name=”location” value=”classpath:sql.properties”></property>
   </bean> 
   
   <bean id=”c3p0″ class=”com.mchange.v2.c3p0.ComboPooledDataSource” destroy-method=”close”>
      <property name=”driverClass”  value=”${driver}”></property>
      <property name=”jdbcUrl”  value=”${url}”></property>
      <property name=”user”  value=”${username}”></property>
      <property name=”password”  value=”${password}”></property>
   </bean> 
   
   <bean id=”demoDao”  class=”org.baicai.spring.dao.impl.DemoDaoImpl”>
       <property name=”source”  ref=”c3p0″></property>
   </bean> 
</beans>


sql.properties

driver=com.mysql.jdbc.Driver
url=jdbc\:mysql\://127.0.0.1\:3306/mysql?characterEncoding\=utf8
username=root
password=paul


web.xml

<?xml version=”1.0″ encoding=”UTF-8″?>
<web-app version=”3.0″ 
xmlns=”http://java.sun.com/xml/ns/javaee” 
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” 
xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd”>
  <display-name></display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <context-param>
       <description>配置spring监听器查找配置文件位置参数</description>
       <param-name>contextConfigLocation</param-name>
       <param-value>classpath:context.xml</param-value>
  </context-param>
  
  <listener>
       <description>启动spring上下工厂的监听器</description>
       <listener-class>
           org.springframework.web.context.ContextLoaderListener
       </listener-class>
  </listener>
  
  <servlet>
        <servlet-name>demo</servlet-name>
        <servlet-class>org.baicai.spring.servlet.DemoServlet</servlet-class>
  </servlet>
   
   <servlet-mapping>
        <servlet-name>demo</servlet-name>
        <url-pattern>/demo.do</url-pattern>
   </servlet-mapping>
  
</web-app>


index.jsp

<%@ page language=”java” contentType=”text/html; charset=ISO-8859-1″
    pageEncoding=”ISO-8859-1″%>
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1″>
<title>Spring+servlet</title>
</head>
<body>
    <center>
         <a href=”demo.do”>Spring+servlet</a>
    </center>
</body>
</html>


demo.jsp

<%@ page language=”java” contentType=”text/html; charset=ISO-8859-1″
    pageEncoding=”ISO-8859-1″%>
 <%@ taglib uri=”http://java.sun.com/jsp/jstl/core” prefix=”c” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1″>
<title>Spring+servlet</title>
</head>
<body>
   <center>
       <c:forEach items=”${list}” var=”data”>
         <h1>
            ${data[0]}-${data[1]}-${data[2]}
         </h1> 
       </c:forEach>  
   </center>
</body>
</html>


注:spring的演示都没有对编码进行设置


执行结果如下:



« »

发表评论

电子邮件地址不会被公开。 必填项已用*标注

昵称 *