在servlet 内实现跳转

我们实现 一个案例 :

     在  query.jsp 中输入学生的名字,在数据库中查询,查询结果在  queryResult.jsp 中显示。

 Servlet是控制者,作用是处理来自 JSP 页面的输入并从  JAVA BEAN中读取来自数据库的数据,再跳转到目标页面

一。使用response对象实现 跳转

1.query.jsp 

 <b>查询学生数据库</b>
    <form action="/proj4/servlet/QueryServlet"  method ="post">
    请输入学生的帐号:<input type ="text"  name ="account">
    <input  type ="submit"  value="查询">
    </form>

2. queryResult.jsp

 查询的关键字为:<%=session.getAttribute("account") %>

3.  QueryServlet.java 

public class QueryServlet extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("gb2312");
		String account= request.getParameter("account");
		//数据库查询
		request.getSession().setAttribute("account", account);
		response.sendRedirect("/proj4/queryResult.jsp");
	}

}

将数据放入  session ,只有这样 ,在下一个页面中才能访问到。

request.getAttribute()方法返回request范围内存在的对象,而request.getParameter()方法是获取http提交过来的数据。


二。使用forward方法实现跳转

只用更改servlet中的代码 

//数据库查询
		request.getSession().setAttribute("account", account);
		ServletContext application = this.getServletContext();
		RequestDispatcher rd = application.getRequestDispatcher("/queryResult.jsp");
		rd.forward(request, response);

前面 讲过,在  forward跳转中,可以保持 request中的值,而 redirect方法中不行。因此 ,我们这里还可以改成

request.setAttribute("account",account);

同时 ,在 queryResult.jsp中的代码 要改

<%=request.getAttribute("account")%>

问题,在 Servlet中,什么时候 用 redirect跳转,什么时候用 forward方法跳转。

当从页面A到  B,如果 存在大量的暂时的数据 (也就是在B显示后就不再会用到的),那么 ,为了节省 内存,我们用forward 跳转,可以避免将很多

内容 存在session 中,而导致服务 器内存过大,因为session 是在服务 器上的。






转载于:https://my.oschina.net/chuiyuan/blog/282541

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
/* * Copyright (c) 2000 David Flanagan. All rights reserved. * This code is from the book Java Examples in a Nutshell, 2nd Edition. * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied. * You may study, use, and modify it for any non-commercial purpose. * You may distribute it non-commercially as long as you retain this notice. * For a commercial use license, or to purchase the book (recommended), * visit http://www.davidflanagan.com/javaexamples2. */ package com.hexiang.examples.servlet; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; import java.io.*; /** * This class demonstrates how JDBC can be used within a servlet. It uses * initialization parameters (which come from the web.xml configuration file) * to create a single JDBC database connection, which is shared by all clients * of the servlet. ***/ public class Query extends HttpServlet { private static final long serialVersionUID = -5616899811848789885L; Connection db; // This is the shared JDBC database connection public void init() throws ServletException { // Read initialization parameters from the web.xml file ServletConfig config = getServletConfig(); String driverClassName = config.getInitParameter("driverClassName"); String url = config.getInitParameter("url"); String username = config.getInitParameter("username"); String password = config.getInitParameter("password"); // Use those init params to establish a connection to the database // If anything goes wrong, log it, wrap the exception and re-throw it try { Class.forName(driverClassName); db = DriverManager.getConnection(url, username, password); } catch (Exception e) { log("Can't create DB connection", e); throw new ServletException("Query: can't initialize: " + e.getMessage(), e); } } /** Close the database connection when the servlet is unloaded */ public void destroy() { try { db.close(); } // Try to close the connection catch (SQLException e) {} // Ignore errors; at least we tried! } public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); // We're outputting HTML PrintWriter out = response.getWriter(); // Where to output it to // Output document header and a form for entering SQL queries // When the form is submitted, this servlet is reloaded out.println("<head><title>DB Query</title></head>\n" + "<body bgcolor=white><h1>DB Query</h1>\n" + "<form><b>Query: </b><input name='q'>" + "<input type=submit></form>"); // See if a query was specified in this request. String query = request.getParameter("q"); if (query != null) { // display the query text as a page heading out.println("<h1>" + query + "</h1>"); // Now try to execute the query and display the results in a table Statement statement = null; // An object to execute the query try { // Create a statement to use statement = db.createStatement(); // Use it to execute the specified query, and get result set ResultSet results = statement.executeQuery(query); // Ask for extra information about the results ResultSetMetaData metadata = results.getMetaData(); // How many columns are there in the results? int numcols = metadata.getColumnCount(); // Begin a table, and output a header row of column names out.println("<table border=2><tr>"); for(int i = 0; i < numcols; i++) out.print("<th>" + metadata.getColumnLabel(i+1) + "</th>"); out.println("</tr>"); // Now loop through the "rows" of the result set while(results.next()) { // For each row, display the the values for each column out.print("<tr>"); for(int i = 0; i < numcols; i++) out.print("<td>" + results.getObject(i+1) + "</td>"); out.println("</tr>"); } out.println("</table>"); // end the table } catch (SQLException e) { // If anything goes wrong (usually a SQL error) display the // error to the user so they can correct it. out.println("SQL Error: " + e.getMessage()); } finally { // Whatever happens, always close the Statement object try { statement.close(); } catch(Exception e) {} } } // Now, display the number of hits on this page by invoking the // Counter servlet and including its output in this page. // This is done with a RequestDispatcher object. RequestDispatcher dispatcher = request.getRequestDispatcher("/servlet/counter"); if (dispatcher != null) { out.println("<br>Page hits:"); // Add a request attribute that tells the servlet what to count. // Use the attribute name defined by the Counter servlet, and // use the name of this class as a unique counter name. request.setAttribute(Counter.ATTRIBUTE_NAME,Query.class.getName()); // Tell the dispatcher to invoke its servlet and include the output dispatcher.include(request, response); } // Finally, end the HTML output out.println("</body>"); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值