首页 > 代码库 > Struts1之简单的配置

Struts1之简单的配置

开发环境:MyEclipse10

学习状态:初学Struts

本次目的:搭建一个Struts1最简工程,实现HelloWorld。

实现过程:

  1.新建Web Project类工程,取名myStruts。

  2.新建三个包:com.luxl.action、com.luxl.impl、com.luxl.test。

  3.添加资源包:commons-beanutils-1.8.0.jar、commons-chain-1.2.jar、commons-digester-1.8.jar、commons-logging-1.0.4.jar、log4j-1.2.14、struts-core-1.3.10.jar。

  4.配置web.xml文件,添加请求分配器,添加如下配置信息:

        <servlet>		<servlet-name>actionServlet</servlet-name>		<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>				<!-- 初始化配置文档 -->		<init-param>			<param-name>config</param-name>			<param-value>struts.xml</param-value>		</init-param>		<load-on-startup>1</load-on-startup>	</servlet>		<servlet-mapping>		<servlet-name>actionServlet</servlet-name>		<url-pattern>*.do</url-pattern>	</servlet-mapping>    

  5.在src目录下建立资源文件夹/config,在/config下建立struts.xml配置文件。

  6.在struts.xml文件中添加以下配置信息:

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration1.2//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd"><struts-config>	<action-mappings>		<action path="/helloWorld" type="com.luxl.action.HelloWorldAction">			<forward name="index" path="/JSP/index.jsp"/>		</action>	</action-mappings></struts-config>

   7.在com.luxl.action下新建类:HelloWorldAction,代码如下:

package com.luxl.action;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.log4j.Level;import org.apache.log4j.Logger;import org.apache.struts.action.Action;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionMapping;public class HelloWorldAction extends Action{        private Logger logger = Logger.getLogger(this.getClass());    @Override    public ActionForward execute(ActionMapping mapping, ActionForm form,            HttpServletRequest request, HttpServletResponse response)            throws Exception {        // TODO Auto-generated method stub        logger.log(Level.INFO, "recive request for HelloWorldAction");        request.setAttribute("helloWorld", "HelloWorld");        return mapping.findForward("index");    }}

  8.在WebRoot下建立文件/JSP/index.jsp,代码如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><html>  <head>    <title>My JSP ‘index.jsp‘ starting page</title>  </head>  <%String str=(String)request.getAttribute("helloWorld"); %>  <body>    <H1><%=str %></H1>  </body></html>

  配置完成。

注:如果工程没有添加资源包commons-chain-1.2.jar,工程启动时会抛出异常:

Unable to initialize Struts ActionServlet due to an unexpected exception or error thrown, so marking the servlet as unavailable.  Most likely, this is due to an incorrect or missing library dependency.
java.lang.NoClassDefFoundError: org/apache/commons/chain/config/ConfigParser
    at org.apache.struts.action.ActionServlet.initChain(ActionServlet.java:1680)......

Struts1之简单的配置