JSP转译成Servlet详细过程

本文解析了JSP与Servlet的执行原理,强调了JSP首次执行时的编译过程及之后请求处理的效率。通过具体示例展示了JSP如何转换为Servlet并执行。

很多人都会认为JSP的执行性能会和Servlet相差很多,其实执行性能上的差别只在第一次的执行。因为JSP在执行第一次后,会被编译成Servlet的类文件,即.class,当再重复调用执行时,就直接执行第一次所产生的Servlet,而不再重新把JSP编译成Servelt。

因此,除了第一次的编译会花较久的时间之外,之后JSP和Servlet的执行速度就几乎相同了。Web容器处理JSP文件请求的执行过程主要包括以下4个部分:

1.客户端发出Request请求

2.JSP Container 将JSP转译成Servlet的源代码

3.将产生的Servlet源代码经过编译后,并加载到内存执行

4.把结果Response(响应)至客户端

在执行JSP网页时,通常可以分为两个时期:转译时期(Translation Time)和请求时期(Request Time)。

◆转译时期:JSP网页转移成Servlet类。

◆请求时期:Servlet类执行后,响应结果至客户端。

转译期间做了两件事情:

◆转译时期:将JSP网页转移为Servlet源代码 .java.

◆编译时期:将Servlet 源代码 .java编译成 Servlet类 .class.

当JSP网页在执行时,JSP Container会做检查工作,如果发现JSP网页有更新修改时,JSP Container才会再次编译JSP成Servlet; 如果JSP没有更新时,就直接执行前面所产生的Servlet。

  1. (showdate.jsp)     
  2. <%@ page language="java" contentType="text/html;charset=gb2312" import="java.text.*,java.util.*;"%>     
  3. <html>     
  4. <head>     
  5. <title>Show time</title>     
  6. </head>     
  7. <body>      
  8.      Hello :      
  9.      <%     
  10.          SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");     
  11.          String str = format.format(new Date());     
  12.       %>     
  13.       <%=str %>     
  14. </body>     
  15. </html> 

当部署好 showdate.jsp之后,启动Tomcat

1.在IE浏览器中输入配置好的路径 .... showdate.jsp 请求这个页面。

2.JSP Container 即Tomcat 服务器会将 showdate.jsp 转译成 showdate_jsp.java 源文件。

3.同时将 showdate_jsp.java 源文件编译成 showdate_jsp.class。

4.编译执行showdate_jsp.class 类,处理请求,返回响应,容器将生成的页面返回给客户端显示。

  1. (转移成的java源文件  showdate_jsp.java)  
  2. package org.apache.jsp.ch04;      
  3.      
  4. import javax.servlet.*;      
  5. import javax.servlet.http.*;      
  6. import javax.servlet.jsp.*;      
  7. import java.text.*;      
  8. import java.util.*;;      
  9.      
  10. public final class showdate_jsp extends org.apache.jasper.runtime.HttpJspBase      
  11.     implements org.apache.jasper.runtime.JspSourceDependent {      
  12.      
  13.   private static java.util.List _jspx_dependants;      
  14.      
  15.   public Object getDependants() {      
  16.     return _jspx_dependants;      
  17.   }      
  18.      
  19.   public void _jspService(HttpServletRequest request, HttpServletResponse response)      
  20.         throws java.io.IOException, ServletException {      
  21.      
  22.     JspFactory _jspxFactory = null;      
  23.     PageContext pageContext = null;      
  24.     HttpSession session = null;      
  25.     ServletContext application = null;      
  26.     ServletConfig config = null;      
  27.     JspWriter out = null;      
  28.     Object page = this;      
  29.     JspWriter _jspx_out = null;      
  30.     PageContext _jspx_page_context = null;      
  31.      
  32.     try {      
  33.       _jspxFactory = JspFactory.getDefaultFactory();      
  34.       response.setContentType("text/html;charset=gb2312");      
  35.       pageContext = _jspxFactory.getPageContext(this, request, response,      
  36.                    null, true, 8192, true);      
  37.       _jspx_page_context = pageContext;      
  38.       application = pageContext.getServletContext();      
  39.       config = pageContext.getServletConfig();      
  40.       session = pageContext.getSession();      
  41.       out = pageContext.getOut();      
  42.       _jspx_out = out;      
  43.      
  44.       out.write("/r/n");      
  45.       out.write("<html>/r/n");      
  46.       out.write("<head>/r/n");      
  47.       out.write("<title>Show time</title>/r/n");      
  48.       out.write("</head>/r/n");      
  49.       out.write("<body> /r/n");      
  50.       out.write("/tHello : /r/n");      
  51.       out.write("/t");      
  52.      
  53.          SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");      
  54.          String str = format.format(new Date());      
  55.      
  56.       out.write("/r/n");      
  57.       out.write("/t ");      
  58.       out.print(str );      
  59.       out.write("/r/n");      
  60.       out.write("</body>/r/n");      
  61.       out.write("</html>");      
  62.     } catch (Throwable t) {      
  63.      
  64.       if (!(t instanceof SkipPageException)){      
  65.         out = _jspx_out;      
  66.         if (out != null && out.getBufferSize() != 0)      
  67.           out.clearBuffer();      
  68.         if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);      
  69.       }      
  70.      
  71.     } finally {      
  72.      
  73.       if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);      
  74.     }      
  75.   }      

