.


:




:

































 

 

 

 


Org.apache.struts.action.ActionMapping




ActionForm -
Action -. ActionForm, (, ). ActionForm , , .. , , set-. , login=goch,
ActionForm setLogin() . Struts .
ActionForm setCompany() getCompany() Company, Employee, Address.
company.employees[n].address.phone,
:

getCompany().getEmployees().getItem(n).getAddress().setPhone().

, - Struts HTTP- URL- Action.

Action ,
, execute() ActionForm ActionMapping. Action Model
View .

- . , JSP-. (mappings) - . (Low Coupling) -, .

JSP- , , HTML-, ,
(action tags). Struts , Struts. , .

Java Server Pages Struts. , Struts , .

. 1. JSP Struts-.

/* # 1: Action : LoginAction.java */

package by.bsu.famcs.jspservlet;

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;

import org.apache.struts.action.ActionForm;

import org.apache.struts.action.ActionForward;

import org.apache.struts.action.ActionMapping;

import org.apache.struts.action.ActionMessage;

import org.apache.struts.action.ActionMessages;

 

public class LoginAction extends Action {

public ActionForward execute(ActionMapping mapping,

ActionForm form, HttpServletRequest request, HttpServletResponse response)

throws IOException, ServletException {

ActionMessages errors = new ActionMessages();

 

LoginForm actionForm = (LoginForm)form;

String login = actionForm.getLogin();

String password = actionForm.getPassword();

if (login!= null && password!= null) {

if (LoginLogic.checkLogin(login, password)) {

return mapping.findForward(" success ");

} else {

errors.add(ActionMessages.GLOBAL_MESSAGE,

new ActionMessage("error.login.incorrectLoginOrPassword"));

saveErrors(request, errors);

}

}

//

return mapping.findForward(" loginAgain ");

}

}

LoginForm, , , : /* # 2: , login.jsp: LoginForm.java */

package by.bsu.famcs.jspservlet;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionForm;

import org.apache.struts.action.ActionMapping;

 

public class LoginForm extends ActionForm {

private String login;

private String password;

//

public void reset(ActionMapping mapping,

HttpServletRequest request) {

super. reset(mapping, request);

this. password = null;

}

public String getLogin() {

return login;

}

public String getPassword() {

return password;

}

public void setLogin(String login) {

this. login = login;

}

public void setPassword(String password) {

this. password = password;

}

} LoginLogic, -, . Struts. ConfigurationManager , struts-config.xml.

/* # 3: , config.properties
: ConfigurationManager.java */

package by.bsu.famcs.jspservlet.manager;

import java.util.ResourceBundle;

 

public class ConfigurationManager {

private static ConfigurationManager instance;

private ResourceBundle resourceBundle;

private static final String BUNDLE_NAME = "config";

public static final String DATABASE_DRIVER_NAME = "DATABASE_DRIVER_NAME";

public static final String DATABASE_URL = "DATABASE_URL";

 

public static ConfigurationManager getInstance() {

if (instance == null) {

instance = new ConfigurationManager();

instance.resourceBundle =

ResourceBundle.getBundle(BUNDLE_NAME);

}

return instance;

}

public String getProperty(String key) {

return (String)resourceBundle.getObject(key);

}

}

config.properties:

###############################

## Application configuration ##

###############################

DATABASE_DRIVER_NAME=com.mysql.jdbc.Driver

DATABASE_URL=jdbc:mysql://localhost:3306/db1?user=

root&password=pass

JSP- : <%-- # 4: Struts:index.jsp --%>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01

Transitional//EN">

<html><head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Index JSP</title>

</head>

<body>

<a href="login.do">Controller</a>

</body></html>

<%-- # 5: :login.jsp --%>

<%@ page language="java" contentType="text/html;

charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>

<%-- Struts--%>

<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>

<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01

Transitional//EN">

<html:html locale="true">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<%-- .properties --%>

<title><bean:message key="jsp.login.title"/></title>

<%-- <base> href, URL
application.

--%>

<html:base />

</head>

<body>

<h3><bean:message key="jsp.login.header"/></h3>

<hr/ ><%-- --%>

