iBatis.java

2008年12月11日 #

JSP与Servlet的跳转及得到路径方法整理

今天整理项目的流程,在JSP和Servlet之间跳来跳去,曾经一段时间,我都是把Servlet路径定义为“/SomeServlet”,也即定义为根目录,因为兼容性比较好,但是用了MyEclipse之后,新建的Servlet默认路径是“/servlet/SomeServlet”,这样写便于管理,另外就是更适合单独为Servlet设置Filter(关于Filter的设置可以参考这篇文章)。而我的JSP文件目前是放在项目的根目录,也即形成下图这样的路径结构:

/ProjectRoot/
  |--servlet/
  |  |--Servlet1
  |  |--Servlet2
  |
  |--myJsp1.jsp
  |--myJsp2.jsp

其中Servlet跳转有两种方式:
1、sendRedirect()方式

response.sendRedirect(String targetUrl);

2、RequestDispather方式

RequestDispatcher requestDispatcher = request.getRequestDispatcher(String targetUrl);
requestDispatcher.forward(request, response);


第一种方式是给用户浏览器发送通知,然后由浏览器再给服务器发送跳转请求,所以比较类似用户自己去点URL的跳转,这种方式如果需要传参给跳转页面,需要使用Session或者使用GET方式将参数显式的写在targetUrl里(如:ooxx.jsp?id=1),而且大部分情况下由于GET方法的局限性,这种跳转方式只能带较为简单的参数。

而第二种方式有点类似C#中的Server.Transfer()方法,即服务器端跳转,从现象上看就是用户的浏览器内容发生了变化,但是浏览器的地址栏不变还是老地址。这种方式由服务器直接控制request及response的走向及参数,从命令行的参数上就可以看出这一点。这样方便程序员控制参数的传递,几乎可以传递任何类型的参数,只要简单的使用setAttribute()方法即可:

request.setAttribute(String attriName, Object attriValue);


但是也就是因为它是服务器端跳转,所以用户浏览器的地址栏是不发生变化的。那么,如果项目路径结构如上图所示的情况,那么:
1、从JSP跳转向Servlet时
只要简单的使用相对路径“serlvet/SomeServlet”即可。

2、从Servlet跳转向另一个Servlet时
因为Servlet都在相同路径下,所以可以直接写相对路径,如“./SomeServlet”或直接“SomeServlet”。

3、从Servlet跳转向JSP时
因为Servlet路径为“servlet/SomeServlet”,所以如果要使用RequestDispather方式跳转,JSP页面在接参数时,会将地址栏的地址作为当前目录寻找自己需要的方法、JavaScript、CSS等。所以经常有朋友遇到JavaScript报错“Ext未定义”就是因为JSP页面找不到Ext的js文件。所以这种情况,需要使用绝对路径来告诉JSP去哪里得到这些资源。JAVA有关获得路径的方法较多,测试如下:

项目根目录:http://localhost:8080/TestProject/
JSP测试:http://localhost:8080/TestProject/TestPath.jsp

 1<%@ page language="java" contentType="text/html; charset=UTF-8"
 2    pageEncoding="UTF-8"
%>
 3<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4<html>
 5<head>
 6<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7<title>Insert title here</title>
 8</head>
 9<body>
10<%="request.getContextPath() = " + request.getContextPath() + "<BR />"%>
11<%="request.getServletPath() = " + request.getServletPath() + "<BR />"%>
12<%="request.getRequestURI() = " + request.getRequestURI() + "<BR />"%>
13<%="request.getRequestURL() = " + request.getRequestURL() + "<BR />"%>
14<%
15    String realPath = session.getServletContext().getRealPath("/");
16
%>
17<%="request.getRealPath(\"/\") = " + realPath + ""%>
18</body>
19</html>

返回结果:

request.getContextPath() = /TestProject
request.getServletPath() = /TestPath.jsp
request.getRequestURI() = /TestProject/TestPath.jsp
request.getRequestURL() = http://localhost:8080/TestProject/TestPath.jsp
request.getRealPath("/") = C:\Tomcat\webapps\TestProject\


Servlet测试

 1package servlet;
 2
 3import java.io.IOException;
 4import java.io.PrintWriter;
 5
 6import javax.servlet.ServletException;
 7import javax.servlet.http.HttpServlet;
 8import javax.servlet.http.HttpServletRequest;
 9import javax.servlet.http.HttpServletResponse;
10import javax.servlet.http.HttpSession;
11
12public class TestPath extends HttpServlet {
13
14    private static final long serialVersionUID = 3093731648408094325L;
15
16    public void doGet(HttpServletRequest request, HttpServletResponse response)
17            throws ServletException, IOException {
18
19        response.setContentType("text/html");
20        PrintWriter out = response.getWriter();
21        out.println("request.getContextPath() = " + request.getContextPath() + "<BR />");
22        out.println("request.getServletPath() = " + request.getServletPath() + "<BR />");
23        out.println("request.getRequestURI() = " + request.getRequestURI() + "<BR />");
24        out.println("request.getRequestURL() = " + request.getRequestURL() + "<BR />");
25        HttpSession session = request.getSession();
26        String realPath = session.getServletContext().getRealPath("/");
27        out.println("request.getRealPath(\"/\") = " + realPath + "");
28        out.flush();
29        out.close();
30    }

31
32    public void doPost(HttpServletRequest request, HttpServletResponse response)
33            throws ServletException, IOException {
34        doGet(request, response);
35    }

36
37}

返回结果:

request.getContextPath() = /TestProject
request.getServletPath() = /servlet/TestPath
request.getRequestURI() = /TestProject/servlet/TestPath
request.getRequestURL() = http://localhost:8080/TestProject/servlet/TestPath
request.getRealPath("/") = C:\Tomcat\webapps\TestProject\


这样就一目了然了,另外要特别说下getRealPath()这个方法,用于得到URL的物理磁盘路径,以前的写法很简单request.getRealPath(String path)即可。但是此方法已被废弃。现在要用ServletContext.getRealPath(String path)。也就是说要先得到ServletContext对象,而这个对象获得方式有好几种,比较简单的无非是从Session中获得:

HttpSession session = request.getSession();
String realPath = session.getServletContext().getRealPath("/");

还有几种方法同样可以获得ServletContext:

Javax.servlet.http.HttpSession.getServletContext()
Javax.servlet.jsp.PageContext.getServletContext()
Javax.servlet.ServletConfig.getServletContext()


以上。

参考资料:
http://hi.baidu.com/fytcm/blog/item/298975d7e796aedaa044df0a.html
http://hi.baidu.com/javagt/blog/item/6b7a68f4ebc3b3d8f2d385e3.html
http://www.blogjava.net/flysky19/articles/98006.html
http://bbs.chinaunix.net/viewthread.php?tid=383861

posted @ 2008-12-11 09:23 Viva Hu 阅读(1831) | 评论 (1)编辑 收藏

2008年11月30日 #

Apache + PHP + MySQL 安装过程中的注意事项

最近要和13一起做一个PHP的宠物展示网站,于是才会想起来去配PHP环境,网上搜搜,按照下面的文章配了一遍,有些收获:
http://tech.163.com/06/0206/11/299AMBLT0009159K.html

以下为配置过程中原文中忽略掉的注意事项。

一、Apache的端口修改
在Apache的配置文件conf/httpd.conf里搜索“Listen ”,后面的数字就是端口了。如果是按照服务模式装的,默认应该是80,按照应用模式装的,那默认是8080,因为我电脑上80跑的IIS,8080跑的RESIN,所以我把Apache改成90了。

