JSP学习经验全面总结

开发 后端
本文全面总结JSP学习经验,熟悉JAVA语法很久后,迟迟才开始学习JSP,学习JSP时,却只学了基本的用法就去学Struts和Hibernate,以致对JSP掌握得很不够。
JSP学习经验前言
 
熟悉JAVA语法很久后,迟迟才开始学习JSP。而学习JSP时,却只学了基本的用法就去学Struts和Hibernate,以致对JSP掌握得很不够。后来发现所学习的Struts框架实际上是“包装”了的JSP。所以,我在学习框架的时候也回头看看JSP。
 
以后应该不会再去专门学习JSP了。现在把一些JSP学习经验总结下,记录下来,以防来日忘了。
 
说明:以下所描述的环境是jdk1.5、tomcat5.5、 jsp2.0、 servlet2.4、JSTL1.1.2
 
一、基本配置
 
基本的重要的配置在web.xml 文件中。
 
1、Jsp属性组
  1. <jsp-property-group> 
  2. <url-pattern>/pages/*url-pattern> 
  3. <el-ignore>trueel-ignore> 
  4. <page-encoding>UTF-8page-encoding> 
  5. <include-prelude>/include/header.jspfinclude-prelude> 
  6. <include-coda>/include/copyright.jspfinclude-coda> 
  7. jsp-property-group> 

这个设置可以指定页面编码,页头页脚等等。

设置 UTF-8 的好处是不用在每个页面像这样指定编码

而设置 /include/header.jspf 使得每个页面都在头部包含header.jspf文件(通常把对标签的包含放在这里)。

2、数据库资源的引用

  1. <resource-ref> 
  2. <description>CourseDesignJDNIdatasourcedescription> 
  3. <res-ref-name>jdbc/testres-ref-name> 
  4. <res-type>javax.sql.DataSourceres-type> 
  5. <res-auth>Containerres-auth> 
  6. resource-ref> 

前提是要在TOMCAT的中配置

  1. <ContextpathContextpath="/Course"docBase="Course"debug=
    "0"
    crosscontext="true"reloadable="true"> 
  2. <ResourcenameResourcename="jdbc/test"auth=
    "Container"
    type="javax.sql.DataSource" 
  3. maxActive="100"maxIdle="30"maxWait="10000" 
  4. username="root"password="123456"  
  5. driverClassName="com.mysql.jdbc.Driver" 
  6. url="jdbc:mysql://localhost:3306/databaseName?
    useUnicode=true&characterEncoding=UTF-8"
    /> 
  7. Context> 

在程序中可以这样获取连接

  1. publicstaticConnectiongetConnection()  
  2. ...{Connectionconn=null;  
  3. try  
  4. ...{  
  5. ContextinitContext=newInitialContext();  
  6. ContextenvContext=(Context)initContext.lookup"java:/comp/env");  
  7. DataSourceds=(DataSource)envContext.lookup"jdbc/test");  
  8. conn=ds.getConnection();  
  9. }  
  10. catch(Exceptione)...{  
  11. }  
  12. returnconn;  

3、过滤器

一般来说,字符编码的处理,我们会写一个过滤器。这个过滤器的JAVA类在TOMCAT的例子中有提供,可以按需来更改再拿来用。只要在配置文件中设置:

  1. <filter-name>setCharacterEncodingfilter-name> 
  2. <filter-class>powerwind.filter.SetCharacterEncodingFilterfilter-class> 
  3. <init-param> 
  4. <param-name>encodingparam-name> 
  5. <param-value>UTF-8param-value> 
  6. init-param> 
  7. filter> 
  8. <filter-mapping> 
  9. <filter-name>setCharacterEncodingfilter-name> 
  10. <url-pattern>/pages/*url-pattern> 
  11. filter-mapping> 

4、标签的URI

JSTL是个东西,里面提供了很好用的标签(Tag),但也不一定满足我们的要求,就自己写标签了。把 *.tld 文件直接放到WEB-INF下,在自己定义的tld文件中加上元素,如:http://powerwind/course 。

5、日志

只用过log4j这个日志包。首先是配置文件 log4j.properties (比较完整的配置,应根据情况选择):

  1. log4j.rootLogger=DEBUG,INFO,A1,A2,A3  
  2. log4j.appender.A1=org.apache.log4j.ConsoleAppender  
  3. log4j.appender.A1.layout=org.apache.log4j.PatternLayout  
  4. log4j.appender.A1.layout.ConversionPattern=%4p[%t](%F:%L)-%m%n  
  5.  
  6. log4j.appender.A2=org.apache.log4j.RollingFileAppender  
  7. log4j.appender.A2.File=../../log/test.log  
  8. log4j.appender.A2.MaxFileSize=1KB 
  9. log4j.appender.A2.MaxBackupIndex=3 
  10. log4j.appender.A2.layout=org.apache.log4j.PatternLayout  
  11. log4j.appender.A2.layout.ConversionPattern=%d{yyyy-MM-ddhh:mm:ss}:%p%t%c-%m%n  
  12.  
  13. log4j.appender.A3=org.apache.log4j.jdbc.JDBCAppender  
  14. log4j.appender.A3.URL=jdbc:mysql://localhost:3306/log4jTest  
  15. log4j.appender.A3.driver=com.mysql.jdbc.Driver  
  16. log4j.appender.A3.user=root 
  17. log4j.appender.A3.password=123456 
  18. log4j.appender.A3.layout=org.apache.log4j.PatternLayout  
  19. log4j.appender.A3.layout.ConversionPattern=INSERTINTO 
  20. log4j(createDate,thread,level,class,message)values('%d','%t','%-5p','%c','%m') 

接着写个Servlet来加载log4j:

  1. packagepowerwind.servlet;  
  2. importorg.apache.log4j.Logger;  
  3. importorg.apache.log4j.PropertyConfigurator;  
  4.  
  5. importjavax.servlet.*;  
  6. importjavax.servlet.http.*;  
  7.  
  8. publicclassLog4jInitextendsHttpServlet{  
  9. publicvoidinit(ServletConfigconfig)throwsServletException{  
  10. super.init(config);  
  11. Stringprefix=getServletContext().getRealPath("/");  
  12. Stringfile=getInitParameter("log4j");  
  13. System.out.println("initlog4j...");  
  14. if(file!=null){  
  15. PropertyConfigurator.configure(prefix+file);  
  16. }else  
  17. {  
  18. PropertyConfigurator.configure(prefix+"log4j.properties");}  
  19. }  

然后同时要在web.xml下配置:

  1. <servlet> 
  2. <servlet-name>log4jInitservlet-name> 
  3. <servlet-class>powerwind.servlet.Log4jInitservlet-class> 
  4. <init-param> 
  5. <param-name>log4jparam-name> 
  6. <param-value>WEB-INF/classes/log4j.propertiesparam-value> 
  7. init-param> 
  8. <load-on-startup>1load-on-startup> 
  9. servlet> 

小型的应用中,我们并不常需要国际化。但是,如果网站要中文版和英文版的话,这个就不错啦。使用时很简单,把资源test_zh_CN.properties文件放到classes目录下,然后用JSTL的fmt标签调用。

其中var和scope属性不是必需的。三者结合,就可以实现国际化了。

  1. <fmt:setLocalevaluefmt:setLocalevalue="zh_CN"scope=”session”/> 
  2. <fmt:setBundlebasenamefmt:setBundlebasename="test"scope=”session”var=”hehe”/> 
  3. <fmt:messagekeyfmt:messagekey="login.title"bundle=”${hehe}”scope=”session”/> 

二、极限与安全

资源放在WEB-INF下是安全的,因为这个目录对于客户端是不存在的。权限控制并不是仅仅这样就可以了。如果只是简单地判断用户是否登录,可用一个过滤器检查Session对象即可。若需要级别控制的话,就在Session中保存级别信息,然后加以判断。

一般把权限的控制做成一个标签(tag)。如:

  1. publicintdoEndTag()throwsJspException{  
  2. HttpSessionsession=pageContext.getSession();  
  3. if((session!=null)&&(session.getAttribute("user")!=null)){  
  4. Stringt=((UserBean)session.getAttribute("user")).getType();  
  5. if(t==null||role==null){  
  6. invalid();  
  7. return(SKIP_PAGE);  
  8. }  
  9. String[]roleroles=role.split(delimiter);  
  10. for(inti=0;i<roles.length;i++){  
  11. if(roles[i].equalsIgnoreCase(role))  
  12. return(EVAL_PAGE);  
  13. }  
  14. }else{  
  15. invalid();  
  16. return(SKIP_PAGE);  
  17. }  
  18. return(EVAL_PAGE);  

三、上传与下载

上传的话,一般使用已有的组件,如commons-fileupload 或者欧莱礼的cos (可能会遇到中文编码的问题)。而下载,比较简单,就自己写了个Servlet。

  1. publicvoidhandleRequest(HttpServletRequestrequest,  
  2. HttpServletResponseresponse)throwsIOException,ServletException{  
  3. Stringname=request.getParameter("name");  
  4. Stringtype=request.getParameter("type");  
  5. Stringdir=request.getParameter("dir");  
  6. if(name==null||name.length()<2||dir==null||dir.
    length()
    <1||type==null||type.length()<1){  
  7. thrownewServletException("Sorry,erroroccured");  
  8. }  
  9. charch=dir.charAt(dir.length()-1);  
  10. if(ch!='/'||ch!='\')  
  11. dirdir=dir+"/";  
  12. ServletOutputStreamos=null;  
  13. BufferedInputStreambis=null;  
  14. try{  
  15. Filefile=newFile(dir+name);  
  16. if(!file.exists()||file.length()>=Integer.MAX_VALUE){  
  17. logger.error("Invalidfileorfiletolarge,file:"+name);  
  18. thrownewServletException(  
  19. "Invalidfileorfiletolarge,file:"+name);  
  20. }  
  21. response.setContentType("application/"+type);  
  22. response.addHeader("Content-Disposition","attachment;filename="+name);  
  23. response.setContentLength((int)file.length());  
  24. os=response.getOutputStream();  
  25. bis=newBufferedInputStream(newFileInputStream(file));  
  26. intsize=-1;  
  27. while((size=bis.read())!=-1)  
  28. os.write(size);  
  29. }catch(IOExceptionioe){  
  30. thrownewServletException(ioe.getMessage());  
  31. }finally{  
  32. if(os!=null)  
  33. os.close();  
  34. if(bis!=null)  
  35. bis.close();  
  36. }  

以上只是个示例程序纪录在JSP学习经验中,灵活与方便的做法应该是在Servlet初始化参数()设置下载文件所在目录,当然也可以在页面中设置参数。甚至可以做成一个下载标签,方便使用。

【编辑推荐】

  1. 全面介绍JSP标准标记库JSTL
  2. JSP开发技术应用详解
  3. 在实战中成长:JSP开发之路
  4. Servlet和JSP技术特性
  5. JSP标签库概念及特点介绍
责任编辑:佚名 来源: Csdn
相关推荐

2011-07-08 13:15:52

JSP

2009-08-20 17:35:47

Servlet和JSP

2009-07-01 11:44:32

JSP学习教程

2009-08-10 16:25:30

JSP SQL Ser

2009-09-16 17:13:54

学习Linq

2013-12-18 15:54:21

2009-08-13 18:13:27

C#学习经验

2011-07-21 13:40:17

java

2010-06-13 13:44:07

UML学习笔记

2009-07-02 11:49:44

JSP学习步骤

2010-06-02 09:06:26

SVN学习

2009-08-11 14:20:41

C# .NET学习经验

2009-09-01 13:10:39

C#读取Word

2010-01-05 16:46:14

学习.NET Fram

2009-08-07 09:47:17

C#枚举C#数组

2011-01-12 17:27:53

2009-12-22 18:36:17

WCF知识结构

2009-09-04 16:33:28

CCNA学习方法

2010-09-28 16:05:36

J2ME技术J2MEWTK

2009-03-21 19:21:22

点赞
收藏

51CTO技术栈公众号