本文是在Intellij IDEA 2017.2.3下创建第一个Struts 2.5.13程序,源码在文末下载。
一、JavaWeb三层架构
JavaWeb三层架构分别为:
Web层:表示层,主要的架构模式为MVC(Model View Controller,模型-视图-控制器),主要框架有:Spring MVC和Struts2(当然也有Struts1);
Service层:业务逻辑层,主要框架有:Spring;
Dao层:数据访问层,即数据持久化层,主要框架有:MyBatis(前身是iBATIS)和Hibernate。
常用的两种框架组合:
SSH:Struts2 + Spring + Hibernate
SSM:Spring MVC + Spring + MyBatis(目前更流行)
二、准备工作

Struts2下载
三、项目创建
新建项目Create New Project:

新建项目
Struts2作为JavaWeb中的Web层,故选择Java Enterprise(Java Web),然后勾选Web Application(表明这是一个Web应用),当前Web Application版本为3.1,并勾选Create web.xml(web.xml是Web Application的配置文件):

勾选Web Application
勾选Struts2,添加Struts2框架有两种种方式:使用已经下载好的本地库或者使用Struts2集成的联网下载库:

勾选Struts2
①、(不推荐,可能会造成Struts2的某些jar包缺失或其版本过低,正如下图所示,目前最新版本为Struts 2.5.13,而集成的版本为为Struts 2.3.20.1)若使用Struts2集成的联网下载库,查看下载了哪些jar包,然后点击Next:

使用IDEA集成的Struts2
②、若使用从Struts2官网下载好的库文件则需导入如下图所示8个jar包即可:
如何知道不同版本至少需要导入几个jar包?只需要导入相应Essential Dependencies Only版本(如struts-2.5.13-min-lib.zip)下所有jar包即可。

导入本地已下载Struts2库
导入好Struts2框架后点击Next:

导入Struts2成功
设置项目名和项目位置:

设置项目名和位置
项目创建成功后会自动生成struts.xml和web.xml文件,其位置分别为src/struts.xml和/web/WEB-INF/web.xml(两个文件名称和位置不可更改):

项目创建成功
四、完善项目
依次打开File > Project Structure:

打开Project Structure
修复所示问题:

修复问题
修改web.xml文件中Filter-Class的值为org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter
(在Struts 2.3版本时为org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
):

修改Filter-Class
修改后无报错,按住Ctrl键点击StrutsPrepareAndExecuteFilter能打开源文件则表示类路径正确:

正确的Filter-Class
写一个模拟登录的项目,写完后启动TomCat服务器:

写完程序并启动TomCat服务器
源文件如下:
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
struts.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<package name="default" namespace="/" extends="struts-default">
<action name="Login" class="com.rcnjtech.action.LoginAction">
<result name="success">/success.jsp</result>
<result name="login">/index.jsp</result>
</action>
</package>
</struts>
index.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>用户登录</title>
</head>
<body>
<h1>用户登录</h1>
<form action="Login.action" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td colspan="2" style="text-align: center"><input type="submit" value="登录"></td>
</tr>
</table>
</form>
</body>
</html>
success.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录成功</title>
</head>
<body>
<h1>登录成功!</h1>
</body>
</html>
LoginAction.java:
package com.rcnjtech.action;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport {
private String username;
private String password;
@Override
public String execute() throws Exception {
if (username.equals("admin") && password.equals("123")) {
return SUCCESS;
} else {
return LOGIN;
}
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
TomCat服务器启动成功:

TomCat服务器启动成功
项目在浏览器上成功运行:

项目在浏览器上运行
测试程序,输入正确的用户名和密码:

输入正确的用户名和密码
显示登录成功:

登录成功
测试程序,输入不正确的用户名或密码:

输入不正确的用户名或密码
显示登录失败:

登录失败
五、错误问题分析
作为程序员,Write Bugs是家常便饭,Fix Bugs也应当轻车熟路。当所写的程序出现异常或错误时,应当打开控制台Console,根据异常错误信息(也称日志或者Log)去分析并处理。举个例子,上文也提过: 如何知道不同版本至少需要导入几个jar包?只需要导入相应Essential Dependencies Only版本(如struts-2.5.14.1-min-lib.zip)下所有jar包即可。所以推荐到Struts 2官网下载 struts-2.5.14.1-all.zip 和struts-2.5.14.1-min-lib.zip。解压已下载的struts-2.5.14.1-min-lib.zip,里面共有如下图所示8个jar包,这8个jar是使用Struts 2框架时必需且最少数量的,故这8个jar包缺一不可:

struts-2.5.14.1-min-lib.zip
正如评论区所指出(也的确是),IntelliJ IDEA 2017集成的Struts 2框架目前(2018-3-16)最高版本为2.5.14.1,应该也是目前最新的版本了。然而只有7个jar包,缺少javassist-3.20.0-GA.jar
:

IDEA所集成的Struts 2框架
假如使用IntelliJ IDEA 2017集成的Struts 2.5.14.1框架(只有7个jar包)创建一个StrutsDemo项目(和StrutsStart项目一样):

StrutsDemo项目
启动Tomcat服务器后,观察控制台Console的输出:

控制台输出
日志信息一般分为五个级别:DEBUG、INFO、WARN、ERROR和FATAL。日志等级依次递增,即DEBUG(调试) < INFO(信息) < WARN(警告) < ERROR(错误) < FATAL(严重)。控制台输出了一大堆日志信息,尤其红色的更让人发慌。但仔细一看输出内容,像一开始的启动Tomcat服务器信息,我们不必理会,总之最后一句16-Mar-2018 11:22:41.260 信息 [main] org.apache.catalina.startup.Catalina.start Server startup in 204 ms
告诉我们Tomcat服务器在204ms启动并且正在部署项目:
C:\Software\Tomcat\bin\catalina.bat run
[2018-03-16 11:22:30,631] Artifact StrutsDemo:war exploded: Waiting for server connection to start artifact deployment...
...
16-Mar-2018 11:22:39.245 信息 [main] org.apache.catalina.startup.VersionLoggerListener.log Server version: Apache Tomcat/9.0.5
...
16-Mar-2018 11:22:41.260 信息 [main] org.apache.catalina.startup.Catalina.start Server startup in 204 ms
Connected to server
[2018-03-16 11:22:41,354] Artifact StrutsDemo:war exploded: Artifact is being deployed, please wait...
接着,异常信息全部输出了。虽然有一大堆内容,但能分析出Bug的也就那么几句话。我稍微精简了一下异常信息并标记了行号,如下,接着将逐一分析错误日志:
1 16-Mar-2018 11:22:43.916 信息 [RMI TCP Connection(2)-127.0.0.1] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
2 ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...
3 ERROR Dispatcher Dispatcher initialization failed
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
...
4 Caused by: java.lang.reflect.InvocationTargetException
...
5 Caused by: java.lang.ExceptionInInitializerError
...
6 Caused by: java.lang.IllegalArgumentException: Javassist library is missing in classpath! Please add missed dependency!
...
7 Caused by: java.lang.ClassNotFoundException: javassist.ClassPool
...
8 16-Mar-2018 11:22:44.635 严重 [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.StandardContext.startInternal One or more Filters failed to start. Full details will be found in the appropriate container log file
9 16-Mar-2018 11:22:44.651 严重 [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.core.StandardContext.startInternal Context [/StrutsDemo] startup failed due to previous errors
10 16-Mar-2018 11:22:51.179 信息 [ContainerBackgroundProcessor[StandardEngine[Catalina]]] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory [C:\Software\Tomcat\webapps\manager]
11 16-Mar-2018 11:22:51.351 信息 [ContainerBackgroundProcessor[StandardEngine[Catalina]]] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [C:\Software\Tomcat\webapps\manager] has finished in [172] ms
第1行为日志级别为信息,其内容大致为:有些jar包缺失TLD文件。TLD是Taglib Description即标签库描述文件。该信息可以忽略:
1 16-Mar-2018 11:22:43.916 信息 [RMI TCP Connection(2)-127.0.0.1] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
第2行日志级别为错误,与日志功能相关的错误,暂时可以忽略:
2 ERROR StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath. Using SimpleLogger to log to the console...
第3行日志级别为错误,Dispatcher initialization failed,即Dispatcher初始化失败。错误原因在第4-7行。在第6行中指出Caused by: java.lang.IllegalArgumentException: Javassist library is missing in classpath! Please add missed dependency!
,即ClassPath中缺少Javassist库,请添加该依赖。于是便找到了问题所在,缺少javassist-3.20.0-GA.jar
,到Maven Repository下载即可。第7行也指出Caused by: java.lang.ClassNotFoundException: javassist.ClassPool
,javassist.ClassPool类找不到,同样可以推测出缺少javassist-3.20.0-GA.jar
:
3 ERROR Dispatcher Dispatcher initialization failed
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
...
4 Caused by: java.lang.reflect.InvocationTargetException
...
5 Caused by: java.lang.ExceptionInInitializerError
...
6 Caused by: java.lang.IllegalArgumentException: Javassist library is missing in classpath! Please add missed dependency!
...
7 Caused by: java.lang.ClassNotFoundException: javassist.ClassPool
...
最后几行就不一一分析了,大致的意思为项目部署失败。当添加了javassist-3.20.0-GA.jar
后再次启动Tomcat服务器后,程序正常运行。
通过分析控制台输出日志,基本可以Fixed Bugs,或者将根据重要的错误信息到搜索引擎查找,一般在Stack Overflow、CSDN等一些平台都能找到解决方法。
项目源码下载,提取密码: 9dtk。
至此,第一个Struts2程序运行成功!
网友评论