二、Apache安装为服务
CMD中进入Apache安装目录下的bin目录,然后执行apache -k install回车即可,其他一些参数如下:
安装为特定的服务名:
apache -k install -n "服务名"
安装一个使用特定配置的服务,安装时指定配置文件:
apache -k install -n "服务名" -f "\my server\conf\my.conf"
移除一个Apache服务
apache -k uninstall -n "服务名"

三、发布目录的配置
Apache的httpd.conf文件里有关DocumentRoot的配置是关于Apache发布目录的,默认是指向Apache安装目录下的htdocs目录,修改后的目录绝不可包括空格,我之前把发布目录放在“我的文档”下面的一个文件夹里,结果“我的文档”的实际目录是F:\My Document\,导致路径中有一个空格,访问不了发布目录。

四、Apache加载PHP模块的配置
在配置Apache加载PHP模块时,除了加入
LoadModule php5_module C:/PHP/php5apache2.dll
这一句以外还要记得在下面加入
PHPIniDir "C:/PHP"
这句,否则就必须把php.ini文件复制到Windows目录下。

PS. 其实如果配过IIS+PHP的就很好理解了,PHP相当于一个ISAPI层,无论是IIS还是Apache都是把PHP作为一个ISAPI解析或者当作一个模块加入到自己里面,所以因为IIS没有加载PHP模块的概念,所以IIS+PHP是加载的php5isapi.dll文件作为ISAPI加入。

五、PHP的ext *.dll文件
很多教程要求把什么PHP目录以及PHP/ext目录下下所有*.dll复制到Windows/System32目录下才可使用,这其实是一种偷懒的办法,因为正确的方法应该是如原文中所说的一样,将PHP以及PHP/ext目录加入系统PATH路径中,其实就是让系统能找到这些dll文件放在哪里而已,我很不喜欢把*.dll放到System32目录,还有把php.ini复制到Windows目录下的这种方式,我认为PHP作为一个独立的模块就应该独立的存在。但是切记修改了系统PATH路径后一定要重新启动才能生效,而把*.dll复制到System32目录下由于System32目录本身就在系统PATH路径里,所以无需重新启动电脑,这就是为什么我刚说这种复制DLL文件的方法其实是偷懒。
要指定extension_dir的路径,"绝不可以"在目录结尾再加一个“/”,会导致无法访问发布目录,我就犯了这个错,为此还从头重做了一遍。
extension_dir = "./" 默认
extension_dir = "C:/PHP/ext"  正确
extension_dir = "C:/PHP/ext/" 错误

六、测试Apache加载PHP成功与否的代码
以下代码可以将PHP的一些信息用HTML的形式显示出来
1<?
2 phpinfo();
3?>

七、测试PHP连接MySQL成功与否的代码
以下代码可以将MySQL的用户表用HTML的形式显示出来,当然,用户名密码得根据实际情况来改,默认用户名为root,密码为空
 1<?PHP
 2 //---基本设定------
 3 $mysql_server_name = "localhost";
 4 $mysql_username    = "root";
 5 $mysql_password    = "";
 6 $mysql_database    = "mysql";
 7 //----------------
 8 $sql    = "select * from user";
 9 $conn   = mysql_connect($mysql_server_name, $mysql_username, $mysql_password);
10 $result = mysql_db_query($mysql_database, $sql, $conn);
11 $row    = mysql_fetch_row($result);
12
13 //表格开始
14 echo "<table border=1 cellspacing=0 cellpading=0>\n";
15 
16 //打印出栏位名称
17 echo "<tr>\n";
18 for ($i=0$i<mysql_num_fields($result); $i++) {
19    echo "<td nowrap>".mysql_field_name($result, $i)."</td>\n";
20 }
21 echo "</tr>\n";
22 
23 //将资料移动回第一笔
24 mysql_data_seek($result, 0);
25 
26 //印出资料内容
27 while($row=mysql_fetch_row($result)) {
28    echo "<tr>\n";
29     for ($i=0$i<mysql_num_fields($result); $i++)
30     {
31         echo "<td nowrap>$row[$i]</td>\n";
32     }
33     echo "</tr>\n";
34 }
35 
36 //表格结束
37 echo "</table>\n";
38 
39 mysql_free_result($result);
40?>

