最近小编在深入研究很多框架的底层,在研究tomcat中间件时下载源码并启动,遇到了很多问题,我相信大部分朋友只要以tomcat源码做分析肯定会遇见的,故此来编写一篇文章来记录一下。同时,很多人应该都会将Tomcat理解为一个框架,这里说一下,Tomcat并不是框架,准确的说它是一款中间件、容器。并且它是以java来编写的。正篇开始。
目录
三、下载Tomcat源码后,会少部分jar包,这里在项目根目录创建pom.xml文件,并编写依赖
四、将当前项目转换为Maven项目:Add as Maven Project
一、源码下载
这里以tomcat 9为例,下载网址:Apache Tomcat® - Apache Tomcat 9 Software Downloads
https://tomcat.apache.org/download-90.cgi选择Source Code Distributions,选择自己喜欢的方式进行下载tomcat源码,我这里使用9.0.76版本
二、解压安装包,导入至IDEA开发工具中
导入流程不再详细描述,下方为导入项目后的架构图:
三、下载Tomcat源码后,会少部分jar包,这里在项目根目录创建pom.xml文件,并编写依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.apache.tomcat</groupId>
<artifactId>Tomcat9.0.76</artifactId>
<name>Tomcat9.0.76</name>
<version>9.0.76</version>
<build>
<finalName>Tomcat9</finalName>
<sourceDirectory>java</sourceDirectory>
<resources>
<resource>
<directory>java</directory>
</resource>
</resources>
<plugins>
<plugin>
<!--
如果maven-compiler-plugin爆红,则说明version版本配置不正确,
需要去maven本地仓库中目录:org.apache.maven.plugins,寻找正确的版本
-->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
<configuration>
<encoding>UTF-8</encoding>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.10.1</version>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant-apache-log4j</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant-commons-logging</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>javax.xml.rpc</groupId>
<artifactId>javax.xml.rpc-api</artifactId>
<version>1.1</version>
</dependency>
<dependency>
<groupId>wsdl4j</groupId>
<artifactId>wsdl4j</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>org.eclipse.jdt.core.compiler</groupId>
<artifactId>ecj</artifactId>
<version>4.6.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
<version>3.5.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
四、将当前项目转换为Maven项目:Add as Maven Project
五、配置Project SDK
六、使用Maven工具编译当前项目:compile
编译项目后,发生了异常:程序包aQute.bnd.annotation.spi不存在,解决方案在pom.xml文件添加依赖。
<!--解决程序包aQute.bnd.annotation.spi不存在问题-->
<dependency>
<groupId>biz.aQute.bnd</groupId>
<artifactId>biz.aQute.bndlib</artifactId>
<version>5.2.0</version>
<scope>provided</scope>
</dependency>
再次编译,发生错误信息,如下图:
解决以上报错信息:当前我的tomcat源码项目配置的jdk是1.8,所以我需要将1.8之后的版本全部注释掉,如果你的tomcat版本、jdk版本都与我的一样可以复制我的JDTCompiler.java
文件 :
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jasper.compiler;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;
import org.apache.jasper.JasperException;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.internal.compiler.ClassFile;
import org.eclipse.jdt.internal.compiler.CompilationResult;
import org.eclipse.jdt.internal.compiler.Compiler;
import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies;
import org.eclipse.jdt.internal.compiler.ICompilerRequestor;
import org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy;
import org.eclipse.jdt.internal.compiler.IProblemFactory;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException;
import org.eclipse.jdt.internal.compiler.env.ICompilationUnit;
import org.eclipse.jdt.internal.compiler.env.INameEnvironment;
import org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer;
import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
/**
* JDT class compiler. This compiler will load source dependencies from the
* context classloader, reducing dramatically disk access during
* the compilation process.
*
* Based on code from Cocoon2.
*
* @author Remy Maucherat
*/
public class JDTCompiler extends org.apache.jasper.compiler.Compiler {
private final Log log = LogFactory.getLog(JDTCompiler.class); // must not be static
/**
* Compile the servlet from .java file to .class file
*/
@Override
protected void generateClass(Map<String,SmapStratum> smaps)
throws FileNotFoundException, JasperException, Exception {
long t1 = 0;
if (log.isDebugEnabled()) {
t1 = System.currentTimeMillis();
}
final String sourceFile = ctxt.getServletJavaFileName();
final String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath();
String packageName = ctxt.getServletPackageName();
final String targetClassName =
((packageName.length() != 0) ? (packageName + ".") : "") + ctxt.getServletClassName();
final ClassLoader classLoader = ctxt.getJspLoader();
String[] fileNames = new String[] {sourceFile};
String[] classNames = new String[] {targetClassName};
final List<JavacErrorDetail> problemList = new ArrayList<>();
class CompilationUnit implements ICompilationUnit {
private final String className;
private final String sourceFile;
CompilationUnit(String sourceFile, String className) {
this.className = className;
this.sourceFile = sourceFile;
}
@Override
public char[] getFileName() {
return sourceFile.toCharArray();
}
@Override
public char[] getContents() {
char[] result = null;
try (FileInputStream is = new FileInputStream(sourceFile);
InputStreamReader isr = new InputStreamReader(is, ctxt.getOptions().getJavaEncoding());
Reader reader = new BufferedReader(isr)) {
char[] chars = new char[8192];
StringBuilder buf = new StringBuilder();
int count;
while ((count = reader.read(chars, 0, chars.length)) > 0) {
buf.append(chars, 0, count);
}
result = new char[buf.length()];
buf.getChars(0, result.length, result, 0);
} catch (IOException e) {
log.error(Localizer.getMessage("jsp.error.compilation.source", sourceFile), e);
}
return result;
}
@Override
public char[] getMainTypeName() {
int dot = className.lastIndexOf('.');
if (dot > 0) {
return className.substring(dot + 1).toCharArray();
}
return className.toCharArray();
}
@Override
public char[][] getPackageName() {
StringTokenizer izer = new StringTokenizer(className, ".");
char[][] result = new char[izer.countTokens()-1][];
for (int i = 0; i < result.length; i++) {
String tok = izer.nextToken();
result[i] = tok.toCharArray();
}
return result;
}
@Override
public boolean ignoreOptionalProblems() {
return false;
}
}
final INameEnvironment env = new INameEnvironment() {
@Override
public NameEnvironmentAnswer findType(char[][] compoundTypeName) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < compoundTypeName.length; i++) {
if (i > 0) {
result.append('.');
}
result.append(compoundTypeName[i]);
}
return findType(result.toString());
}
@Override
public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) {
StringBuilder result = new StringBuilder();
int i=0;
for (; i < packageName.length; i++) {
if (i > 0) {
result.append('.');
}
result.append(packageName[i]);
}
if (i > 0) {
result.append('.');
}
result.append(typeName);
return findType(result.toString());
}
private NameEnvironmentAnswer findType(String className) {
if (className.equals(targetClassName)) {
ICompilationUnit compilationUnit = new CompilationUnit(sourceFile, className);
return new NameEnvironmentAnswer(compilationUnit, null);
}
String resourceName = className.replace('.', '/') + ".class";
try (InputStream is = classLoader.getResourceAsStream(resourceName)) {
if (is != null) {
byte[] classBytes;
byte[] buf = new byte[8192];
ByteArrayOutputStream baos = new ByteArrayOutputStream(buf.length);
int count;
while ((count = is.read(buf, 0, buf.length)) > 0) {
baos.write(buf, 0, count);
}
baos.flush();
classBytes = baos.toByteArray();
char[] fileName = className.toCharArray();
ClassFileReader classFileReader = new ClassFileReader(classBytes, fileName, true);
return new NameEnvironmentAnswer(classFileReader, null);
}
} catch (IOException | ClassFormatException exc) {
log.error(Localizer.getMessage("jsp.error.compilation.dependent", className), exc);
}
return null;
}
private boolean isPackage(String result) {
if (result.equals(targetClassName) || result.startsWith(targetClassName + '$')) {
return false;
}
String resourceName = result.replace('.', '/') + ".class";
try (InputStream is =
classLoader.getResourceAsStream(resourceName)) {
return is == null;
} catch (IOException e) {
// we are here, since close on is failed. That means it was not null
return false;
}
}
@Override
public boolean isPackage(char[][] parentPackageName, char[] packageName) {
StringBuilder result = new StringBuilder();
int i = 0;
if (parentPackageName != null) {
for (; i < parentPackageName.length; i++) {
if (i > 0) {
result.append('.');
}
result.append(parentPackageName[i]);
}
}
if (Character.isUpperCase(packageName[0])) {
if (!isPackage(result.toString())) {
return false;
}
}
if (i > 0) {
result.append('.');
}
result.append(packageName);
return isPackage(result.toString());
}
@Override
public void cleanup() {
}
};
final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
final Map<String,String> settings = new HashMap<>();
settings.put(CompilerOptions.OPTION_LineNumberAttribute,
CompilerOptions.GENERATE);
settings.put(CompilerOptions.OPTION_SourceFileAttribute,
CompilerOptions.GENERATE);
settings.put(CompilerOptions.OPTION_ReportDeprecation,
CompilerOptions.IGNORE);
if (ctxt.getOptions().getJavaEncoding() != null) {
settings.put(CompilerOptions.OPTION_Encoding,
ctxt.getOptions().getJavaEncoding());
}
if (ctxt.getOptions().getClassDebugInfo()) {
settings.put(CompilerOptions.OPTION_LocalVariableAttribute,
CompilerOptions.GENERATE);
}
// Source JVM
if(ctxt.getOptions().getCompilerSourceVM() != null) {
String opt = ctxt.getOptions().getCompilerSourceVM();
if(opt.equals("1.1")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_1);
} else if(opt.equals("1.2")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_2);
} else if(opt.equals("1.3")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
} else if(opt.equals("1.4")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4);
} else if(opt.equals("1.5")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
} else if(opt.equals("1.6")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_6);
} else if(opt.equals("1.7")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_7);
} else if(opt.equals("1.8")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_8);
// Version format changed from Java 9 onwards.
// Support old format that was used in EA implementation as well
}
/*else if(opt.equals("9") || opt.equals("1.9")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_9);
} else if(opt.equals("10")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_10);
} else if(opt.equals("11")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_11);
} else if(opt.equals("12")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_12);
} else if(opt.equals("13")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_13);
} else if(opt.equals("14")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_14);
} else if(opt.equals("15")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_15);
} else if(opt.equals("16")) {
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_16);
} else if(opt.equals("17")) {
// Constant not available in latest ECJ version that runs on
// Java 8.
// This is checked against the actual version below.
settings.put(CompilerOptions.OPTION_Source, "17");
} else if (opt.equals("18")) {
// Constant not available in latest ECJ version that runs on
// Java 8.
// This is checked against the actual version below.
settings.put(CompilerOptions.OPTION_Source, "18");
} else if (opt.equals("19")) {
// Constant not available in latest ECJ version that runs on
// Java 8.
// This is checked against the actual version below.
settings.put(CompilerOptions.OPTION_Source, "19");
} else if (opt.equals("20")) {
// Constant not available in latest ECJ version that runs on
// Java 8.
// This is checked against the actual version below.
settings.put(CompilerOptions.OPTION_Source, "20");
} else if (opt.equals("21")) {
// Constant not available in latest ECJ version that runs on
// Java 8.
// This is checked against the actual version below.
settings.put(CompilerOptions.OPTION_Source, "21");
}*/
else {
log.warn(Localizer.getMessage("jsp.warning.unknown.sourceVM", opt));
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_8);
}
} else {
// Default to 1.8
settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_8);
}
// Target JVM
if(ctxt.getOptions().getCompilerTargetVM() != null) {
String opt = ctxt.getOptions().getCompilerTargetVM();
if(opt.equals("1.1")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
} else if(opt.equals("1.2")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_2);
} else if(opt.equals("1.3")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_3);
} else if(opt.equals("1.4")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4);
} else if(opt.equals("1.5")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5);
} else if(opt.equals("1.6")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_6);
} else if(opt.equals("1.7")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_7);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_7);
} else if(opt.equals("1.8")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_8);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_8);
// Version format changed from Java 9 onwards.
// Support old format that was used in EA implementation as well
}
/*else if(opt.equals("9") || opt.equals("1.9")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_9);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_9);
} else if(opt.equals("10")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_10);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_10);
} else if(opt.equals("11")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_11);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_11);
} else if(opt.equals("12")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_12);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_12);
} else if(opt.equals("13")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_13);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_13);
} else if(opt.equals("14")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_14);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_14);
} else if(opt.equals("15")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_15);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_15);
} else if(opt.equals("16")) {
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_16);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_16);
} else if(opt.equals("17")) {
// Constant not available in latest ECJ version that runs on
// Java 8.
// This is checked against the actual version below.
settings.put(CompilerOptions.OPTION_TargetPlatform, "17");
settings.put(CompilerOptions.OPTION_Compliance, "17");
} else if (opt.equals("18")) {
// Constant not available in latest ECJ version that runs on
// Java 8.
// This is checked against the actual version below.
settings.put(CompilerOptions.OPTION_TargetPlatform, "18");
settings.put(CompilerOptions.OPTION_Compliance, "18");
} else if (opt.equals("19")) {
// Constant not available in latest ECJ version that runs on
// Java 8.
// This is checked against the actual version below.
settings.put(CompilerOptions.OPTION_TargetPlatform, "19");
settings.put(CompilerOptions.OPTION_Compliance, "19");
} else if (opt.equals("20")) {
// Constant not available in latest ECJ version that runs on
// Java 8.
// This is checked against the actual version below.
settings.put(CompilerOptions.OPTION_TargetPlatform, "20");
settings.put(CompilerOptions.OPTION_Compliance, "20");
} else if (opt.equals("21")) {
// Constant not available in latest ECJ version that runs on
// Java 8.
// This is checked against the actual version below.
settings.put(CompilerOptions.OPTION_TargetPlatform, "21");
settings.put(CompilerOptions.OPTION_Compliance, "21");
}*/
else {
log.warn(Localizer.getMessage("jsp.warning.unknown.targetVM", opt));
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_8);
}
} else {
// Default to 1.8
settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_8);
settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_8);
}
final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());
final ICompilerRequestor requestor = new ICompilerRequestor() {
@Override
public void acceptResult(CompilationResult result) {
try {
if (result.hasProblems()) {
IProblem[] problems = result.getProblems();
for (IProblem problem : problems) {
if (problem.isError()) {
String name =
new String(problem.getOriginatingFileName());
try {
problemList.add(ErrorDispatcher.createJavacError
(name, pageNodes, new StringBuilder(problem.getMessage()),
problem.getSourceLineNumber(), ctxt));
} catch (JasperException e) {
log.error(Localizer.getMessage("jsp.error.compilation.jdtProblemError"), e);
}
}
}
}
if (problemList.isEmpty()) {
ClassFile[] classFiles = result.getClassFiles();
for (ClassFile classFile : classFiles) {
char[][] compoundName =
classFile.getCompoundName();
StringBuilder classFileName = new StringBuilder(outputDir).append('/');
for (int j = 0;
j < compoundName.length; j++) {
if (j > 0) {
classFileName.append('/');
}
classFileName.append(compoundName[j]);
}
byte[] bytes = classFile.getBytes();
classFileName.append(".class");
try (FileOutputStream fout = new FileOutputStream(classFileName.toString());
BufferedOutputStream bos = new BufferedOutputStream(fout)) {
bos.write(bytes);
}
}
}
} catch (IOException exc) {
log.error(Localizer.getMessage("jsp.error.compilation.jdt"), exc);
}
}
};
ICompilationUnit[] compilationUnits =
new ICompilationUnit[classNames.length];
for (int i = 0; i < compilationUnits.length; i++) {
String className = classNames[i];
compilationUnits[i] = new CompilationUnit(fileNames[i], className);
}
CompilerOptions cOptions = new CompilerOptions(settings);
// Check source/target JDK versions as the newest versions are allowed
// in Tomcat configuration but may not be supported by the ECJ version
// being used.
String requestedSource = ctxt.getOptions().getCompilerSourceVM();
if (requestedSource != null) {
String actualSource = CompilerOptions.versionFromJdkLevel(cOptions.sourceLevel);
if (!requestedSource.equals(actualSource)) {
log.warn(Localizer.getMessage("jsp.warning.unsupported.sourceVM", requestedSource, actualSource));
}
}
String requestedTarget = ctxt.getOptions().getCompilerTargetVM();
if (requestedTarget != null) {
String actualTarget = CompilerOptions.versionFromJdkLevel(cOptions.targetJDK);
if (!requestedTarget.equals(actualTarget)) {
log.warn(Localizer.getMessage("jsp.warning.unsupported.targetVM", requestedTarget, actualTarget));
}
}
cOptions.parseLiteralExpressionsAsConstants = true;
Compiler compiler = new Compiler(env,
policy,
cOptions,
requestor,
problemFactory);
compiler.compile(compilationUnits);
if (!ctxt.keepGenerated()) {
File javaFile = new File(ctxt.getServletJavaFileName());
if (!javaFile.delete()) {
throw new JasperException(Localizer.getMessage(
"jsp.warning.compiler.javafile.delete.fail", javaFile));
}
}
if (!problemList.isEmpty()) {
JavacErrorDetail[] jeds =
problemList.toArray(new JavacErrorDetail[0]);
errDispatcher.javacError(jeds);
}
if( log.isDebugEnabled() ) {
long t2=System.currentTimeMillis();
log.debug("Compiled " + ctxt.getServletJavaFileName() + " "
+ (t2-t1) + "ms");
}
if (ctxt.isPrototypeMode()) {
return;
}
// JSR45 Support
if (! options.isSmapSuppressed()) {
SmapUtil.installSmap(smaps);
}
}
}
接下来重新编译,如下图,编译成功:
七、项目启动
八、控制台乱码解决
修改org.apache.jasper.compiler.Localizer中getMessage(String errCode)方法
public static String getMessage(String errCode) {
String errMsg = errCode;
try {
if (bundle != null) {
errMsg = bundle.getString(errCode);
//解决tomcat源码项目中编码集问题
errMsg = new String(errMsg.getBytes("ISO-8859-1"),"UTF-8");
}
} catch (MissingResourceException e) {
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return errMsg;
}
修改org.apache.tomcat.util.res.StringManager中getString(String key)方法
public String getString(String key) {
if (key == null) {
String msg = "key may not have a null value";
throw new IllegalArgumentException(msg);
}
String str = null;
try {
// Avoid NPE if bundle is null and treat it like an MRE
if (bundle != null) {
str = bundle.getString(key);
//解决tomcat源码项目中编码集问题
str = new String(str.getBytes("ISO-8859-1"),"UTF-8");
}
} catch (MissingResourceException mre) {
// bad: shouldn't mask an exception the following way:
// str = "[cannot find message associated with key '" + key +
// "' due to " + mre + "]";
// because it hides the fact that the String was missing
// from the calling code.
// good: could just throw the exception (or wrap it in another)
// but that would probably cause much havoc on existing
// code.
// better: consistent with container pattern to
// simply return null. Calling code can then do
// a null check.
str = null;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return str;
}
九、 解决无法编译jsp
通过上述流程解决乱码问题后,再次启动并访问http://localhost:8080/,出现如下图:
解决方案:添加JSP解析器并初始化
修改org.apache.catalina.startup.ContextConfig中configureStart()方法
protected synchronized void configureStart() {
// Called from StandardContext.start()
if (log.isDebugEnabled()) {
log.debug(sm.getString("contextConfig.start"));
}
if (log.isDebugEnabled()) {
log.debug(sm.getString("contextConfig.xmlSettings",
context.getName(),
Boolean.valueOf(context.getXmlValidation()),
Boolean.valueOf(context.getXmlNamespaceAware())));
}
webConfig();
//添加JSP解析器初始化
context.addServletContainerInitializer(new JasperInitializer(), null);
if (!context.getIgnoreAnnotations()) {
applicationAnnotationsConfig();
}
if (ok) {
validateSecurityRoles();
}
// Configure an authenticator if we need one
if (ok) {
authenticatorConfig();
}
// Dump the contents of this pipeline if requested
if (log.isDebugEnabled()) {
log.debug("Pipeline Configuration:");
Pipeline pipeline = context.getPipeline();
Valve valves[] = null;
if (pipeline != null) {
valves = pipeline.getValves();
}
if (valves != null) {
for (Valve valve : valves) {
log.debug(" " + valve.getClass().getName());
}
}
log.debug("======================");
}
// Make our application available if no problems were encountered
if (ok) {
context.setConfigured(true);
} else {
log.error(sm.getString("contextConfig.unavailable"));
context.setConfigured(false);
}
}
修改后,再次启动并访问http://localhost:8080/,出现以下图,访问成功:
十、解决无法部署应用目录或容器启动失败
在项目启动后,控制台会有很多的报错信息,如:启动子级时出错、容器启动失败等,如下图:
解决方案:
因为它是在webapps目录下的,也就是说webapps文件中是存放我们自己开发的应用项目,所以说这里可以删掉examples文件,同样webapps文件中的所有应用都可以删掉。所以说这里的报错信息没有影响,不是我们自己的项目,可以选择删掉examples文件。删除成功后重新启动tomcat,这时控制台没有任何报错信息,完美运行。