Web开发小结 - 1

Jetty配置

在插件位置配置jetty, 在配置的时候也可以不指定插件的版本, 默认使用
   < plugin >
         < groupId >org.mortbay.jetty groupId >
         < artifactId >maven-jetty-plugin artifactId >
         < version >6.1.9 version >
       plugin >

jetty->请求的操作无法在使用用户映射区域打开的文件上执行

jetty\etc\webdefault.xml中 
Java代码 
  1.   
  2.   useFileMappedBuffer  
  3.   true   
  4.   


原贴http://docs.codehaus.org/display/JETTY/Files+locked+on+Windows

 或者在web.xml中插入如下信息:

      
      
      
      
  1. <servlet> 
  2.         <servlet-name>defaultservlet-name> 
  3.         <servlet-class>org.mortbay.jetty.servlet.DefaultServletservlet-class> 
  4.         <init-param> 
  5.             <param-name>useFileMappedBufferparam-name> 
  6.             <param-value>falseparam-value> 
  7.         init-param> 
  8.         <load-on-startup>0load-on-startup> 
  9.     servlet> 

 

 

1、Filter设置统一字符集

【注意】filter只对post请求起作用,对get请求不起作用

1.Filter设置统一字符集类:CharsetEncodingFilter.java

 

    
    
    
    
  1. import java.io.IOException; 
  2. import javax.servlet.Filter; 
  3. import javax.servlet.FilterChain; 
  4. import javax.servlet.FilterConfig; 
  5. import javax.servlet.ServletException; 
  6. import javax.servlet.ServletRequest; 
  7. import javax.servlet.ServletResponse; 
  8. /** 
  9.  * 统一设置字符集 
  10.  * 
  11.  */ 
  12. public class CharsetEncodingFilter implements Filter { 
  13.   
  14.  private String encoding; 
  15.   
  16.  public void destroy() { 
  17.  } 
  18.  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, 
  19.    FilterChain filterChain) throws IOException, ServletException { 
  20.    
  21.   //设置字符集 
  22.   servletRequest.setCharacterEncoding(encoding); 
  23.     filterChain.doFilter(servletRequest, servletResponse); 
  24.  } 
  25.  public void init(FilterConfig filterConfig) throws ServletException { 
  26.   //取得初始化参数 
  27.   this.encoding = filterConfig.getInitParameter("encoding"); 
  28.   } 

2.在web.xml增加以下内容

 

    
    
    
    
  1. <filter> 
  2.   <filter-name>CharsetEncodingFilterfilter-name> 
  3.   <filter-class>com.lx.filter.CharsetEncodingFilterfilter-class> 
  4.   <init-param> 
  5.    <param-name>encodingparam-name> 
  6.    <param-value>GB18030param-value> 
  7.   init-param> 
  8.  filter> 
  9.   
  10.  <filter-mapping> 
  11.   <filter-name>CharsetEncodingFilterfilter-name> 
  12.   <url-pattern>*.jspurl-pattern> 
  13.  filter-mapping> 

 2、JSP中路径查找的解决方案

 

    
    
    
    
  1. <
  2.     String path = request.getContextPath(); 
  3.     String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
  4. %> 

 在JSP的正文部分开头加上如下代码则之下的代码直接从根(WebRoot)开始查找

 

    
    
    
    
  1. <base href="<%=basePath %>"> 

 3、文件上传

(1)提交方式必须为post,且指定enctype="multipart/form-data"

 

    
    
    
    
  1. <body class="body1"> 
  2.     <form name="itemForm" target="_self" id="itemForm" action="servlet/basedata/ItemUploadServlet" enctype="multipart/form-data" method="post"> 
  3.         <input type="hidden" name="itemNo" value="<%=item.getItemNo() %>"> 
  4.         <div align="center"> 
  5.                 <tr> 
  6.                     <td height="74"> 
  7.                         <div align="right"> 
  8.                             图片:  
  9.                         div> 
  10.                     td> 
  11.                     <td> 
  12.                         <img src="upload/<%=item.getItemNo() %>.gif" width="85" height="49"> 
  13.                     td> 
  14.                 tr> 
  15.                 <tr> 
  16.                     <td width="22%" height="29"> 
  17.                         <div align="right"> 
  18.                             <font color="#FF0000">*font>选择图片:  
  19.                         div> 
  20.                     td> 
  21.                     <td width="78%"> 
  22.                         <input name="fileName" type="file" class="text1" size="40" maxlength="40"> 
  23.                     td> 
  24.                 tr> 
  25.             table> 
  26.             <hr width="97%" align="center" size=0> 
  27.             <div align="center"> 
  28.                 <input name="btn_upload" class="button1" type="submit" 
  29.                     id="btn_upload" value="上传"> 
  30.                      
  31.                 <input name="btnBack" class="button1" type="button" id="btnBack" 
  32.                     value="返回" onClick="location='<%=basePath %>servlet/basedata/SearchItemServlet'"> 
  33.             div> 
  34.         div> 
  35.     form> 
  36. body> 

 

