Servlet传值总结
1) redirect方式[效率不高] 客户端跳转,不能跳到WEB_INF下
request和response没有传给目标页面
response.sendRedirect("/a.jsp");
页面的路径是相对路径。sendRedirect可以将页面跳转到任何页面,不一定局限于本web应用中,如:
response.sendRedirect("URL");跳转后浏览器地址栏变化。
这种方式要传值出去的话,只能在url中带parameter或者放在session中,无法使用request.setAttribute来传递。
传值:HttpSession session =request.getSession();
session.setAttribute("bbbb", 1111111111);
取值:session.getAttribute("bbbb");
传值:RequestDispatcher rd =application.getRequestDispatcher("/queryResult.jsp?a="+000);
取值:request.getParameter("a")
2) forward方式[更多地使用此方法进行服务器端的跳转] 服务器跳转
ServletContext application =this.getServletContext(); //this是这个页面
RequestDispatcher rd =
application.getRequestDispatcher("/目标页面");
rd.forward(request, response);
Servlet页面跳转的路径是相对路径。forward方式只能跳转到本web应用中的页面上,跳转后浏览器地址栏不会变化。
使用这种方式跳转,传值可以使用三种方法:url中带parameter,session,request.setAttribute
传值:request.setAttribute("a", 00);
取值:request.getAttribute("a");
传值:HttpSession session =request.getSession();
session.setAttribute("bbbb", 1111111111);
取值:session.getAttribute("bbbb");
传值:RequestDispatcher rd =application.getRequestDispatcher("/queryResult.jsp?a="+000);
取值:request.getParameter("a");
getParameter只能传递字符串setAttribute/getAttribute可以传递对象
其次getParameter方法传递的数据,会从Web客户端传到Web服务器端,代表HTTP请求数据。
只能是页面发送到后台或者Web客户端传到Web服务器端
=======================================================================
servlet 和 jsp 跳转页面的几种方法
跳转分两部分:
一是发生在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;
}
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.sql
USE [abc]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[userinfo](
[uname] [varchar](50) NOT NULL,
[ps] [varchar](50) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO