Tomcat7在JNDI中添加定制的JavaBean数据源

1.写一个JavaBean

package com.mycompany;

public class MyBean {
	private String foo = "Default Foo";
	private int bar = 0;
	public String getFoo() {
		return foo;
	}
	public void setFoo(String foo) {
		this.foo = foo;
	}
	public int getBar() {
		return bar;
	}
	public void setBar(int bar) {
		this.bar = bar;
	}

}

2.写一个数据源工厂类实现javax.naming.spi.ObjectFactory接口

package com.mycompany;

import java.util.Enumeration;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;

public class MyBeanFactory implements ObjectFactory {

  public Object getObjectInstance(Object obj,
      Name name, Context nameCtx, Hashtable environment)
      throws NamingException {

      // Acquire an instance of our specified bean class
      MyBean bean = new MyBean();

      // Customize the bean properties from our attributes
      Reference ref = (Reference) obj;
      Enumeration addrs = ref.getAll();
      while (addrs.hasMoreElements()) {
          RefAddr addr = (RefAddr) addrs.nextElement();
          String name1 = addr.getType();
          String value = (String) addr.getContent();
          if (name1.equals("foo")) {
              bean.setFoo(value);
          } else if (name1.equals("bar")) {
              try {
                  bean.setBar(Integer.parseInt(value));
              } catch (NumberFormatException e) {
                  throw new NamingException("Invalid 'bar' value " + value);
              }
          }
      }

      // Return the customized instance
      return (bean);

  }

}

3.在WEB-INF/web.xml中添加JNDI名字和bean实例的映射

JNDI的配置在<resource-env-ref>标签下,下面是完整的web.xml文档

(注<resource-ref>标签用于配置JavaMail和数据库)


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>jndiDemo1</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <resource-env-ref>
    <description>
    	Object factory for MyBean instances.
 	 </description>
    <resource-env-ref-name>
   		 bean/MyBeanFactory
  	</resource-env-ref-name>
   	 <resource-env-ref-type>
   	     com.mycompany.MyBean
 	</resource-env-ref-type>
  </resource-env-ref>
</web-app>

4.编写JSP页


<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page import="javax.naming.*,com.mycompany.*"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%
		Context initCtx;
		initCtx = new InitialContext();
		Context envCtx = (Context) initCtx.lookup("java:comp/env");
		MyBean bean = (MyBean) envCtx.lookup("bean/MyBeanFactory");
		String outstr = "foo = " + bean.getFoo() + ", bar = "
				+ bean.getBar();
		System.out.println(outstr);
	%>
	输出结果为:
	<br />
	<%=outstr%>
</body>
</html>

5.配置tomcat数据源,为了方便移植,这里在META-INF/context.xml中配置

<Context>标签下添加<Resource>

<?xml version="1.0" encoding="UTF-8"?>
<Context>   
    <Resource name="bean/MyBeanFactory" auth="Container"
            type="com.mycompany.MyBean"
            factory="com.mycompany.MyBeanFactory"
            singleton="false"
            bar="23"/>
</Context>

6.部署到tomcat之后运行JSP页

大功告成

 

下面是一个配置Personbean的JNDI的例子

1.写bean

package com.myexample;

public class Person {
	private String userName;
	private String password;
	private String nickName;
	private int age;
	private String sex;
	private String addr;
	private String phoneNumber;
	

	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;
	}
	public String getNickName() {
		return nickName;
	}
	public void setNickName(String nickName) {
		this.nickName = nickName;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getAddr() {
		return addr;
	}
	public void setAddr(String addr) {
		this.addr = addr;
	}
	public String getPhoneNumber() {
		return phoneNumber;
	}
	public void setPhoneNumber(String phoneNumber) {
		this.phoneNumber = phoneNumber;
	}

}


2.写工厂类

package com.myexample;

import java.util.Enumeration;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;

public class PersonFactory implements ObjectFactory {

	@Override
	public Object getObjectInstance(Object obj, Name name, Context nameCtx,
			Hashtable environment) throws NamingException {

		Person person = new Person();

		Reference ref = (Reference) obj;
		Enumeration addrs = ref.getAll();
		while (addrs.hasMoreElements()) {
			RefAddr addr = (RefAddr) addrs.nextElement();
			String name1 = addr.getType();
			String value = (String) addr.getContent();
			if (name1.equals("userName")) {
				person.setUserName(value);
			} else if (name1.equals("password")) {
				person.setPassword(value);
			} else if (name1.equals("nickName")) {
				person.setNickName(value);
			} else if (name1.equals("age")) {
				try {
					person.setAge(Integer.parseInt(value));
				} catch (NumberFormatException e) {
					throw new NamingException("Invalid 'age' value " + value);
				}
			} else if (name1.equals("sex")) {
				if ("male".equals(value)||"female".equals(value)) {
					person.setSex(value);
				}else{
					throw new NamingException("Invalid 'sex' value " + value);
				}
			} else if (name1.equals("addr")) {
				person.setAddr(value);;
			}else if (name1.equals("phoneNumber")) {
				try {
					Integer.parseInt(value);
					person.setPhoneNumber(value);
				} catch (NumberFormatException e) {
					throw new NamingException("Invalid 'phoneNumber' value " + value);
				}
			}
		}

		return (person);
	}
}

3.写WEB-INF/web.xml

 <resource-env-ref>
    <description>
    	Object factory for MyPerson instances.
 	 </description>
    <resource-env-ref-name>
   		 bean/PersonFactory
  	</resource-env-ref-name>
   	 <resource-env-ref-type>
   	     com.myexample.Person
 	</resource-env-ref-type>
  </resource-env-ref>

4.编写Servlet

package com.myexample.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.myexample.Person;

/**
 * Servlet implementation class servletDemo1
 */
@WebServlet("/servletDemo1")
public class servletDemo1 extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		Context initCtx;
		try {
			initCtx = new InitialContext();
			Context envCtx = (Context) initCtx.lookup("java:comp/env");
			Person person = (Person) envCtx.lookup("bean/PersonFactory");
			String outstr = "userName = " + person.getUserName();
			System.out.println(outstr);
			response.setCharacterEncoding("UTF-8");
			PrintWriter  writer = response.getWriter();
			writer.print("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
			writer.print(outstr);
		} catch (NamingException e) {
			e.printStackTrace();
		}
		

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

5.写 META-INF/context.xml

<Resource name="bean/PersonFactory" auth="Container"
		type="com.myexample.Person" factory="com.myexample.PersonFactory"
		singleton="false" userName="小明"/>

6.部署到tomcat之后,运行Servlet

上面servlet是3.0的标准(用注解@WebServlet映射URL),如果用2.5的标准,需要在web.xml中配置如下内容

 <servlet>
  	<servlet-name>servletDemo1</servlet-name>
  	<servlet-class>com.myexample.servlet.servletDemo1</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>servletDemo1</servlet-name>
  	<url-pattern>/servletDemo1</url-pattern>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值