当JSP页面被转译成Servlet时,内容主要包含三个部分:

  1. public void _jspInit(){ ..}       
  2. -- 当JSP网页一开始执行时,最先执行此方法,执行初始化工作     
  3. public void _jspDestory(){...} – JSP网页最后执行的方法     
  4. public void _jspService(HttpServletRequest request, HttpServletResponse response)     
  5.         throws java.io.IOException, ServletException { 

JSP网页中最主要的程序都是在此执行,将showdate.jsp和showdate_jsp.java做一个简单对比:s

Servlet 输出到网页的文字出现乱码的原因通常是编码设置不正确。以下是一些常见的原因和解决方法: --- ### 1. 问题分析 #### 常见原因 - **请求参数编码**:浏览器发送的请求参数(如表单数据)可能使用了默认的ISO-8859-1编码,而服务器没有正确转换为UTF-8。 - **响应内容编码**:Servlet输出的内容可能没有指定正确的字符集(如UTF-8),导致浏览器无法正确解析。 - **数据库或文件编码**:如果数据来源于数据库或文件,且这些数据的编码与Servlet输出的编码不一致,也会导致乱码。 --- ### 2. 解决方案 #### (1) 设置请求参数编码 在Servlet中,可以通过`request.setCharacterEncoding("UTF-8")`设置请求参数的编码为UTF-8。 ```java package com.example.servlet; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/example") public class ExampleServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置请求参数编码为UTF-8 request.setCharacterEncoding("UTF-8"); String name = request.getParameter("name"); response.getWriter().println("你好," + name); } } ``` #### 解释 - `request.setCharacterEncoding("UTF-8")`:强制将请求参数的编码设置为UTF-8,确保中文等非ASCII字符不会被错误解析。 --- #### (2) 设置响应内容编码 在输出响应时,需要明确指定字符集为UTF-8,并设置Content-Type头信息。 ```java protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置响应内容编码为UTF-8 response.setContentType("text/html;charset=UTF-8"); // 或者直接使用以下方式 response.setCharacterEncoding("UTF-8"); response.setHeader("Content-Type", "text/html;charset=UTF-8"); String message = "你好,世界!"; response.getWriter().println(message); } ``` #### 解释 - `response.setContentType("text/html;charset=UTF-8")`:设置响应的内容类型为HTML,并指定字符集为UTF-8。 - `response.setCharacterEncoding("UTF-8")`:单独设置响应的字符集为UTF-8。 - `response.setHeader("Content-Type", "text/html;charset=UTF-8")`:通过设置HTTP头信息显式指定字符集。 --- #### (3) 配置web.xml中的过滤器 为了确保所有请求和响应都使用UTF-8编码,可以在`web.xml`中配置一个过滤器。 ```xml <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>com.example.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> ``` 对应的过滤器代码如下: ```java package com.example.filter; import jakarta.servlet.*; import java.io.IOException; public class CharacterEncodingFilter implements Filter { private String encoding; @Override public void init(FilterConfig filterConfig) throws ServletException { encoding = filterConfig.getInitParameter("encoding"); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (encoding != null) { request.setCharacterEncoding(encoding); response.setCharacterEncoding(encoding); } chain.doFilter(request, response); } @Override public void destroy() { // 清理资源 } } ``` #### 解释 - 过滤器会在每个请求和响应中自动设置编码为UTF-8。 - 通过`web.xml`配置过滤器,可以避免在每个Servlet中重复设置编码。 --- #### (4) 确保JSP页面编码正确 如果前端使用了JSP页面,需要确保页面的编码设置为UTF-8。 ```jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>示例页面</title> </head> <body> <form action="example" method="get"> 名字: <input type="text" name="name"><br> <button type="submit">提交</button> </form> </body> </html> ``` #### 解释 - `contentType="text/html; charset=UTF-8"`:设置JSP页面的内容类型和字符集。 - `<meta charset="UTF-8">`:确保浏览器以UTF-8编码解析页面。 --- ### 3. 总结 通过以上方法,可以有效解决Servlet输出到网页的文字乱码问题: 1. 设置请求参数编码:`request.setCharacterEncoding("UTF-8")`。 2. 设置响应内容编码:`response.setContentType("text/html;charset=UTF-8")`。 3. 使用过滤器统一管理编码。 4. 确保JSP页面编码正确。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值