Java/Servlets/JNDI
Версия от 18:01, 31 мая 2010; (обсуждение)
Содержание
Email JNDI Filter
import java.io.IOException;
import java.io.PrintWriter;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.mail.*;
import javax.mail.internet.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class EmailJndiServlet extends HttpServlet {
private Session mailSession;
public void init() throws ServletException {
Context env = null;
try{
env = (Context) new InitialContext();
mailSession = (Session) env.lookup("MyEmail");
if (mailSession == null)
throw new ServletException(
"MyEmail is an unknown JNDI object");
//close the InitialContext
env.close();
} catch (NamingException ne) {
try{ env.close();} catch (NamingException nex) { }
throw new ServletException(ne);
}
}
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
java.io.IOException {
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter();
out.println(
"<html><head><title>Email message sender</title></head><body>");
String to = request.getParameter("to");
String from = request.getParameter("from");
String subject = request.getParameter("subject");
String emailContent = request.getParameter("emailContent");
try{
sendMessage(to,from,subject,emailContent);
} catch(Exception exc){
throw new ServletException(exc.getMessage());
}
out.println(
"<h2>The message was sent successfully</h2></body></html>");
out.println("</body></html>");
out.close();
} //doPost
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
java.io.IOException {
doPost(request,response);
}
private void sendMessage(String to, String from,String subject,
String bodyContent) throws Exception {
Message mailMsg = null;
synchronized(mailSession){
mailMsg = new MimeMessage(mailSession);//a new email message
}
InternetAddress[] addresses = null;
try {
if (to != null) {
//throws "AddressException" if the "to" email address
//violates RFC822 syntax
addresses = InternetAddress.parse(to, false);
mailMsg.setRecipients(Message.RecipientType.TO, addresses);
} else {
throw new MessagingException(
"The mail message requires a "To" address.");
}
if (from != null)
mailMsg.setFrom(new InternetAddress(from));
if (subject != null)
mailMsg.setSubject(subject);
if (bodyContent != null)
mailMsg.setText(bodyContent);
//Finally, send the mail message; throws a "SendFailedException"
//if any of the message"s recipients have an invalid adress
Transport.send(mailMsg);
} catch (Exception exc) {
throw exc;
}
}//sendMessage
}//EmailJndiServlet
JNDI Filter
import java.io.IOException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
public class JndiFilter implements Filter {
private FilterConfig config;
private Context env;
public JndiFilter() {
}
public void init(FilterConfig filterConfig) throws ServletException {
this.config = filterConfig;
try {
env = (Context) new InitialContext();
} catch (NamingException ne) {
throw new ServletException(ne);
}
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
javax.mail.Session mailSession = null;
try {
mailSession = (javax.mail.Session) env.lookup("MyEmail");
} catch (NamingException ne) {
}
HttpServletRequest hRequest = null;
if (request instanceof HttpServletRequest) {
hRequest = (HttpServletRequest) request;
HttpSession hSession = hRequest.getSession();
if (hSession != null)
hSession.setAttribute("MyEmail", mailSession);
}//if
chain.doFilter(request, response);
}// doFilter
public void destroy() {
/*
* called before the Filter instance is removed from service by the web
* container
*/
}
}
Servlet JNDI and Bean
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class BeanServlet extends HttpServlet {
private StockPriceBean spbean;
public void init() throws ServletException {
Context env = null;
try {
// Compile error since there is no StockPriceBean.class
// change the name according to your requirements
env = (Context) new InitialContext().lookup("java:comp/env");
spbean = (StockPriceBean) env.lookup("bean/pricebean");
//close the InitialContext
env.close();
if (spbean == null)
throw new ServletException(
"bean/pricebean is an unknown JNDI object");
} catch (NamingException ne) {
try {
env.close();
} catch (NamingException nex) {
}
throw new ServletException(ne);
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
//set the MIME type of the response, "text/html"
response.setContentType("text/html");
//use a PrintWriter send text data to the client who has requested the
// servlet
java.io.PrintWriter out = response.getWriter();
//Begin assembling the HTML content
out.println("<html><head>");
out.println("<title>Stock Price Fetcher</title></head><body>");
out.println("<h2>Please submit a valid stock symbol</h2>");
//make sure method="post" so that the servlet service method
//calls doPost in the response to this form submit
out.println("<form method=\"post\" action =\""
+ request.getContextPath() + "/namingbean\" >");
out.println("<table border=\"0\"><tr><td valign=\"top\">");
out.println("Stock symbol: </td> <td valign=\"top\">");
out.println("<input type=\"text\" name=\"symbol\" size=\"10\">");
out.println("</td></tr><tr><td valign=\"top\">");
out.println("<input type=\"submit\" value=\"Submit Info\"></td></tr>");
out.println("</table></form>");
out.println("</body></html>");
out.close();
} //end doGet
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException {
String symbol;//this will hold the stock symbol
float price = 0f;
symbol = request.getParameter("symbol");
boolean isValid = (symbol == null || symbol.length() < 1) ? false
: true;
//set the MIME type of the response, "text/html"
response.setContentType("text/html");
//use a PrintWriter send text data to the client who has requested the
// servlet
java.io.PrintWriter out = response.getWriter();
//Begin assembling the HTML content
out.println("<html><head>");
out.println("<title>Latest stock value</title></head><body>");
if ((!isValid) || spbean == null) {
out.println("<h2>Sorry, the stock symbol parameter was either empty or null</h2>");
} else {
out.println("<h2>Here is the latest value of " + symbol + "</h2>");
spbean.setSymbol(symbol);
price = spbean.getLatestPrice();
out.println((price < 1 ? "The symbol is probably invalid." : ""
+ price));
}
out.println("</body></html>");
}// doPost
}//BeanServlet
Use JNDI to get database connection or data source
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
public class Main extends HttpServlet implements Servlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
Connection connection = getConnection();
if (connection != null) {
String sql = "SELECT SYSDATE FROM DUAL";
try{
PreparedStatement statement = connection.prepareStatement(sql);
ResultSet rs = statement.executeQuery();
while (rs.next()) {
Date date = rs.getDate("SYSDATE");
writer.println("The current date is " + dateFormat.format(date));
}
connection.close();
}catch(Exception e){
System.out.println(e);
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
private Connection getConnection() {
Connection connection = null;
try {
InitialContext context = new InitialContext();
DataSource dataSource = (DataSource) context.lookup("jdbc/DataSource");
connection = dataSource.getConnection();
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
}
Web JNDI
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class WebJndiServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
String state = request.getParameter("state");
Context env = null;
Abbrev abbrev = null;
AbbrevHome home = null;
try {
env = (Context) new InitialContext();
Object localH = env.lookup("AbbrevHome");
home = (AbbrevHome) PortableRemoteObject.narrow(localH,
AbbrevHome.class);
//close the InitialContext
env.close();
if (home == null)
throw new ServletException(
"AbbrevHome is an unknown JNDI object");
abbrev = (Abbrev) PortableRemoteObject.narrow(home.create(),
Abbrev.class);
} catch (NamingException ne) {
try {
env.close();
} catch (NamingException nex) {
}
throw new ServletException(ne);
} catch (javax.ejb.CreateException ce) {
throw new ServletException(ce);
}
//set the MIME type of the response, "text/html"
response.setContentType("text/html");
//use a PrintWriter send text data to the client who has requested the
// servlet
java.io.PrintWriter out = response.getWriter();
//Begin assembling the HTML content
out.println("<html><head>");
out.println("<title>State abbreviations</title></head><body>");
out.println("<h2>Here is the state"s abbreviation</h2>");
if (state != null)
out.println(abbrev.getAbbreviation(state.toUpperCase()));
try {
abbrev.remove();
} catch (javax.ejb.RemoveException re) {
}
out.println("</body></html>");
out.close();
} //end doGet
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
doGet(request, response);
}// doPost
}//BeanServlet