servlet jsp之间跳转的方法与两者之间的乱码问题

jsp页面采用utf-8的编码方式

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>

<script type="text/javascript">

window.onload=function(){
	   //document.getElementById("bg").style.backgroundColor="#F90";
	   //location.href="http://localhost:8081/tomcatTest/HelloServlet"; 
	     alert("<%=basePath%>HelloServlet");
		 alert("<%=basePath%>test.jsp");
         //直接从jsp跳到helloServlet的servlet中
		 location.href = "<%=basePath%>HelloServlet";
	}
</script>

window.onload页面自己调用的函数 不需要人为来进行调用
window.οnlοad=function(

   在这里边直接跳转到servlet中的代码
   location.href = "<%=basePath%>HelloServlet";
)

后天跳转资源的代码

//跳转成功 
response.sendRedirect(basePath+"jsp/test.jsp");
//跳转失败 
request.getRequestDispatcher(basePath+"jsp/test.jsp").forward(request, response);
// 可以跳转
response.sendRedirect(basePath+"LoginServlet");
// 跳转失败
request.getRequestDispatcher(basePath+"LoginServlet").forward(request, response);

关于中文乱码的解决  页面jsp是utf-8的编码

//页面向后台传递参数的时候  参数为中文的时候设置请求编码方式
//获取中文成功不设置编码获取失败
request.setCharacterEncoding("utf-8");  
//获取中文失败的设置 不可取
request.setCharacterEncoding("gbk");



/* 
后台返回给前台的参数是中文的话  返回要设置编码方式的

修改乱码成功  设置为utf-8是不可以的*/
response.setCharacterEncoding("gbk");

关于表单体提交servlet的代码

<form   action="<%=basePath%>LoginServlet"  method="post"   name="form1">
               用户名:<input type="text" name="userName" >
              密码:<input type="password" name="password">
       <input type="submit"  value="提交">
</form>

 alert("<%=basePath%>HelloServlet");  的结果

 alert("<%=basePath%>test.jsp");的结果

http://localhost:8081/tomcatTest/LoginServlet  相当于action="<%=basePath%>LoginServlet"  两者等价

为什么  request.getRequestDispatcher(basePath+"jsp/test.jsp").forward(request, response);在跳转的时候就无法跳转成功啊

而response.sendRedirect(basePath+"jsp/test.jsp");就跳转失败了呢

 

---------------------------------------------------------------------------------------------------------------------

还是觉得可以跳转,所以就又试了下  以相对路径访问时就可以跳转的

/*
   这样就可以跳转了  
*/
request.getRequestDispatcher("LoginServlet").forward(request, response);
request.getRequestDispatcher("jsp/test.jsp").forward(request, response);

不是太明白为啥相对路径就可以跳转   求大神解释  目录层次如下

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值