<html:form action=" /login " method="POST">

<bean:message key="jsp.login.field.login"/>:<br>

<%-- --%>

<html:text property=" login "/><br>

<bean:message key="jsp.login.field.password"/>:<br>

<%-- --%>

<html:password property=" password "

redisplay="false"/><br>

<html:submit><bean:message

key="jsp.Login.button.submit"/> </html:submit>

</html:form>

<%-- , / --%>

<html:errors/>

<hr/>

</body>

</html:html>

<bean:message key="jsp.login.header"/>,

,
ApplicationResources.properties
. , , key. , LoginAction , :

errors.add(ActionMessages.GLOBAL_MESSAGE,

new ActionMessage("error.login.incorrectLoginOrPassword"));

: # # 6: : ApplicationResources.properties # header footer, # , <errors/>.

errors.header=<ul>

errors.footer=</ul>

errors.prefix=<li>

errors.suffix=</li>

# <errors/>,

# , .

error.login.incorrectLoginOrPassword=<li>incorrect login or password</li>

 

# login.jsp

jsp.login.title=Login

jsp.login.header=Login

jsp.login.field.login=Login

jsp.login.field.password=Password

jsp.login.button.submit=Enter

 

# main.jsp

jsp.main.title=Welcome

jsp.main.header=Welcome

jsp.main.hello=Hello

 

# error.jsp

jsp.error.title=Error

jsp.error.header=Error

jsp.error.returnToLogin=Return to login page struts-config.xml, , Struts. # 7: action, forward, resource ..: struts-config.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts-config PUBLIC "-//Apache

Software Foundation//DTD Struts Configuration 1.2//EN"

"http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">

<struts-config>

<data-sources>

<!-- . , . -->

</data-sources>

<!-- ========== Form Bean Definitions -->

<form-beans>

<form-bean name="loginForm"

type="by.bsu.famcs.jspservlet.LoginForm" />

</form-beans>

<!-- ============== Global Exception Definitions ( )-->

<global-exceptions>

</global-exceptions>

<!-- ============== Global Forward Definitions( ) -->

<global-forwards>

</global-forwards>

 

<!-- =============== Action Mapping Definitions -->

<action-mappings>

<!-- Action -->

<action name="loginForm"

path="/login"

scope="request" <!- . , , . -->

type="by.bsu.famcs.jspservlet.LoginAction"

validate="false">

<!-- JSP, action -->

<forward name="againlogin" path="/WEB-INF/jsp/login.jsp" />

<forward name="success" path="/WEB-INF/jsp/main.jsp" />

</action>

</action-mappings>

<!-- =================== Message Resources Definitions -->

<!-- .properties, . classes. -->

<message-resources parameter=

"resources.ApplicationResources"/>

</struts-config>

<action> path /login JSP ActionForm, . login.jsp FORM ACTION.
, , .
<forward> , success login, /jsp/login.jsp /jsp /main.jsp . findForward() ActionMapping . web.xml ActionServlet struts-config.xml, servlet-mapping . # 8: : web.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app id="WebApp">

<display-name>Study</display-name>

<!-- Struts ActionServlet -->

<servlet>

<servlet-name>action</servlet-name>

<servlet-class>

org.apache.struts.action.ActionServlet</servlet-class>

<!-- Struts struts-config.xml -->

<init-param>

<param-name>config</param-name>

<param-value>WEB-INF/struts-config.xml</param-value>

</init-param>

<init-param>

<param-name>debug</param-name>

<param-value>2</param-value>

</init-param>

<init-param>

<param-name>detail</param-name>

<param-value>2</param-value>

</init-param>

<init-param>

<param-name>validate</param-name>

<param-value>true</param-value>

</init-param>

<load-on-startup>1</load-on-startup>

</servlet>

<!-- (mapping) , , , .do -->

<servlet-mapping>

<servlet-name>action</servlet-name>

<url-pattern>*.do</url-pattern>

</servlet-mapping>

<welcome-file-list>

<welcome-file>index.jsp</welcome-file>

</welcome-file-list>

<!-- struts- ( ) -->

<taglib>

<taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri>

