首页 > 代码库 > springMVC-JNDI

springMVC-JNDI

最近在学习JNDI,今天整出来一个demo,拿出来大家分享下。

先上一个项目结构的截图:

1、配置JNDI数据源

  首先,修改一下tomcat的配置文件conf/context.xml

  在Context属性中加入

<Resource name="jndi-web"
        type="javax.sql.DataSource"
        driverClassName="oracle.jdbc.OracleDriver"
        url="jdbc:oracle:thin:@localhost:1521:orcl"
        username="scott"
        password="tigger"
        maxIdle="40"
        maxWait="4000"
        maxActive="250"
        removeAbandoned="true"
        removeAbandonedTimeout="100"
        logAbandoned="true"
        factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
    />

   其次,项目中的web.xml中加入

<resource-ref>
    <description>DB Connection</description>
    <res-ref-name>jndi-web</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

  最后,就是在spring的配置文件applicationContext.xml中加入

<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
        <property name="jndiName">
            <value>java:comp/env/jndi-web</value>
        </property>
    </bean>

  到这里,JNDI的配置就算是结束了。注意:上面3个配置文件中都用到了“jndi-web”的名称,请保持一致性。

2、SpringMVC的配置

  首先,在项目中的web.xml文件中加入

<servlet>
      <servlet-name>test</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
      <servlet-name>test</servlet-name>
      <url-pattern>*.do</url-pattern>
  </servlet-mapping>

  其次,加入controller代码<HelloController.java>:

package com.blanddrift.controller;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import com.blanddrift.util.DataBaseUtil;

public class HelloController implements Controller {

    @Override
    public ModelAndView handleRequest(HttpServletRequest req,
            HttpServletResponse resp) throws Exception {
        Connection conn = DataBaseUtil.getConn();
        List<Map<String, String>> list = new ArrayList<Map<String,String>>(); 
        try {
            Statement stt = conn.createStatement();
            ResultSet rs = stt.executeQuery("select * from emp");
            while(rs.next()) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("empno", rs.getString(1));
                map.put("ename", rs.getString(2));
                map.put("job", rs.getString(3));
                map.put("mgr", rs.getString(4));
                map.put("hiredate", rs.getString(5));
                map.put("sal", rs.getString(6));
                map.put("comm", rs.getString(7));
                map.put("deptno", rs.getString(8));
                list.add(map);
            }
            req.setAttribute("emp", list);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DataBaseUtil.closeConn(conn);
        }
        req.setAttribute("hello", "Welcome to spring!!!");
        return new ModelAndView("welcome");
    }

}

  上面用到一个的DataBaseUtil的代码如下<DataBaseUtil.java>:

package com.blanddrift.util;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class DataBaseUtil {

    private static DataSource ds;
    
    static {
        try {
            Context ctx = new InitialContext();
            ds = (DataSource) ctx.lookup("java:comp/env/jndi-web");
        } catch (NamingException e) {
            e.printStackTrace();
        }
    }
    
    private DataBaseUtil(){}
    
    public synchronized static Connection getConn(){
        
        try {
            return ds.getConnection() != null ? ds.getConnection() : null;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        return null;
    }
    
    public static void closeConn(Connection conn) {
        try{
            if(conn != null) {
                conn.close();
                conn = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
}

  最后,在WEB-INF下新建test-servlet.xml的配置文件(文件名称为web.xml中的<servlet-name>属性 + “-servlet.xml”),文件内容如下:

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>

    <!--缺省映射处理器,不需要明确声明,但声明后就非常清楚使用的是哪个映射处理器 -->
    <bean id="beanNameUrlMapping"
        class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping">
    </bean>

    <!-- 这里的name属性有两个职责,既定义Bean的名字,也定义需要这个控制器处理的URL样式 -->
    <bean name="/hello.do" class="com.blanddrift.controller.HelloController">
    </bean>

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

  根据test-servlet.xml的配置文件可以知道我们需要编写的jsp文件,即/WEB-INF/jsp/welcome.jsp,下面提供welcome.jsp的代码:

<%@page import="java.util.Map"%>
<%@page import="java.util.List"%>
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ page isELIgnored="false" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>Hello World!</title>
 </head>
 <body>
  <h2>
   This is a note which come from Java !!!
  </h2> 
  <h3>
      ${hello }   
  </h3>
  <table border="1" cellpadding="0" cellspacing="0">
      <tr>
          <td>empno</td>
          <td>ename</td>
          <td>job</td>
          <td>mgr</td>
          <td>hiredate</td>
          <td>sal</td>
          <td>comm</td>
          <td>deptno</td>
      </tr>      
      <%
          List<Map<String, String>> list = (List<Map<String, String>>)request.getAttribute("emp");
          for(int i = 0; i < list.size(); i++) {
              Map<String, String> map = list.get(i);
      %>
          <tr>
              <td><%=map.get("empno")%></td>
              <td><%=map.get("ename")%></td>
              <td><%=map.get("job")%></td>
              <td><%=map.get("mgr")%></td>
              <td><%=map.get("hiredate")%></td>
              <td><%=map.get("sal")%></td>
              <td><%=map.get("comm")%></td>
              <td><%=map.get("deptno")%></td>
          </tr>        
      <%
          }
      %>
  </table> 
 </body> 
</html>

3、部署工程,启动刚才修改过context.xml文件的tomcat,访问http://localhost:8080/jndi-web/hello.do,就会得到下面的页面:

 项目的war包:jndi-web.zip