步骤 1 : 拓扑图点亮 步骤 2 : JspClassLoader 概念 步骤 3 : Context 步骤 4 : JspClassLoader 步骤 5 : JspServlet 步骤 6 : TestTomcat 步骤 7 : 比较可运行项目,快速定位问题
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
package cn.how2j.diytomcat.catalina;
import cn.how2j.diytomcat.classloader.WebappClassLoader;
import cn.how2j.diytomcat.exception.WebConfigDuplicatedException;
import cn.how2j.diytomcat.http.ApplicationContext;
import cn.how2j.diytomcat.http.StandardServletConfig;
import cn.how2j.diytomcat.util.ContextXMLUtil;
import cn.how2j.diytomcat.watcher.ContextFileChangeWatcher;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.LogFactory;
import org.apache.jasper.compiler.JspRuntimeContext;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import java.io.File;
import java.util.*;
import org.apache.jasper.JspC;
public class Context {
private String path;
private String docBase;
private File contextWebXmlFile;
private Map<String, String> url_servletClassName;
private Map<String, String> url_ServletName;
private Map<String, String> servletName_className;
private Map<String, String> className_servletName;
private Map<String, Map<String, String>> servlet_className_init_params;
private List<String> loadOnStartupServletClassNames;
private WebappClassLoader webappClassLoader;
private Host host;
private boolean reloadable;
private ContextFileChangeWatcher contextFileChangeWatcher;
private ServletContext servletContext;
private Map<Class<?>, HttpServlet> servletPool;
public Context(String path, String docBase, Host host, boolean reloadable) {
TimeInterval timeInterval = DateUtil.timer();
this.host = host;
this.reloadable = reloadable;
this.path = path;
this.docBase = docBase;
this.contextWebXmlFile = new File(docBase, ContextXMLUtil.getWatchedResource());
this.url_servletClassName = new HashMap<>();
this.url_ServletName = new HashMap<>();
this.servletName_className = new HashMap<>();
this.className_servletName = new HashMap<>();
this.servlet_className_init_params = new HashMap<>();
this.loadOnStartupServletClassNames = new ArrayList<>();
this.servletContext = new ApplicationContext(this);
ClassLoader commonClassLoader = Thread.currentThread().getContextClassLoader();
this.webappClassLoader = new WebappClassLoader(docBase, commonClassLoader);
this.servletPool = new HashMap<>();
LogFactory.get().info("Deploying web application directory {}", this.docBase);
deploy();
LogFactory.get().info("Deployment of web application directory {} has finished in {} ms", this.docBase,timeInterval.intervalMs());
}
public void reload() {
host.reload(this);
}
private void deploy() {
init();
if(reloadable){
contextFileChangeWatcher = new ContextFileChangeWatcher(this);
contextFileChangeWatcher.start();
}
JspC c = new JspC();
new JspRuntimeContext(servletContext, c);
}
private void init() {
if (!contextWebXmlFile.exists())
return;
try {
checkDuplicated();
} catch (WebConfigDuplicatedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
String xml = FileUtil.readUtf8String(contextWebXmlFile);
Document d = Jsoup.parse(xml);
parseServletMapping(d);
parseServletInitParams(d);
parseLoadOnStartup(d);
handleLoadOnStartup();
}
private void parseServletMapping(Document d) {
// url_ServletName
Elements mappingurlElements = d.select("servlet-mapping url-pattern");
for (Element mappingurlElement : mappingurlElements) {
String urlPattern = mappingurlElement.text();
String servletName = mappingurlElement.parent().select("servlet-name").first().text();
url_ServletName.put(urlPattern, servletName);
}
// servletName_className / className_servletName
Elements servletNameElements = d.select("servlet servlet-name");
for (Element servletNameElement : servletNameElements) {
String servletName = servletNameElement.text();
String servletClass = servletNameElement.parent().select("servlet-class").first().text();
servletName_className.put(servletName, servletClass);
className_servletName.put(servletClass, servletName);
}
// url_servletClassName
Set<String> urls = url_ServletName.keySet();
for (String url : urls) {
String servletName = url_ServletName.get(url);
String servletClassName = servletName_className.get(servletName);
url_servletClassName.put(url, servletClassName);
}
}
private void checkDuplicated(Document d, String mapping, String desc) throws WebConfigDuplicatedException {
Elements elements = d.select(mapping);
// 判断逻辑是放入一个集合,然后把集合排序之后看两临两个元素是否相同
List<String> contents = new ArrayList<>();
for (Element e : elements) {
contents.add(e.text());
}
Collections.sort(contents);
for (int i = 0; i < contents.size() - 1; i++) {
String contentPre = contents.get(i);
String contentNext = contents.get(i + 1);
if (contentPre.equals(contentNext)) {
throw new WebConfigDuplicatedException(StrUtil.format(desc, contentPre));
}
}
}
private void checkDuplicated() throws WebConfigDuplicatedException {
String xml = FileUtil.readUtf8String(contextWebXmlFile);
Document d = Jsoup.parse(xml);
checkDuplicated(d, "servlet-mapping url-pattern", "servlet url 重复,请保持其唯一性:{} ");
checkDuplicated(d, "servlet servlet-name", "servlet 名称重复,请保持其唯一性:{} ");
checkDuplicated(d, "servlet servlet-class", "servlet 类名重复,请保持其唯一性:{} ");
}
public String getServletClassName(String uri) {
return url_servletClassName.get(uri);
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getDocBase() {
return docBase;
}
public void setDocBase(String docBase) {
this.docBase = docBase;
}
public WebappClassLoader getWebappClassLoader() {
return webappClassLoader;
}
public void stop() {
webappClassLoader.stop();
contextFileChangeWatcher.stop();
destroyServlets();
}
public boolean isReloadable() {
return reloadable;
}
public void setReloadable(boolean reloadable) {
this.reloadable = reloadable;
}
public ServletContext getServletContext() {
return servletContext;
}
public synchronized HttpServlet getServlet(Class<?> clazz)
throws InstantiationException, IllegalAccessException, ServletException {
HttpServlet servlet = servletPool.get(clazz);
if (null == servlet) {
servlet = (HttpServlet) clazz.newInstance();
ServletContext servletContext = this.getServletContext();
String className = clazz.getName();
String servletName = className_servletName.get(className);
Map<String, String> initParameters = servlet_className_init_params.get(className);
ServletConfig servletConfig = new StandardServletConfig(servletContext, servletName, initParameters);
servlet.init(servletConfig);
servletPool.put(clazz, servlet);
}
return servlet;
}
private void parseServletInitParams(Document d) {
Elements servletClassNameElements = d.select("servlet-class");
for (Element servletClassNameElement : servletClassNameElements) {
String servletClassName = servletClassNameElement.text();
Elements initElements = servletClassNameElement.parent().select("init-param");
if (initElements.isEmpty())
continue;
Map<String, String> initParams = new HashMap<>();
for (Element element : initElements) {
String name = element.select("param-name").get(0).text();
String value = element.select("param-value").get(0).text();
initParams.put(name, value);
}
servlet_className_init_params.put(servletClassName, initParams);
}
// System.out.println("class_name_init_params:" + servlet_className_init_params);
}
private void destroyServlets() {
Collection<HttpServlet> servlets = servletPool.values();
for (HttpServlet servlet : servlets) {
servlet.destroy();
}
}
public void parseLoadOnStartup(Document d) {
Elements es = d.select("load-on-startup");
for (Element e : es) {
String loadOnStartupServletClassName = e.parent().select("servlet-class").text();
loadOnStartupServletClassNames.add(loadOnStartupServletClassName);
}
}
public void handleLoadOnStartup() {
for (String loadOnStartupServletClassName : loadOnStartupServletClassNames) {
try {
Class<?> clazz = webappClassLoader.loadClass(loadOnStartupServletClassName);
getServlet(clazz);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | ServletException e) {
e.printStackTrace();
}
}
}
public WebappClassLoader getWebClassLoader() {
return webappClassLoader;
}
}
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
package cn.how2j.diytomcat.classloader;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Map;
import cn.how2j.diytomcat.catalina.Context;
import cn.how2j.diytomcat.util.Constant;
import cn.hutool.core.util.StrUtil;
public class JspClassLoader extends URLClassLoader {
private static Map<String, JspClassLoader> map = new HashMap<>();
public static void invalidJspClassLoader(String uri, Context context) {
String key = context.getPath() + "/" + uri;
map.remove(key);
}
public static JspClassLoader getJspClassLoader(String uri, Context context) {
String key = context.getPath() + "/" + uri;
JspClassLoader loader = map.get(key);
if (null == loader) {
loader = new JspClassLoader(context);
map.put(key, loader);
}
return loader;
}
private JspClassLoader(Context context) {
super(new URL[] {}, context.getWebClassLoader());
try {
String subFolder;
String path = context.getPath();
if ("/".equals(path))
subFolder = "_";
else
subFolder = StrUtil.subAfter(path, '/', false);
File classesFolder = new File(Constant.workFolder, subFolder);
URL url = new URL("file:" + classesFolder.getAbsolutePath() + "/");
this.addURL(url);
} catch (Exception e) {
e.printStackTrace();
}
}
}
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
package cn.how2j.diytomcat.servlets;
import cn.how2j.diytomcat.catalina.Context;
import cn.how2j.diytomcat.classloader.JspClassLoader;
import cn.how2j.diytomcat.http.Request;
import cn.how2j.diytomcat.http.Response;
import cn.how2j.diytomcat.util.Constant;
import cn.how2j.diytomcat.util.JspUtil;
import cn.how2j.diytomcat.util.WebXMLUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
public class JspServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static JspServlet instance = new JspServlet();
public static synchronized JspServlet getInstance() {
return instance;
}
private JspServlet() {
}
public void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws IOException, ServletException {
try {
Request request = (Request) httpServletRequest;
Response response = (Response) httpServletResponse;
String uri = request.getRequestURI();
if ("/".equals(uri))
uri = WebXMLUtil.getWelcomeFile(request.getContext());
String fileName = StrUtil.removePrefix(uri, "/");
File file = FileUtil.file(request.getRealPath(fileName));
File jspFile = file;
if (jspFile.exists()) {
Context context = request.getContext();
String path = context.getPath();
String subFolder;
if ("/".equals(path))
subFolder = "_";
else
subFolder = StrUtil.subAfter(path, '/', false);
String servletClassPath = JspUtil.getServletClassPath(uri, subFolder);
File jspServletClassFile = new File(servletClassPath);
if (!jspServletClassFile.exists()) {
JspUtil.compileJsp(context, jspFile);
} else if (jspFile.lastModified() > jspServletClassFile.lastModified()) {
JspUtil.compileJsp(context, jspFile);
JspClassLoader.invalidJspClassLoader(uri, context);
}
String extName = FileUtil.extName(file);
String mimeType = WebXMLUtil.getMimeType(extName);
response.setContentType(mimeType);
JspClassLoader jspClassLoader = JspClassLoader.getJspClassLoader(uri, context);
String jspServletClassName = JspUtil.getJspServletClassName(uri, subFolder);
Class jspServletClass = jspClassLoader.loadClass(jspServletClassName);
HttpServlet servlet = context.getServlet(jspServletClass);
servlet.service(request,response);
response.setStatus(Constant.CODE_200);
} else {
response.setStatus(Constant.CODE_404);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
增值内容,请先登录
自己写一个Tomcat, 几乎使用到了除开框架外的所有Java 技术,如多线程,Socket, J2EE, 反射,Log4j, JSoup, JUnit, Html 等一整套技术栈, 从无到有,循序渐进涵盖全部74个知识点,549个开发步骤, 为竞争高薪资职位加上一个有吸引力的砝码.
增值内容,点击购买
使用爬虫已经被系统记录,请勿使用爬虫,增大封号风险。 如果是误封 ,请联系站长,谢谢
HOW2J公众号,关注后实时获知最新的教程和优惠活动,谢谢。
问答区域
2022-02-01
jsp转译生成的java文件执行service方法抛出空指针异常,续
2 个答案
我q146 跳转到问题位置 答案时间:2022-09-12 检查jspservlet有没有问题。然后再看StandardServletConfig这个类的getter方法返回的是null,还是一个有效的值
how2j 跳转到问题位置 答案时间:2022-02-02 试试步骤7呢,能否定位你的疑问所在。
回答已经提交成功,正在审核。 请于 我的回答 处查看回答记录,谢谢
2021-01-22
请教一下站长,为什么JSP不直接用WebappClassLoader加载
2020-10-26
转译生成的java文件执行service方法抛出空指针异常
2020-08-23
为什么JspClassLoader要作为WebAppClassLoader的子加载器
2020-08-19
关于getJspClassLoader方法的线程安全问题(续)
提问太多,页面渲染太慢,为了加快渲染速度,本页最多只显示几条提问。还有 3 条以前的提问,请 点击查看
提问之前请登陆
提问已经提交成功,正在审核。 请于 我的提问 处查看提问记录,谢谢
|