<taglib-location>/WEB-INF/struts-bean.tld</taglib-location>

</taglib>

<taglib>

<taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>

<taglib-location>/WEB-INF/struts-html.tld</taglib-location>

</taglib>

<taglib>

<taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri>

<taglib-location>/WEB-INF/struts-logic.tld</taglib-location>

</taglib>

</web-app>

, datasource struts-config.xml, :

# 9: : data-sources <data-sources>

<data-source type="org.apache.commons.dbcp.BasicDataSource">

<set-property

property="driverClassName"

value="com.mysql.jdbc.Driver" />

<set-property

property="url"

value="jdbc:mysql://localhost/_" />

<set-property

property="username"

value="root" />

<set-property

property="password"

value="pass" />

<set-property

property="maxActive"

value="10" />

<set-property

property="maxWait"

value="5000" />

<set-property

property="defaultAutoCommit"

value="false" />

<set-property

property="defaultReadOnly"

value="false" />

</data-source>

</data-sources>

, org.apache.struts.action.Action,
getDataSource(HttpServletRequest request)).

JSP- : <%-- # 10: , : main.jsp --%>

<%@ page errorPage="error.jsp" %>

<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>

<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>

<html:html locale="true">

<head>

<title><bean:message key="jsp.main.title"/></title>

<html:base/>

</head>

<body>

<h3><bean:message key="jsp.main.header"/></h3>

<hr/>

<bean:message key="jsp.main.hello"/>,

<bean:write name="loginForm" property="login"/>

<hr/>

<a href="login.do"><bean:message

key="jsp.error.returnToLogin"/></a>

<html:errors/>

</body>

</html:html>

, , : <%-- # 11: , : error.jsp --%>

<%@ page isErrorPage="true" %>

<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>

<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>

<html:html locale="true">

<head>

<title><bean:message key="jsp.error.title"/></title>

<html:base/>

</head>

<body>

<h3><bean:message key="jsp.error.header"/></h3>

<hr>

<%=(exception!= null)? exception.toString():

"unknown error"%>

<hr>

<a href="login.do"><bean:message key="jsp.error.returnToLogin"/></a>

</body>

</html:html>

, Struts, struts.jar Java- : struts-bean.tld

struts-html.tld

struts-logic.tld

, :http://localhost:8080/StrutsProject

Action

Action, Action . Action execute()
, . DispatchAction

. , User UserDispatchAction save(), delete(), list() ., , struts-config.xml action.

<action path="/ModuleAction"

type="com.struts.ModuleDispatchAction"

parameter="method"

...</action> JSP method, , . :

<a href="ModuleAction.do? method=edit &id=1>Edit</a>

<a href="ModuleAction.do? method=view &id=1>View</a> ModuleDispatchAction. , unspecified() . cancelled(), <html:cancel/>.

import org.apache.struts.actions.DispatchAction;

 

public class ModuleDispatchAction extends DispatchAction{

public ActionForward edit(ActionMapping mapping,

ActionForm form,

HttpServletRequest request,

HttpServletResponse response)

throws IOException,

ServletException {

//

}

public ActionForward view(...)

throws IOException, ServletException {

//

}

...

public ActionForward unspecified(...)

throws IOException, ServletException {

 

mapping.findForward("methodNotFound");

}

public ActionForward cancelled(ActionMapping mapping,

ActionForm form,

HttpServletRequest request,

HttpServletResponse response)

throws IOException, ServletException {

 

mapping.findForward("cancelPage");

}

}

LookupDispatchAction DispatchAction. , View, .

JSP <html:submit/> , property , <bean:message/> .

<html:form action="ModuleAction.do">

...

<html:submit property=" method ">

<bean:message key=" submit.button.print " />

</html:submit>

<html:submit property=" method ">

<bean:message key=" button.save " />

</html:submit>

</html:form>

, DispatchAction, , .

<action path="/ModuleAction"

type="com. struts.ModuleLookupDispatchAction"

parameter="method"

...</action>

DispatchAction , getKeyMethodMap(), mapping .

import org.apache.struts.actions.LookupDispatchAction;

...

