转发特点:
1.只有1次请求
2.地址栏地址不变,显示上个页面的地址
3.请求域内数据不会丢失
重定向特点:
1.有2次或多次请求
2.地址栏地址会变化,显示新页面的地址
3.请求域内数据会丢失,因为是第2次请求
代码示例
<%
String uName = request.getParameter("userName");
String pwd = request.getParameter("pwd");
Connection conn = DBHelper.conn();
PreparedStatement ps = null;
ResultSet rs = null;
String sql = "select * from u_ser where U_name='" + uName
+ "'and pwd='" + pwd + "'";
try {
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
if (rs.next()) {
session.setAttribute("userName", uName);
response.sendRedirect("login2.jsp");//重定向
} else {
request.setAttribute("msg", "账号或密码有误");
request.getRequestDispatcher("index.jsp").forward(request,
response);//转发
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
DBHelper.close(conn, ps, rs);
}
%>