ItemUploadServlet.java用于处理文件的上传 

    
    
    
    
  1. public class ItemUploadServlet extends HttpServlet { 
  2.   
  3.     //private String uploadPath = "D:\\apache-tomcat-5.5.26\\webapps\\drp4.5\\upload\\"; // 用于存放上传文件的目录 
  4.  
  5.     // 用于存放临时文件的目录 
  6.     private File tempPath = null;  
  7.      
  8.     private File uploadPath = null
  9.      
  10.     @Override 
  11.     public void init() throws ServletException { 
  12.         //取得临时交换目录 
  13.         tempPath = new File(this.getServletContext().getRealPath("temp")); 
  14.         //如果目录不存在,创建一个 
  15.         if (!tempPath.exists()) { 
  16.             tempPath.mkdir(); 
  17.         } 
  18.         //取得上传路径 
  19.         uploadPath = new File(this.getServletContext().getRealPath("upload")); 
  20.         //如果目录不存在,创建一个 
  21.         if (!uploadPath.exists()) { 
  22.             uploadPath.mkdir(); 
  23.         } 
  24.     } 
  25.  
  26.     @SuppressWarnings({ "unused""unchecked" }) 
  27.     public void doPost(HttpServletRequest req, HttpServletResponse res) 
  28.             throws ServletException, IOException { 
  29.         //采用request不能取得普通表单数据 
  30.         //String itemNo = req.getParameter("itemNo"); 
  31.         DiskFileItemFactory factory = new DiskFileItemFactory(); 
  32.         // maximum size that will be stored in memory 
  33.         factory.setSizeThreshold(4096); 
  34.         // the location for saving data that is larger than getSizeThreshold() 
  35.         factory.setRepository(tempPath); 
  36.  
  37.         ServletFileUpload upload = new ServletFileUpload(factory); 
  38.         // maximum size before a FileUploadException will be thrown 
  39.         upload.setSizeMax(1000000); 
  40.         try { 
  41.             List fileItems = upload.parseRequest(req); 
  42.             Iterator iter = fileItems.iterator(); 
  43.             String itemNo = ""
  44.             while (iter.hasNext()) { 
  45.                 FileItem item = (FileItem) iter.next(); 
  46.                 if (item.isFormField()) { 
  47.                     if ("itemNo".equals(item.getFieldName())) { 
  48.                         itemNo = item.getString(); 
  49.                     } 
  50.                     //if ("itemName".equals(item.getFieldName())) { 
  51.                     //   
  52.                     //} 
  53.                 } 
  54.                 // 忽略其他不是文件域的所有表单信息 
  55.                 if (!item.isFormField()) { 
  56.                     String fileName = item.getName(); 
  57.                     fileName = fileName.substring(fileName.lastIndexOf("\\"), fileName.length()); 
  58.                     String fullFilePath = uploadPath +  "\\" + itemNo + ".gif"; 
  59.                     item.write(new File(fullFilePath)); 
  60.                     res.sendRedirect(req.getContextPath() + "/servlet/basedata/SearchItemServlet"); 
  61.                 } 
  62.             }    
  63.         } catch (Exception e) { 
  64.             throw new AppException("文件上传失败!"); 
  65.         } 
  66.     } 

 

 4、获取本机的IP地址和计算机名, 可放在提交表单的隐含域中进行提交到服务器中

 在jsp中使用时加入:<%@ page import="java.net.InetAddress" %>

    
    
    
    
  1. InetAddress addr = InetAddress.getLocalHost();  
  2. String ip=addr.getHostAddress().toString();//获得本机IP  
  3. String address=addr.getHostName().toString();//获得本机名称  

 5、使用index.html定位login.jsp页面,则可直接输入工程名即可访问登陆页面

index.html:location完成跳转

    
    
    
    
  1. <script> 
  2.     location="login.jsp"
  3. script> 

 使用html页面转换为jsp页面时需要去掉html的相关信息,而在头部添加信息:

 jsp头部如下:

    
    
    
    
  1. <%@ page language="java" contentType="text/html; charset=GB18030" 
  2.     pageEncoding="GB18030"%> 

 html头部如下:

    
    
    
    
  1. > 

 6、JSP中的指令

JSP指令的用途非常简单,它只是告诉JSP引擎对JSP页面如何编译。因此它不包含业务逻辑,也不修改out流。这些指令始终被括在 “<%@ ?%>”标记中。两个最重要的指令是“pagePage”和“Include”。

(1)引入java代码指令:

    
    
    
    
  1. <%@ page import="com.util.*" %>     

 (2)page指令

基本语法
page 指令是以<%@ page 起始,以%>结束:
      <%@ page attribute1=“value1” attribute2= “value2” attribute3=…%>

3、Include指令

<%@ include file="url"%>
  file的属性值被解释为相对于当前jsp文件的URL.

 

 

 7、是否显示目录下面所有文件: Tomcat中web..xml设置 - listings

修改配置文件: %Catalina%/conf/web.xml

找到: default 
org.apache.catalina.servlets.DefaultServlet 
 
debug 
0 
 
 
listings 
true 
 
1 

default: true // display the Directory Listing for

false // disable

  8、多浏览器测试工具IETester

 download: http://www.my-debugbar.com/wiki/IETester/HomePage

  9、SQL注入问题 - 由于SQL拼串所造成的

由于”or '1'='1'“导致了通过验证,具体方式如下:

    
    
    
    
  1. * 登录,演示SQL注入 
  2. 用户:aaaaa 
  3. 密码:' or '1'='
  4. 形成的sql语句如下:select * from t_user where user_id='aaaaa' and password='' or '1'='1' 

 10、404或500错误处理

在web.xml中配置

 

    
    
    
    
  1. <error-page> 
  2.         <exception-type>com.company.util.AppExceptionexception-type> 
  3.         <location>/error.jsplocation> 
  4.     error-page> 
  5.      
  6.     <error-page> 
  7.         <error-code>404error-code> 
  8.         <location>/http_error.jsplocation> 
  9.     error-page> 
  10.      
  11.     <error-page> 
  12.         <error-code>500error-code> 
  13.         <location>/http_error.jsplocation> 
  14.     error-page> 

 在http_error.jsp中取得错误代码进行跳转

    
    
    
    
  1. <body> 
  2.     <
  3.         Integer errorCode = (Integer)request.getAttribute("javax.servlet.error.status_code"); 
  4.         //System.out.println("http_error=" + errorCode); 
  5.         if (errorCode == 404) { 
  6.             response.sendRedirect(request.getContextPath() + "/404.html");   
  7.         }else if (errorCode == 500) { 
  8.             response.sendRedirect(request.getContextPath() + "/500.html"); 
  9.         } 
  10.     %> 
  11. body> 

 404.html

    
    
    
    
  1. <html> 
  2.     <head> 
  3.         <meta http-equiv="content-type" content="text/html;charset=gb2312" /> 
  4.     head> 
  5.     <body> 
  6.         未找到请求的页面 
  7.     body> 
  8. html> 

500.html

    
    
    
    
  1. <html> 
  2.     <head> 
  3.         <meta http-equiv="content-type" content="text/html;charset=gb2312" /> 
  4.     head> 
  5.     <body> 
  6.         系统出现错误,请与系统管理员联系! 
  7.     body> 
  8. html> 

 11、文本框中的Disabled和ReadOnly的区别

设置为Diabled无法通过request.getParameter("userId")取得内容,而readonly是可以的 

    
    
    
    
  1. <table width="95%" border="0" cellpadding="0" cellspacing="0"> 
  2.                     <tr> 
  3.                         <td width="22%" height="29"> 
  4.                             <div align="right"> 
  5.                                 用户代码:  
  6.                             div> 
  7.                         td> 
  8.                         <td width="78%"> 
  9.                             <input name="userId" type="text" class="text1" id="userId" 
  10.                                 size="10" maxlength="10" readonly="true" value="<%=user.getUserId() %>"> 
  11.                         td> 
  12.                     tr> 
  13. table> 

 12、Fileter处理对字符集进行统一的处理

 在web.xml中进行配置filter, 它体现了一种‘责任链’模式

    
    
    
    
  1. <filter> 
  2.     <filter-name>CharsetEncodingFilterfilter-name> 
  3.     <filter-class>com.company.util.filter.CharsetEncodingFilterfilter-class> 
  4.     <init-param> 
  5.         <param-name>encodingparam-name> 
  6.         <param-value>GB18030param-value> 
  7.     init-param> 
  8. filter> 
  9.  
  10. <filter-mapping> 
  11.     <filter-name>CharsetEncodingFilterfilter-name> 
  12.     <url-pattern>*.jspurl-pattern> 
  13. filter-mapping> 
    
    
    
    
  1. import java.io.IOException; 
  2.  
  3. import javax.servlet.Filter; 
  4. import javax.servlet.FilterChain; 
  5. import javax.servlet.FilterConfig; 
  6. import javax.servlet.ServletException; 
  7. import javax.servlet.ServletRequest; 
  8. import javax.servlet.ServletResponse; 
  9.  
  10. /** 
  11.  * 统一设置字符集 
  12.  * @author Administrator 
  13.  * 
  14.  */ 
  15. public class CharsetEncodingFilter implements Filter { 
  16.      
  17.     private String encoding; 
  18.      
  19.     public void destroy() { 
  20.     } 
  21.  
  22.     public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, 
  23.             FilterChain filterChain) throws IOException, ServletException { 
  24.          
  25.         //设置字符集 
  26.         servletRequest.setCharacterEncoding(encoding); 
  27.         System.out.println("CharsetEncodingFilter.doFilter--begin"); 
  28.         filterChain.doFilter(servletRequest, servletResponse); 
  29.         System.out.println("CharsetEncodingFilter.doFilter--end"); 
  30.     } 
  31.  
  32.     public void init(FilterConfig filterConfig) throws ServletException { 
  33.         //取得初始化参数 
  34.         this.encoding = filterConfig.getInitParameter("encoding"); 
  35.         System.out.println("CharsetEncodingFilter.init() encoding=" + this.encoding); 
  36.     } 

 也可以在实现fileter的类进行处理, 之前之后处理完成想要完成的事情, 比如直接设置字符集处理等

 

    
    
    
    
  1. import java.io.IOException; 
  2. import javax.servlet.Filter; 
  3. import javax.servlet.FilterChain; 
  4. import javax.servlet.FilterConfig; 
  5. import javax.servlet.ServletException; 
  6. import javax.servlet.ServletRequest; 
  7. import javax.servlet.ServletResponse; 
  8.  
  9. /** 
  10.  * 统一设置字符集 
  11.  * @author Administrator 
  12.  * 
  13.  */ 
  14. public class CharsetEncodingFilter implements Filter { 
  15.      
  16.     public void destroy() { 
  17.     } 
  18.  
  19.     public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, 
  20.             FilterChain filterChain) throws IOException, ServletException { 
  21.          
  22.         //设置字符集 
  23.         servletRequest.setCharacterEncoding("GB18030"); 
  24.         filterChain.doFilter(servletRequest, servletResponse); 
  25.     } 
  26.  
  27.     public void init(FilterConfig filterConfig) throws ServletException { 
  28.     } 

 13、HTTPLOOK查看http访问过程

download:http://www.skycn.com/soft/10782.html

 

 14、配置安全的访问页面, 访问WEB-INF下面的页面

WEB-INF下面的内容对外面来讲是不能访问的,如果需要访问,可以通过配置web.xml来解决。

    
    
    
    
  1.  <servlet> 
  2.   <servlet-name>demoservlet-name>  
  3.   <jsp-file>/WEB-INF/hello.jsp</jsp-file>  
  4. <init-param> 
  5.   <param-name>driverparam-name>  
  6.   <param-value>oracle.jdbc.driver.OracleDriverparam-value>  
  7.   init-param> 
  8. <init-param> 
  9.   <param-name>urlparam-name>  
  10.   <param-value>jdbc:oracle:thin:@localhost:1521:sidparam-value>  
  11.   init-param> 
  12.   servlet> 
  13. <servlet-mapping> 
  14.   <servlet-name>demoservlet-name>  
  15.   <url-pattern>/hello.welcomeurl-pattern>  
  16.   servlet-mapping> 

 通过config取得初始化参数:

    
    
    
    
  1. <html> 
  2. <head> 
  3.     <title>HELLO JSP WORLD!!!title> 
  4. head> 
  5. <body> 
  6.     <h1><%=config.getInitParameter("driver")%>h1> 
  7.     <h1><%=config.getInitParameter("url")%>h1> 
  8. body> 
  9. html> 

 15、配置tomcat的虚拟目录

            unpackWARs="true" autoDeploy="true"
            xmlValidation="false" xmlNamespaceAware="false">
 

Tomcat的conf\server.xml文件中上面配置 context的reloadable属性的时候,设置了path和docBase,
如果说path是Tomcat的wabapps目录下的项目名称,那么docBase是设置的那个路径呢?

答疑:
path对应的是我们每次在访问一个网站的时候在浏览器上输入的虚拟目录路径,而服务器上的具体的对应的目录就是docBase。实际上二者是一个映射过程。

 
则可通过http://localhost:8080/helloworld/index.jsp来访问目录 d:\demoes\webdemo\WebRoot下面的index.jsp页面。