servlet、jsp跳轉(傳值)總結及URL傳參數
跳轉分兩部分:
一是發生在servlet,一是在JSP,其實JSP也就是servlet,不過還是有點差異滴。當然,在servlet中,一般跳轉都發生在doGet, doPost等方法裡面。
Servlet:
(1)redirect 方式response.sendRedirect("/a.jsp");頁面的路徑是相對路徑。sendRedirect可以將頁面跳轉到任何頁面,不局限於本web應用中,如:response.sendRedirect(http://www.ycul.com);跳轉後瀏覽器地址欄變化。這種方式要傳值出去的話,只能在url中帶parameter或者放在session中,無法使用request.setAttribute來傳遞。
(2) forward方式request.getRequestDispatcher("/a.jsp").forward(request, response);或getServletContext().getRequestDispatcher("/a.jsp").forward(request, response);頁面的路徑是相對路徑。forward方式只能跳轉到本web應用中的頁面上。跳轉後瀏覽器地址欄不會變化。使用這種方式跳轉,傳值可以使用三種方法:url中帶parameter,session,request.setAttribute
JSP
1)response.sendRedirect();和servlet的response.sendRedirect()方式一樣。此語句前不允許有out.flush(),如果有,會有異常:java.lang.IllegalStateException: Can"t sendRedirect() after data has committed to the client.at com.caucho.server.connection.AbstractHttpResponse.sendRedirect(AbstractHttpResponse.java:558)....跳轉後瀏覽器地址欄變化如果要跳到不同主機下,跳轉後,此語句後面的語句會繼續執行,如同新開了線程,但是對response的操作已經無意義了;如果要跳到相同主機下,此語句後面的語句執行完成後才會跳轉
2)response.setHeader("Location","");此語句前不允許有out.flush(),如果有,頁面不會跳轉。跳轉後瀏覽器地址欄變化此語句後面的語句執行完成後才會跳轉.
3)<jsp:forward page="" />此語句前不允許有out.flush(),如果有,會有異常:java.lang.IllegalStateException: forward() not allowed after buffer has committed.at com.caucho.server.webapp.RequestDispatcherImpl.forward(RequestDispatcherImpl.java:134)at com.caucho.server.webapp.RequestDispatcherImpl.forward(RequestDispatcherImpl.java:101)at com.caucho.jsp.PageContextImpl.forward(PageContextImpl.java:836)跳轉後瀏覽器地址欄不變,但是只能跳到當前主機下此語句後面的語句執行完成後才會跳轉
==============================================================例題:login.jsp---->LoginServlet.java----->UserDAO.java----->success.jsp請看下面項目部署結構:web.xml:<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>loginservlet</servlet-name> <servlet-class>com.laolu.servlet.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>loginservlet</servlet-name> <url-pattern>/loginservlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app>login.jsp:<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>login.jsp</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="loginservlet" method="post"> 用戶名:<input type="text" name="uname" /><br/> 密碼:<input type="password" name="ps" /><br/> 文本域:<textarea rows="10" cols="30" name="text"></textarea><br/> <input type="submit" value="提交"> </form> </body></html>LoginServlet.java:package com.laolu.servlet;import java.io.UnsupportedEncodingException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.laolu.dao.UserDAO;public class LoginServlet extends HttpServlet{ public void doGet (HttpServletRequest request,HttpServletResponse response){ String name = request.getParameter("uname"); byte[] b; try { b = name.getBytes("iso8859-1"); String username = new String(b,"UTF-8"); String password = request.getParameter("ps"); String text = request.getParameter("text"); //設置session範圍屬性 request.getSession().setAttribute("china", "李靜"); //設置request範圍屬性 request.setAttribute("n", "肖人"); UserDAO user = new UserDAO(); boolean flag = user.findUser(username,password); if(flag){ //將需要轉發或發送的地址進行轉碼操作。這樣在目標頁面更好取值,以免亂碼產生 String url = "forward/success.jsp?first=傳遞第一個參數&second=傳遞第二個參數"; url = new String(url.getBytes("UTF-8"),"ISO8859-1"); //客戶端跳轉。只有session範圍的屬性及url中參數會被傳遞下去 //response.sendRedirect(url); //伺服器端跳轉。request對象、url中的參數會被傳遞下去 request.getRequestDispatcher(url).forward(request, response); }else{ response.sendRedirect("forward/error.jsp"); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public void doPost(HttpServletRequest request,HttpServletResponse response){ doGet(request, response); }}success.jsp:<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>My JSP "login.jsp" starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> servlet登錄成功。<br/><br/> <!-- 取得在servlet中設置的session範圍屬性值 --> <%= "session中取得的屬性值"+ session.getAttribute("china") %><br/> <!-- 取得通過url傳遞的參數的值。並進行解碼。否則會亂碼 --> <%="url中第一個參數:"+ new String(request.getParameter("first").getBytes("ISO8859-1"),"UTF-8") %> <br/> <%="url中第二個參數:"+ new String(request.getParameter("second").getBytes("ISO8859-1"),"UTF-8") %> <br/> <!-- 取得在servlet中設置的request的屬性值。並進行解碼。否則會亂碼 --> <%="request中取得的屬性值:"+ request.getAttribute("n") %> <br/> <!-- 取得表單提交過來的數據。同樣需要進行解碼--> <%=new String(request.getParameter("text").getBytes("ISO8859-1"),"UTF-8") %> </body></html>error.jsp:<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>My JSP "login.jsp" starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> servlet輸入錯誤,<a href="forward/login.jsp">請重新登錄</a> </body></html>UserDAO:package com.laolu.dao;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class UserDAO { Connection conn = null; //去連接資料庫,查詢userInfo表中的數據 //1.連接資料庫 public Connection getCon(){ //1.載入資料庫驅動程序:微軟公司開發的資料庫驅動程序jar包,添加到WEB-INF/lib目錄下 String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; String url = "jdbc:sqlserver://localhost:1433;DataBaseName=abc"; try { Class.forName(driver); try { conn = DriverManager.getConnection(url,"sa","sasa"); System.out.println("資料庫連接成功!"); System.out.println(conn); } catch (SQLException e) { e.printStackTrace(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } //取得資料庫連接對象 return conn; } /** * @通過用戶名和密碼查找用戶 * @param name * @param ps */ public boolean findUser(String name,String ps){ boolean flag = false; conn = this.getCon(); //st對象用於執行sql語句 Statement st; try { st = conn.createStatement(); ResultSet rs = st.executeQuery("select * from userinfo where uname=""+name+"" and ps=""+ps+"""); while (rs.next()) { String uname = rs.getString("uname"); String password = rs.getString("ps"); //System.out.println(uname); return flag=true; } rs.close(); st.close(); conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return flag; }}生成資料庫表的腳本:a.sqlUSE [abc]GO/****** 對象: Table [dbo].[userinfo] 腳本日期: 03/19/2012 14:25:31 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOSET ANSI_PADDING ONGOCREATE TABLE [dbo].[userinfo]( [uname] [varchar](50) NOT NULL, [ps] [varchar](50) NULL) ON [PRIMARY]GOSET ANSI_PADDING OFFGO
推薦閱讀:
※奇門遁甲各類預測的主要參數(即用神)
※從下往上看--新皮層資料的讀後感 第五部分 從自動調參找規律
※攝影中用光原則和PS處理圖象常用手法和一些參數值
※買車前必須了解的汽車參數(一)