posted @ 2008-11-30 23:20 Viva Hu 阅读(388) | 评论 (0)编辑 收藏

2008年11月10日 #

[From LDH]两种JSP页面include用法的区别

     摘要: 最近做華為箱單系統又有新需求,拿出一年前的代碼時,正好遇到了這個問題,想起7thgen上有LDH大師的一篇絕佳文章,轉載如下。  阅读全文

posted @ 2008-11-10 17:22 Viva Hu 阅读(880) | 评论 (0)编辑 收藏

远程重启XP

公司弄了一台新臺式機,老臺式機放在一邊遠程登錄用,結果遠程登錄發現老機器沒有重新啓動選項。開始以爲是遠程登錄客戶端版本有問題,換了Vista的遠程登錄現象依舊。於是去MSDN上搜索了一下:

引自:http://blogs.msdn.com/helloworld/archive/2007/11/23/remotely-restarting-windows-xp.aspx

Remotely restarting Windows XP

If you are using Remote Desktop quite a lot, you may need to restart your XP machine remotely, but there is no option to restart or shutdown the machine. The only options available are Log Off and Disconnect.

To restart or to reboot XP machines remotely, use 'shutdown' command from the command console.

Run cmd.exe, and type 'shutdown -r -t 0' to restart the machine.

大致翻譯:

如果你經常使用遠程桌面,你可能需要遠程重新啓動你的XP機器,但是卻發現開始菜單裏根本沒有“重新啓動”或者“關機”選項。只有“註銷”和“斷開遠程連接”。
如果要遠程重啓XP機器,你必須在命令行控制臺中使用“shutdown”命令。方法如下:
運行cmd.exe,鍵入“shutdown -r -t 0”即可重啓XP。

命令解釋:
shuntdown是Windows自帶的関機命令,-r參數表示Reboot重新啓動,如果不加這個參數則執行関機操作,-t [0-n]參數表示Time等待[0-n]秒時間,0表示不等待立即執行。你甚至可以把這條命令保存成bat文件放在桌面上,一個用來重啓,一個用來関機(雖然遠程登錄時基本永不到関機功能)。

其實這篇文章後面的用戶評論更精彩:

- That's not true. You can Alt-F4 from the desktop to bring up the "Turn Off Computer" options, which allows you to restart. You can also restart via Task Manager.
你可以直接在桌面上按Alt+F4調出“關閉計算機”選項,裏面有“重啓電腦”的選項,你也可以通過任務管理器重啓。

- Can't you just do ctrl-alt-end and choose restart? that's what i've always done.
難道你不能按Ctrl+Alt+End調出菜單來重新啓動嗎?我經常這麽干呢。lol

- You just have to find "Windows Security" on the Start Menu, which give you the Ctrl-Alt-Del screen. Or it will just bring up the Task Manager, which also has all the standard shutdown/restart options.
你只要找到開始菜單裏的“Windows安全”,可以找到一個Ctrl+Alt+Del界面。或者能幫你打開任務管理其,你同樣也可以找到標準的関機/重啓選項。

最後,我事後也想到了一個方法,只適用于XP以及XP以上版本的Windows,Win2K不支持:
開始菜單 - 運行 - msconfig回車 - 在“啓動”選項卡裏隨便改點東西,點確定按鈕,即可跳出一個對話框問你“是否立即重新啓動?”,大功告成。Win2K不自帶msconfig.exe這個管理程序,除非從XP裏複製一個過去用。

人民的智慧是偉大的。lol

posted @ 2008-11-10 09:10 Viva Hu 阅读(692) | 评论 (0)编辑 收藏

仅列出标题