public class ModuleLookupDispatchAction

extends LookupDispatchAction {

private static Map m = new HashMap();

static {

m.put("myapp.submit.button.print","print");

m.put("myapp.submit.button.save","save");

}

protected Map getKeyMethodMap(){

return m;

}

public ActionForward print(...)

throws IOException, ServletException {

...

}

public ActionForward save(...)

throws IOException, ServletException {

...

}...} MappingDispatchAction DispatchAction , , URL- struts-config.xml. MappingDispatchAction <action>:

<action path="/userUpdate"

type="com.struts.UserMappingDispatchAction"

parameter="update"

...

<action path="/userAdd"

type="com.struts.UserMappingDispatchAction"

parameter="create"

... parameter , ., , .

import org.apache.struts.actions.MappingDispatchAction;

...

public class UserMappingDispatchAction

extends MappingDispatchAction{

 

public ActionForward update (ActionMapping mapping,

ActionForm form,

HttpServletRequest request,

HttpServletResponse response)

throws IOException, ServletException {

...

}

public ActionForward create (...)

throws IOException, ServletException {

...

}

...

public ActionForward unspecified(...)

throws IOException, ServletException {

mapping.findForward("methodNotFound");

}

}

Struts

Struts Bean Tags

  • cookie

cookie.

<p>Display the properties of our current session ID cookie (if there is one):</p>

 

<bean:cookie id="sess" name="JSESSIONID" value="JSESSIONID-IS-UNDEFINED"/>

  • define

id toScope ( page scope) value, Java bean name a property.

<bean:define id="test1_boolean" name="test1"

property="booleanProperty" toScope=session/>

<bean:define id="test1_double" name="test1"

property="doubleProperty"/>

<bean:define id="test1_float" name="test1"

property="floatProperty"/>

<bean:define id="test1_int" name="test1"

property="intProperty"/>

<bean:define id="test1_long" name="test1"

property="longProperty"/>

<bean:define id="test1_short" name="test1"

property="shortProperty"/>

<bean:define id="test1_string" name="test1"

property="stringProperty"/>

<bean:define id="test1_value" value="ABCDE"/>

  • header

.

Display the values of the headers included in this request.<br><br>

<%

java.util.Enumeration names =

((HttpServletRequest) request).getHeaderNames();

%>

 

<table border="1">

<tr>

<th>Header Name</th>

<th>Header Value</th>

</tr>

<%

while (names.hasMoreElements()) {

String name = (String) names.nextElement();

%>

<bean:header id="head" name="<%= name %>"/>

<tr>

<td><%= name %></td>

<td><%= head %></td>

</tr>

<%

}

%>

  • include

. page id.

<bean:include id="index" page="/index.jsp"/>

  • message

.

  • page

.

  • parameter

.

<bean:parameter id="param1" name="param1"/>

  • resource

Web-.

<bean:resource id="webxml" name="/WEB-INF/web.xml"/>

  • size

java.lang.Integer , .

<bean:size id="dataSize" collection="<%= data %>"/>

  • struts

Struts.

  • write

.

Struts Html Tags

  • button, cancel, checkbox, file, form, frame, hidden, image, img, link, multibox, password, radio, reset, submit, text, textarea

html-.

  • errors

.

  • javascript

JavaScript-, , .

  • messages

.

<%

ActionMessages messages = new ActionMessages();

messages.add("property1",

new ActionMessage("property1message1"));

messages.add("property2",

new ActionMessage("property2message1"));

messages.add("property2",

new ActionMessage("property2message2"));

messages.add(ActionMessages.GLOBAL_MESSAGE,

new ActionMessage("globalMessage"));

request.setAttribute(Action.MESSAGE_KEY, messages);

%>

<html:messages property="property1" message="true" id="msg"

header="messages.header" footer="messages.footer">

<tr><td><%= pageContext.getAttribute("msg") %></td></tr>

</html:messages>

  • select, option, optionsCollection

html- select c option . optionsCollection , .

<html:select property="singleSelect" size="10">

<html:option value="Single 0">Single 0 </html:option>

<html:option value="Single 1">Single 1 </html:option>

