课程 1.4 引导您创建 Web 项目以测试应用程序。
<%@page session="false"%>
<HTML>
<HEAD>
<TITLE>IBM WebSphere EJB 3.1 and JPA 2.0 Counter Sample</TITLE>
<BODY bgcolor="cornsilk">
<H1>EJB 3.1 and JPA 2.0 Counter Sample</H1>
<P>
<B>
This application communicates with the WebSphere Application Server using http requests to increment a singleton EJB 3.1 counter bean which is using a JPA 2.0 entity (ie. keeps a persistent counter in a Derby database table).
</B>
<FORM METHOD=POST ACTION="counter">
<BR/>
<%
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires",0);
String msg = (String) request.getAttribute("msg");
if (msg == null) msg = "";
%>
<B>Click on the Increment button to increment the count</B>
<BR/><BR/>
<INPUT TYPE=SUBMIT VALUE="Increment">
</FORM>
<H3><%=msg%></H3>
</BODY>
</HTML>
package com.ibm.example.websphere.ejb3sample.counter;
// This program may be used, executed, copied, modified and distributed
// without royalty for the purpose of developing, using, marketing, or distributing.
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.Servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* This servlet demonstrates an EJB3 counter bean with JPA.
*/
@WebServlet(
description="This servlet demonstrates the various ways to increment EJB 3.1 counter beans.",
name="EJB Count Servlet",
displayName="EJB Count Servlet",
urlPatterns="/counter"
)
public class EJBCount extends HttpServlet {
private static final long serialVersionUID = -5983708570653958619L;
// Use injection to get the ejb
@EJB private LocalCounter singletonCounter;
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String msg = null;
int ejbCount = 0;
try {
ejbCount = singletonCounter.getTheValue();
}
catch (RuntimeException e) {
msg = "Error - getTheValue() method on EJB failed!";
e.printStackTrace();
}
msg = "EJB Count value for Singleton Bean with JPA: " + ejbCount;
// Set attributes and dispatch the JSP.
req.setAttribute("msg", msg);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/EJBCount.jsp");
rd.forward(req, res);
}
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String msg = null;
int ejbCount = 0;
try {
ejbCount = singletonCounter.increment();
}
catch (RuntimeException e) {
msg = "Error - increment() method on EJB failed!";
e.printStackTrace();
}
msg = "EJB Count value for Singleton Bean with JPA: " + ejbCount;
// Set attibutes and dispatch the JSP.
req.setAttribute("msg", msg);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/EJBCount.jsp");
rd.forward(req, res);
}
}