新聞中心
JSP學習經(jīng)驗前言
熟悉JAVA語法很久后,遲遲才開始學習JSP。而學習JSP時,卻只學了基本的用法就去學Struts和Hibernate,以致對JSP掌握得很不夠。后來發(fā)現(xiàn)所學習的Struts框架實際上是“包裝”了的JSP。所以,我在學習框架的時候也回頭看看JSP。 以后應(yīng)該不會再去專門學習JSP了?,F(xiàn)在把一些JSP學習經(jīng)驗總結(jié)下,記錄下來,以防來日忘了。 說明:以下所描述的環(huán)境是jdk1.5、tomcat5.5、 jsp2.0、 servlet2.4、JSTL1.1.2
一、基本配置 基本的重要的配置在web.xml 文件中。
1、Jsp屬性組

成都創(chuàng)新互聯(lián)公司是一家專業(yè)提供海曙企業(yè)網(wǎng)站建設(shè),專注與成都網(wǎng)站設(shè)計、網(wǎng)站制作、HTML5建站、小程序制作等業(yè)務(wù)。10年已為海曙眾多企業(yè)、政府機構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)網(wǎng)站建設(shè)公司優(yōu)惠進行中。
/pages/*url-pattern> trueel-ignore> UTF-8page-encoding> /include/header.jspfinclude-prelude> /include/copyright.jspfinclude-coda> - jsp-property-group>
這個設(shè)置可以指定頁面編碼,頁頭頁腳等等。
設(shè)置 UTF-8 的好處是不用在每個頁面像這樣指定編碼
而設(shè)置 /include/header.jspf 使得每個頁面都在頭部包含header.jspf文件(通常把對標簽的包含放在這里)。
2、數(shù)據(jù)庫資源的引用
CourseDesignJDNIdatasourcedescription> jdbc/testres-ref-name> javax.sql.DataSourceres-type> Containerres-auth> - resource-ref>
前提是要在TOMCAT的中配置
- <ContextpathContextpath="/Course"docBase="Course"debug=
"0"crosscontext="true"reloadable="true">- <ResourcenameResourcename="jdbc/test"auth=
"Container"type="javax.sql.DataSource"- maxActive="100"maxIdle="30"maxWait="10000"
- username="root"password="123456"
- driverClassName="com.mysql.jdbc.Driver"
- url="jdbc:mysql://localhost:3306/databaseName?
useUnicode=true&characterEncoding=UTF-8"/>- Context>
在程序中可以這樣獲取連接
- publicstaticConnectiongetConnection()
- ...{Connectionconn=null;
- try
- ...{
- ContextinitContext=newInitialContext();
- ContextenvContext=(Context)initContext.lookup"java:/comp/env");
- DataSourceds=(DataSource)envContext.lookup"jdbc/test");
- conn=ds.getConnection();
- }
- catch(Exceptione)...{
- }
- returnconn;
- }
3、過濾器
一般來說,字符編碼的處理,我們會寫一個過濾器。這個過濾器的JAVA類在TOMCAT的例子中有提供,可以按需來更改再拿來用。只要在配置文件中設(shè)置:
setCharacterEncodingfilter-name> powerwind.filter.SetCharacterEncodingFilterfilter-class> encodingparam-name> UTF-8param-value> - init-param>
- filter>
setCharacterEncodingfilter-name> /pages/*url-pattern> - filter-mapping>
4、標簽的URI
JSTL是個東西,里面提供了很好用的標簽(Tag),但也不一定滿足我們的要求,就自己寫標簽了。把 *.tld 文件直接放到WEB-INF下,在自己定義的tld文件中加上元素,如:http://powerwind/course 。
5、日志
只用過log4j這個日志包。首先是配置文件 log4j.properties (比較完整的配置,應(yīng)根據(jù)情況選擇):
- log4j.rootLogger=DEBUG,INFO,A1,A2,A3
- log4j.appender.A1=org.apache.log4j.ConsoleAppender
- log4j.appender.A1.layout=org.apache.log4j.PatternLayout
- log4j.appender.A1.layout.ConversionPattern=%4p[%t](%F:%L)-%m%n
- log4j.appender.A2=org.apache.log4j.RollingFileAppender
- log4j.appender.A2.File=../../log/test.log
- log4j.appender.A2.MaxFileSize=1KB
- log4j.appender.A2.MaxBackupIndex=3
- log4j.appender.A2.layout=org.apache.log4j.PatternLayout
- log4j.appender.A2.layout.ConversionPattern=%d{yyyy-MM-ddhh:mm:ss}:%p%t%c-%m%n
- log4j.appender.A3=org.apache.log4j.jdbc.JDBCAppender
- log4j.appender.A3.URL=jdbc:mysql://localhost:3306/log4jTest
- log4j.appender.A3.driver=com.mysql.jdbc.Driver
- log4j.appender.A3.user=root
- log4j.appender.A3.password=123456
- log4j.appender.A3.layout=org.apache.log4j.PatternLayout
- log4j.appender.A3.layout.ConversionPattern=INSERTINTO
- log4j(createDate,thread,level,class,message)values('%d','%t','%-5p','%c','%m')
接著寫個Servlet來加載log4j:
- packagepowerwind.servlet;
- importorg.apache.log4j.Logger;
- importorg.apache.log4j.PropertyConfigurator;
- importjavax.servlet.*;
- importjavax.servlet.http.*;
- publicclassLog4jInitextendsHttpServlet{
- publicvoidinit(ServletConfigconfig)throwsServletException{
- super.init(config);
- Stringprefix=getServletContext().getRealPath("/");
- Stringfile=getInitParameter("log4j");
- System.out.println("initlog4j...");
- if(file!=null){
- PropertyConfigurator.configure(prefix+file);
- }else
- {
- PropertyConfigurator.configure(prefix+"log4j.properties");}
- }
- }
然后同時要在web.xml下配置:
log4jInitservlet-name> powerwind.servlet.Log4jInitservlet-class> log4jparam-name> WEB-INF/classes/log4j.propertiesparam-value> - init-param>
1load-on-startup> - servlet>
小型的應(yīng)用中,我們并不常需要國際化。但是,如果網(wǎng)站要中文版和英文版的話,這個就不錯啦。使用時很簡單,把資源test_zh_CN.properties文件放到classes目錄下,然后用JSTL的fmt標簽調(diào)用。
其中var和scope屬性不是必需的。三者結(jié)合,就可以實現(xiàn)國際化了。
- <fmt:setLocalevaluefmt:setLocalevalue="zh_CN"scope=”session”/>
- <fmt:setBundlebasenamefmt:setBundlebasename="test"scope=”session”var=”hehe”/>
- <fmt:messagekeyfmt:messagekey="login.title"bundle=”${hehe}”scope=”session”/>
二、極限與安全
資源放在WEB-INF下是安全的,因為這個目錄對于客戶端是不存在的。權(quán)限控制并不是僅僅這樣就可以了。如果只是簡單地判斷用戶是否登錄,可用一個過濾器檢查Session對象即可。若需要級別控制的話,就在Session中保存級別信息,然后加以判斷。
一般把權(quán)限的控制做成一個標簽(tag)。如:
- publicintdoEndTag()throwsJspException{
- HttpSessionsession=pageContext.getSession();
- if((session!=null)&&(session.getAttribute("user")!=null)){
- Stringt=((UserBean)session.getAttribute("user")).getType();
- if(t==null||role==null){
- invalid();
- return(SKIP_PAGE);
- }
- String[]roleroles=role.split(delimiter);
- for(inti=0;i
;i++){ - if(roles[i].equalsIgnoreCase(role))
- return(EVAL_PAGE);
- }
- }else{
- invalid();
- return(SKIP_PAGE);
- }
- return(EVAL_PAGE);
- }
三、上傳與下載
上傳的話,一般使用已有的組件,如commons-fileupload 或者歐萊禮的cos (可能會遇到中文編碼的問題)。而下載,比較簡單,就自己寫了個Servlet。
- publicvoidhandleRequest(HttpServletRequestrequest,
- HttpServletResponseresponse)throwsIOException,ServletException{
- Stringname=request.getParameter("name");
- Stringtype=request.getParameter("type");
- Stringdir=request.getParameter("dir");
- if(name==null||name.length()<2||dir==null||dir.
length()<1||type==null||type.length()<1){- thrownewServletException("Sorry,erroroccured");
- }
- charch=dir.charAt(dir.length()-1);
- if(ch!='/'||ch!='\')
- dirdir=dir+"/";
- ServletOutputStreamos=null;
- BufferedInputStreambis=null;
- try{
- Filefile=newFile(dir+name);
- if(!file.exists()||file.length()>=Integer.MAX_VALUE){
- logger.error("Invalidfileorfiletolarge,file:"+name);
- thrownewServletException(
- "Invalidfileorfiletolarge,file:"+name);
- }
- response.setContentType("application/"+type);
- response.addHeader("Content-Disposition","attachment;filename="+name);
- response.setContentLength((int)file.length());
- os=response.getOutputStream();
- bis=newBufferedInputStream(newFileInputStream(file));
- intsize=-1;
- while((size=bis.read())!=-1)
- os.write(size);
- }catch(IOExceptionioe){
- thrownewServletException(ioe.getMessage());
- }finally{
- if(os!=null)
- os.close();
- if(bis!=null)
- bis.close();
- }
- }
以上只是個示例程序紀錄在JSP學習經(jīng)驗中,靈活與方便的做法應(yīng)該是在Servlet初始化參數(shù)()設(shè)置下載文件所在目錄,當然也可以在頁面中設(shè)置參數(shù)。甚至可以做成一個下載標簽,方便使用。
名稱欄目:JSP學習經(jīng)驗全面總結(jié)
新聞來源:http://fisionsoft.com.cn/article/dphdhoi.html


咨詢
建站咨詢