<html:option value="Single 2">Single 2 </html:option>

<html:option value="Single 3">Single 3 </html:option>

<html:option value="Single 4">Single 4 </html:option>

<html:option value="Single 5">Single 5 </html:option>

<html:option value="Single 6">Single 6 </html:option>

<html:option value="Single 7">Single 7 </html:option>

<html:option value="Single 8">Single 8 </html:option>

<html:option value="Single 9">Single 9 </html:option>

</html:select>

Struts Logic Tags

  • empty, notEmpty

, ( ) null .

<logic:empty name="bean" property="nullProperty">

empty

</logic:empty>

<logic:notEmpty name="bean" property="nullProperty">

notEmpty

</logic:notEmpty>

  • equal, notEqual

, / .

  • forward

URL.

  • greaterEqual, lessEqual

, (), , .

  • greaterThan, lessThan

, (), .

  • iterate

.

<% {

java.util.ArrayList list =

new java.util.ArrayList();

list.add("First");

list.add("Second");

list.add("Third");

list.add("Fourth");

list.add("Fifth");

pageContext.setAttribute("list", list, PageContext.PAGE_SCOPE);

 

int intArray[] = new int[]

{ 0, 10, 20, 30, 40 };

pageContext.setAttribute("intArray", intArray, PageContext.PAGE_SCOPE);

}%>

<h3>Test 1 - Iterate Over A String Array [0..4]</h3>

 

<ol>

<logic:iterate id="element" name="bean"

property="stringArray" indexId="index">

<li><em><bean:write name="element"/></em>&nbsp;[<bean:write name="index"/>]</li>

</logic:iterate>

</ol>

 

<h3>Test 2 - Iterate Over A String Array [0..2]</h3>

<ol>

<logic:iterate id="element" name="bean" property="stringArray" indexId="index"

length="3">

<li><em><bean:write name="element"/></em>&nbsp;[<bean:write name="index"/>]</li>

</logic:iterate>

</ol>

 

<h3>Test 3 - Iterate Over A String Array [3..4]</h3>

 

<ol>

<logic:iterate id="element" name="bean" property="stringArray" indexId="index"

offset="3">

<li><em><bean:write name="element"/></em>&nbsp;[<bean:write name="index"/>]</li>

</logic:iterate>

</ol>

 

<h3>Test 4 - Iterate Over A String Array [1..3]</h3>

 

<ol>

<logic:iterate id="element" name="bean"

property="stringArray" indexId="index"

offset="1" length="3">

<li><em><bean:write name="element"/></em>&nbsp;[<bean:write name="index"/>]</li>

</logic:iterate>

</ol>

 

<h3>Test 5 - Iterate Over an Array List</h3>

 

<ol>

<logic:iterate id="item" name="list" indexId="index">

<li><em><bean:write name="item"/></em>&nbsp;[<bean:write name="index"/>]</li>

</logic:iterate>

</ol>

 

<h3>Test 6 - Iterate Over an Array List [0..2]</h3>

 

<ol>

<logic:iterate id="item" name="list" indexId="index"

offset="0" length="3">

<li><em><bean:write name="item"/></em>&nbsp;[<bean:write name="index"/>]</li>

</logic:iterate>

</ol>

 

<h3>Test 7 - Iterate Over an Array List [2..4]</h3>

 

<ol>

<logic:iterate id="item" name="list" indexId="index"

offset="2" length="3">

<li><em><bean:write name="item"/></em>&nbsp;[<bean:write name="index"/>]</li>

</logic:iterate>

</ol>

 

<h3>Test 8 - Iterate Over an int array</h3>

 

<ol>

<logic:iterate id="item" name="intArray" indexId="index">

<li><em><bean:write name="item"/></em>&nbsp;[<bean:write name="index"/>]</li>

</logic:iterate>

</ol>

 

<h3>Test 9 - Iterate Over an int array [0..2]</h3>

 

<ol>

<logic:iterate id="item" name="intArray" indexId="index"

length="3">

<li><em><bean:write name="item"/></em>&nbsp;[<bean:write name="index"/>]</li>

</logic:iterate>

</ol>

 

