Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 53 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
53
Dung lượng
490,44 KB
Nội dung
//Setting the query criteria. memberVO.setUserId(userId); memberVO.setPassword(password); MemberDAO memberDAO = new MemberDAO(); try{ memberVO = (MemberVO) memberDAO.findByCriteria(memberVO); if(memberVO == null) { if (log.isInfoEnabled()) { log.info( "Failed Login Attempt. Username:" + userId + " Password:" + password); } } else { If (log.isInfoEnabled()) { log.info("Successful Login Attempt for user:" + userId); } } } catch(DataAccessException e){ log.error("Error in MemberManagerBD.authenticate()", e); throw new ApplicationException( "Error in MemberManagerBD.validateUserId(): " + e.toString(),e); } log.debug("authenticate() finished"); return memberVO; } Notice that for failed attempts you write both the user name and the password to the log file, whereas on successful attempts you write just the user name. The last thing you want to do is compromise the security of the JavaEdge application by storing valid user name and password combinations in a plain text file. Logging in the Web Tier Now to the section you’ve been waiting for! Logging in Struts Actions or ActionForms You can, of course, add any kind of logging you want to your Struts actions or ActionForms, but since most if not all of the logic in your application will reside in the business tier, there isn’t really that much to log. Couple this with the extensive log output available from Struts, and you shouldn’t need to perform any logging inside of your actions or ActionForms. CHAPTER 9 ■ LOGGING AND DEBUGGING 349 Ch09_7389_CMP3 9/27/06 11:39 AM Page 349 Logging ApplicationExceptions The ApplicationException class derives indirectly from RuntimeException, making it an unchecked exception—that is, there is no need to either catch the exception within a method or declare it as thrown by that method. The JavaEdge application relies on Struts’ ability to handle exceptions globally using a global exception handler. For the JavaEdge application, you build a global exception handler that sends the error details to an e-mail recipient. This is useful since it means that you can alert an administrator if something goes wrong in the appli- cation. However, you also want any ApplicationExceptions to be logged in the application log file. Since all ApplicationExceptions are caught and handled globally, this is a simple matter. All you need to do is add the logging code to the MailExceptionHandler: public class MailExceptionHandler extends ExceptionHandler { private static Log log = ServiceLocator.getInstance().getLog(MailExceptionHandler.class); public ActionForward execute(Exception e, ExceptionConfig ex, ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws ServletException{ ActionForward forward = super.execute(e, ex, mapping, form, request, response); Properties props = new Properties(); //Getting the name of the e-mail server. props.put("mail.smtp.host", "netchange.us"); props.put("mail.from", "JavaEdgeApplication"); Session session = Session.getDefaultInstance(props, null); session.setDebug(false); // Write the exception details to the log file. log.error("An ApplicationException has occurred", e); Message msg = new MimeMessage(session); try{ msg.setFrom(); //Setting who is supposed to receive the e-mail. InternetAddress to = new InternetAddress("john.carnell@netchange.us"); CHAPTER 9 ■ LOGGING AND DEBUGGING350 Ch09_7389_CMP3 9/27/06 11:39 AM Page 350 //Setting the important text. msg.setRecipient(MimeMessage.RecipientType.TO, to); msg.setSubject("Error message occurred in Action:" + mapping.getName()); msg.setText( "An error occurred while trying to invoke execute() on Action:" + mapping.getName() + ". Error is: " + e.getMessage()); Transport.send(msg); if (log.isDebugEnabled()) { log.debug("E-Mail sent to:" + to); } } catch(Exception exception){ log.error(" ==================================="); log.error( "An error has occurred in the MailExceptionHandler" + "while trying to process Action:" + mapping.getName()); log.error("Exception raised is : " + exception.getMessage()); log.error("Original Exception: " + e.getMessage()); log.error("===================================="); } return forward; } } Notice that not only do you log the actual ApplicationException, but you also log when an e-mail is sent successfully and when one fails. This way you have proof that the administra- tor was notified of the error and you can also diagnose any errors with the mail delivery easily. Debugging Struts Applications Using JBoss and Eclipse So far, everything in this chapter has been focused on logging technologies and building and logging implementations for your application. In this final section, we are going to demon- strate how you can debug your Struts-based applications running in JBoss using the Eclipse open source IDE. We are not going to go into the details about what a debugger is and how to use one, since we assume you are already familiar with that topic. Instead, we want to give a practical demonstration of debugging Struts applications with JBoss and Eclipse, so that you will be able to use the knowledge in your own debugging. JBoss IDE Eclipse Plug-Ins We assume at this point you already have Eclipse and JBoss installed on your machine. If not, you will find more information on obtaining Eclipse in Appendix A and more information on obtaining and setting up JBoss in Appendix B. CHAPTER 9 ■ LOGGING AND DEBUGGING 351 Ch09_7389_CMP3 9/27/06 11:39 AM Page 351 Once you have those applications up and running, you need to obtain the JBoss IDE. JBoss IDE is a set of plug-ins developed by JBoss for use with Eclipse. Amongst other things, the JBoss IDE plug-ins add support for managing JBoss servers directly from the Eclipse IDE, hot code deployment, and application server debugging. You can download the JBoss IDE from http://www.jboss.org. Once you have the download, you need to unpack it and place the plug-ins in the appropriate directory in your Eclipse program directory. Configuring the JBoss Server Once you have the JBoss IDE plug-ins installed, the first thing you need to do is configure the JBoss server instance. To do this, you need to open the Server Navigator view by going to Window ➤ Show View ➤ Other and selecting the view from the JBoss IDE category, as shown in Figure 9-1. Figure 9-1. Eclipse view browser Once the Server Navigator is displayed, right-click it and choose Configuration. When the Configuration dialog box appears, right-click the appropriate icon for your version of JBoss and choose New from the pop-up menu. Enter a meaningful name for your server and then enter the path to the JBoss home directory in the corresponding box, as shown in Figure 9-2. The home directory is the one containing the bin directory, not the bin directory itself. CHAPTER 9 ■ LOGGING AND DEBUGGING352 Ch09_7389_CMP3 9/27/06 11:39 AM Page 352 Figure 9-2. JBoss IDE server configuration Under the JDK tab, make sure that the JDK selected is actually a full JDK and not just a JRE. When we first installed the plug-in on our Windows machine, it picked up the Sun JRE instead of our BEA JDK. Once that is done, click Apply and then Debug. When the Configuration dialog box closes, the JBoss application server will start up inside the Eclipse IDE. You will see all the messages that usually go to the console being streamed through the Eclipse Console window. Debugging the JavaEdge Application To start debugging, you need to create a new project in Eclipse to hold the JavaEdge source code. To create a new project, go to File ➤ New ➤ Project and select Java Project from the dialog box. CHAPTER 9 ■ LOGGING AND DEBUGGING 353 Ch09_7389_CMP3 9/27/06 11:39 AM Page 353 When you create the project, don’t create it in the same folder as the JavaEdge source code. Instead, once the project is created, right-click it in the Package Explorer and choose Import from the menu. When the Import dialog box opens, choose File System as shown in Figure 9-3, and click Next. Figure 9-3. Eclipse Import dialog box You are now prompted to choose the folder to import, so select the folder containing the JavaEdge source code. You need to check the box displayed next to the source folder as shown in Figure 9-4 to make sure Eclipse includes all the source files. Once the source code is imported, make sure that JBoss is running by checking the status on the Server Navigator. If JBoss is not running, you can right-click the icon for your server and choose Start to run it. Now open up the source file for HomePageSetupAction and set a breakpoint inside the execute() method as shown in Figure 9-5 by double-clicking the margin of the code editor. Now fire up your browser and point it to the JavaEdge application running in JBoss. Once the home page executes, the code will stop at the breakpoint you defined, and Eclipse will switch into Debug mode. From here you can step through your code in the standard way you would with any debugger. You will find the debugger commands under the Run menu along with the particular shortcut keys for your platform. You can set breakpoints at any point in your code, enabling you to analyze exactly what is going on within your application. CHAPTER 9 ■ LOGGING AND DEBUGGING354 Ch09_7389_CMP3 9/27/06 11:39 AM Page 354 Figure 9-4. Eclipse Import wizard Figure 9-5. Breakpoints in Eclipse Hot-Deploy One really nifty feature of running the JBoss application server from within Eclipse is hot deployment of code. Provided you are running a JVM that supports in-VM replacement, such as the Sun JVMs 1.4.1 and 1.4.2, then when you are running JBoss and your J2EE application from within the Eclipse IDE, any time you recompile a class it will replace the current version in the JBoss VM. This allows you to make lots of changes while debugging your application without having to perform a full rebuild and redeploy each time. CHAPTER 9 ■ LOGGING AND DEBUGGING 355 Ch09_7389_CMP3 9/27/06 11:39 AM Page 355 Debugging the Struts Framework You’re not only restricted to debugging your own source code. If you suspect there may be a problem with some part of the Struts framework, you can actually get the source code level for the framework at the same level as your own source code. To do this, you first need to obtain the source code for Struts, which you can either download from the Apache web site or check out from the Apache CVS server. The example here uses the downloadable source package. Once you have downloaded the source package, locate the struts.jar file listed in the Pack- age Explorer, right-click it, and choose Properties. In the Java Source Attachment page of the Properties dialog box, enter the path to the ZIP file containing the source in the Location Path box, as shown in Figure 9-6. Figure 9-6. Source code attachment for Struts Once you have mounted the source code, expand the struts.jar node in the Package Explorer, and then expand the org.struts.action node. Under this node you will find the RequestProcessor class. If you expand this node, all the methods are listed. Clicking the process() method will bring up the source code, and you can place a breakpoint directly inside the process() method. When you next request a page from the JavaEdge application, JBoss will halt execution at your breakpoint, and the Eclipse IDE will switch into debug mode with the Struts RequestProcessor source code in the current view. Summary In this chapter, we have given you an in-depth look at logging technologies, addressing exactly what makes a good logging tool and looking at tools that meet the required criteria. Specifi- cally, this chapter has focused mainly on Commons Logging and log4j, as together these tools provide the most flexible and complete logging solution currently available. We have addressed issues related to the design of a logging strategy, as well as the per- formance of Commons Logging and log4j. We discussed at length some of the best practices that you should take into consideration when adding logging support to your application. Most of the concepts in this chapter have been backed up by practical demonstrations, so you should now have a sense of how these topics work in a real scenario, not just on paper. CHAPTER 9 ■ LOGGING AND DEBUGGING356 Ch09_7389_CMP3 9/27/06 11:39 AM Page 356 Of course, we haven’t neglected Struts; we have taken an extensive look at how to configure logging within Struts, and also at some specific issues related to the JBoss application server. To cement these ideas, we demonstrated how logging has been integrated into the JavaEdge appli- cation and also explained the decision-making process we went through when picking our logging strategy. In the final part of the chapter, we presented a practical demonstration of how you can leverage the Eclipse IDE and JBoss application server to interactively debug not only your application, but the Struts framework as well. CHAPTER 9 ■ LOGGING AND DEBUGGING 357 Ch09_7389_CMP3 9/27/06 11:39 AM Page 357 Ch09_7389_CMP3 9/27/06 11:39 AM Page 358 [...]... the Velocity engine With Struts, you don’t want to have to go through this process every single time you build a view using Velocity Thankfully, you don’t need to With the VelocityTools project comes the VelocityViewServlet, which you can map to the *.vm extension to have all-out Velocity 381 Ch10_7 389 _CMP2 382 9/25/06 9:11 PM Page 382 CHAPTER 10 ■ VELOCITY TEMPLATE ENGINE templates processed automatically... your templates Ch10_7 389 _CMP2 9/25/06 9:11 PM Page 383 CHAPTER 10 ■ VELOCITY TEMPLATE ENGINE • ErrorsTool: Using this tool, you can work with Struts error messages within your templates in a manner similar to that by which the tag works in JSP • StrutsLinkTool: This tool helps you to build links to other Struts actions from within your templates This is synonymous with the ... request org .apache. velocity.tools .struts. StrutsLinkTool msg request org .apache. velocity.tools .struts. MessageTool errors request org .apache. velocity.tools .struts. ErrorsTool form request org .apache. velocity.tools .struts. FormTool... building the model, the Velocity team started a separate project, VelocityTools, to build a set of standard tools to provide integration with other projects, one of these being Struts The result of this is the VelocityStruts toolset that enables your Velocity templates to work alongside Struts This includes, amongst other things, support for working with ActionForms, the Validator, and more recently the... one product It has two properties, Name and Price, with the corresponding get() and set() methods The next thing you need to do is to create a Collection of Product objects and store the Collection in the VelocityContext: public static void main(String[] args) throws Exception { Velocity.init(); VelocityContext context = new VelocityContext(); Collection products = new ArrayList(); products.add(new Product("Widget",... core Struts tools: • MessageTool: This tool gives your template access to the resources stored in your Struts resource file; in the case of the JavaEdge application this is the ApplicationResources.properties file • FormTool: This tool allows you to access ActionForm beans that are accessible within the current scope You also use FormTool to build HTML forms that work with the Struts framework from within... have support for working with Struts; that support is introduced by another Jakarta project: VelocityTools As part of the Velocity project, the Jakarta team added a mechanism to extend the capabilities in a standard way without affecting the core code base This mechanism involves building a kind of plug-in called a tool and then configuring this within Velocity so that it runs within your application... objects and build an HTML price list So first you need the Product class in Java to hold the product details: public class Product { private String name; private double price; public Product(String aName, double aPrice) { name = aName; price = aPrice; } public String getName() { return name; } 377 Ch10_7 389 _CMP2 3 78 9/25/06 9:11 PM Page 3 78 CHAPTER 10 ■ VELOCITY TEMPLATE ENGINE public double getPrice()... you have seen how to map requests for any resource ending with vm to the VelocityViewServlet and also configure the four key Struts tools within the Velocity engine At this point, you can use a Velocity template as the destination for any ActionForwards defined within Struts Creating the Struts Action Typically, when creating a new feature in a Struts application, you have to create one or more Action... point of Struts is that your Action classes have nothing to do with the actual user interface; instead, they are merely the control logic that sits behind the user interface In this case, the action you want the JavaEdge application to perform is to display a story and the list of 383 Ch10_7 389 _CMP2 384 9/25/06 9:11 PM Page 384 CHAPTER 10 ■ VELOCITY TEMPLATE ENGINE associated comments From a Struts point . form, request, response); Properties props = new Properties(); //Getting the name of the e-mail server. props.put("mail.smtp.host", "netchange.us"); props.put("mail.from",. 355 Ch09_7 389 _CMP3 9/27/06 11:39 AM Page 355 Debugging the Struts Framework You’re not only restricted to debugging your own source code. If you suspect there may be a problem with some part of the Struts. the Struts framework as well. CHAPTER 9 ■ LOGGING AND DEBUGGING 357 Ch09_7 389 _CMP3 9/27/06 11:39 AM Page 357 Ch09_7 389 _CMP3 9/27/06 11:39 AM Page 3 58 Velocity Template Engine All of the Struts