<h3>Test 10 - Iterate Over an int array [2..4]</h3>

 

<ol>

<logic:iterate id="item" name="intArray" indexId="index"

offset="2" length="3">

<li><em><bean:write name="item"/></em>&nbsp;[<bean:write name="index"/>]</li>

</logic:iterate>

</ol>

  • messagesNotPresent, messagesPresent

, ActionMessages ActionErrors ( ) .

  • notPresent

, .

<logic:present name="bean" property="stringProperty">

present

</logic:present>

<logic:notPresent name="bean" property ="stringProperty">

notPresent

</logic:notPresent>

Struts Nested Tags

, , nested- , .

, , Company, Address .

<%@ page contentType="text/html;charset=UTF-8"

language="java" %>

<%@ taglib uri="/tags/struts-html" prefix="html" %>

<html:html>

<body>

<html:form action="company.do">

Company name:

<html:text property="company.name" size="60" />

<br>

Company address:

<br>

City:

<html:text property=

"company.address.city" size="60" />

<br>

Street:

<html:text property=

"company.address.street" size="60" />

<br>

<html:submit/>

</html:form>

</body>

</html:html>

, getCompany() . getAddress() Company.

nested- JSP :

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%@ taglib uri="/tags/struts-html" prefix="html" %>

<%@ taglib uri="/tags/struts-nested" prefix="nested" %>

<html:html>

<body>

<html:form action="company.do">

<nested:nest property="company"/>

Company name:

<html:text property="name" size="60" />

<br>

Company address:

<br>

<nested:nest property="address">

City:

<html:text property="city" size="60" />

<br>

Street:

<html:text property="street" size="60" />

<br>

</nested:nest>

</nested:nest>

<html:submit/>

</html:form>

</body>

</html:html>

nest , nested-, , nested-. , nested- , .

 

 
7

(LOGGER)

, , .. API . API Log4j, Jakarta Apache.

API Log4j (, , ). API Log4j : http://logging.apache.org/log4j/. log4j-1.2.13.jar
.

Log4j :

(logger);

(appender);

(layout).

logger , appender, , layout.

java.util.logging . , Log4j, .

Logger

API Logger, . , , , GUI- . , .

logger . , Java. getLogger(String name), name . . . getRootLogger().

(TRACE, DEBUG, INFO, WARN, ERROR, FATAL), . debug(), info(), warn(), error(), fatal(). , , Throwable. , , (TRACE < DEBUG < INFO < WARN < ERROR < FATAL), . . INFO, logger.debug(message) , . . DEBUG < INFO. setLevel(Level level), Level, . , . DEBUG.

:

log(Priority priority, Object message, Throwable t) t.

log(Priority priority, Object message) .

Appender Layout

. , Appender. addAppender(Appender newAppender) Logger Apeender . Appender. ConsoleAppender. FileAppender . , , FileAppender(Layout layout, String filename) setFile(String file). , , . FileAppender(Layout layout, String filename, boolean append) append setAppend(boolean append).

, JDBCAppender, NTEventLogAppender, SMTP- SMTPAppender, SocketAppender.

, , . ,
setAdditivity(boolean additive). .

. , Layout. Layout . :

HTMLLayout HTML-;

XMLLayout XML-;

SimpleLayout .

XML-.

Layout FileAppender ConsoleAppender
setLayout(Layout layout) .

, ( ).

/* # 1: : Demo Log.java */

package app6;

import org.apache.log4j.Logger;

import org.apache.log4j.FileAppender;

import org.apache.log4j.SimpleLayout;

import org.apache.log4j.Level;

import java.io.IOException;

 

public class DemoLog {

static Logger logger = Logger.getLogger(DemoLog. class);

 

public static void main(String[] args) {

try {

//

factorial(9);

factorial(-3);

} catch (IllegalArgumentException e) {

// ERROR

logger.error("negative argument", e);

}

}

public static int factorial(int n) {

if (n < 0)

throw new IllegalArgumentException(

"argument " + n +" less then zero");

// DEBUG

logger.debug("Argument n is " + n);

int result = 1;

for (int i = n; i >= 1; i--)

result *= i;

// INFO

logger.info("Result is " + result);

return result;

}

}

"log4j.xml" :

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>

<appender name="TxtAppender" class="org.apache.log4j.FileAppender">

<param name="File" value="log.txt" />

<layout class="org.apache.log4j.SimpleLayout"/>

</appender>

<logger name="app6">

<level value="debug" />

</logger>

<root>

<appender-ref ref="TxtAppender" />

</root>

</log4j:configuration>

"app6.DemoLog", log.txt :

DEBUG - Argument n is 9

INFO - Result is 362880

ERROR - negative argument java.lang.IllegalArgumentException: argument -3 less then zero

at app6.DemoLog.factorial(DemoLog.java:35)

at app6.DemoLog.main(DemoLog.java:27)

. :

FileAppender appender =

new FileAppender(

new SimpleLayout(), "log.txt");

logger.addAppender(appender);

logger.setLevel(Level.DEBUG);

XML :

<appender name="ConsAppender" class="org.apache.log4j.ConsoleAppender">

<layout class="org.apache.log4j.SimpleLayout"/>

</appender>

<appender name="XMLAppender" class="org.apache.log4j.FileAppender">

<param name="File" value="log.xml" />

<layout class="org.apache.log4j.xml.XMLLayout"/>

</appender>

<root>

<appender-ref ref="ConsAppender" />

<appender-ref ref="XMLAppender" />

</root>

:

ConsoleAppender appender2 =

new ConsoleAppender(new SimpleLayout());

FileAppender appender3 =

new FileAppender(new XMLLayout(), "log.xml");

logger.addAppender(appender2);

logger.addAppender(appender3);

Logger , , : fine(), info(), warning(), log(), throwing() .

log.xml .

/* # 2: : StandartDemoLog.java */

package app6;

import java.io.IOException;

import java.util.logging.FileHandler;

import java.util.logging.Level

import java.util.logging.Logger;

 

public class StandartDemoLog {

static Logger log = Logger.getLogger("app6");

 

public static void main(String[] args)

throws SecurityException, IOException {

/* , XMLFormatter,
XML */

FileHandler fh = new FileHandler("log.xml");

log.addHandler(fh);

log.setLevel(Level.WARNING); //

int arr[] = { 5, 6, 1, -4 };

for (int i = 0; i < arr.length; i++) {

int j = arr[i] % 3;

switch (j) {

case 0:

log.fine(arr[i] + "%3 = 0");

break;

case 1:

log.info(arr[i] + "%3 = 1");

break;

case 2:

log.warning(arr[i] + "%3 = 2");

break;

default:

log.severe(arr[i] + "%3 < 0");

}

}

}

}

:

App6.DemoLog main

WARNING: 5%3 = 2

App6.DemoLog main

INFO: 1%3 = 1

App6.DemoLog main

SEVERE: -4%3 < 0

log.xml

<?xml version="1.0" encoding="windows-1251"

standalone="no"?>

<!DOCTYPE log SYSTEM "logger.dtd">

<log>

<record>

<date>2006-03-17T15:39:03</date>

<millis>1142602743635</millis>

<sequence>0</sequence>

<logger>app6</logger>

<level>WARNING</level>

<class>app6.DemoLog</class>

<method>main</method>

<thread>10</thread>

<message>5%3 = 2</message>

</record>

<record>

<date>2006-03-17T15:39:03</date>

<millis>1142602743736</millis>

<sequence>1</sequence>

<logger>app6</logger>

<level>INFO</level>

<class>app6.DemoLog</class>

<method>main</method>

<thread>10</thread>

<message>1%3 = 1</message>

</record>

<record>

<date>2006-03-17T15:39:03</date>

<millis>1142602743736</millis>

<sequence>2</sequence>

<logger>app6</logger>

<level>SEVERE</level>

<class>app6.DemoLog</class>

<method>main</method>

<thread>10</thread>

<message>-4%3 < 0</message>

</record>

</log>





:


: 2016-04-03; !; : 483 |


:

:

80% - .
==> ...

1501 - | 1336 -


© 2015-2024 lektsii.org - -

: 5.498 .