Servlet, JSP jump (pass value) summary and URL pass parameter __js

Source: Internet
Author: User
servlet Pass Value Summary 1) Redirect Way[Efficiency is not high] 
Request and response did not pass to the target page 
Response.sendredirect ("/a.jsp"); 
The path to the page is the relative path. Sendredirect can jump to any page, not necessarily limited to this web application, such as: 
Response.sendredirect ("URL"), after the Jump browser address bar changes. 
This way to pass the value out, you can only in the URL with parameter or in the session, can not use Request.setattribute to pass. 
Transfer value: HttpSession session =request.getsession (); 
Session.setattribute ("bbbb", 1111111111); 
Value: Session.getattribute ("bbbb"); 

Pass Value: RequestDispatcher rd =application.getrequestdispatcher ("/queryresult.jsp?a=" +000); 
Value: Request.getparameter ("a") 

2) Forward Way[More use of this method for server-side jumps] 
Servlet Context Application =this.getservletcontext (); This is the page 
RequestDispatcher rd = Application.getrequestdispatcher ("/target page"); 
Rd.forward (request, response); 
The path to a servlet page jump is a relative path. Forward mode can only jump to the page in this Web application, the browser address bar will not change after the jump. 
Use this way to jump, the value can be used in three ways: URL with Parameter,session,request.setattribute 
Transfer value: Request.setattribute ("a", 00); 
Value: Request.getattribute ("a"); 

Transfer value: HttpSession session =request.getsession (); 
Session.setattribute ("bbbb", 1111111111); 
Value: Session.getattribute ("bbbb"); 

Pass Value: RequestDispatcher rd =application.getrequestdispatcher ("/queryresult.jsp?a=" +000); 
Value: Request.getparameter ("a"); 
GetParameter () can only pass strings, while setattribute ()/getattribute () also passes objects 
Second, the data passed by the GetParameter method is uploaded from the Web client to the Web server side, representing the HTTP request data. 
Only the page is sent to the background or the Web client is uploaded to the Web server 

======================================================================= 
several methods for servlet and JSP jump pages


Jumps are divided into two parts:





One is in the servlet, one is in the JSP, in fact, JSP is the servlet, but still a little different drip. Of course, in the servlet, the general jump occurs in Doget, Dopost and other methods.





Servlet:





(1) REDIRECT mode
Response.sendredirect ("/a.jsp");
The path to the page is the relative path.
Sendredirect can jump to any page, not limited to this Web application, such as: Response.sendredirect (http://www.ycul.com);
After the Jump browser address bar changes.
This way to pass the value out, you can only in the URL with parameter or in the session, can not use Request.setattribute to pass.





(2) Forward mode
Request.getrequestdispatcher ("/a.jsp"). Forward (request, response);
Or
Getservletcontext (). Getrequestdispatcher ("/a.jsp"). Forward (request, response);
The path to the page is the relative path.
The forward method can only jump to a page in this Web application.
The browser address bar will not change after the jump.
Use this way to jump, the value can be used in three ways: URL with Parameter,session,request.setattribute





JSP





1) response.sendredirect ();
Same as the Response.sendredirect () method of the servlet.
Out.flush () is not allowed before this statement, and if so, there will be an exception:
Java.lang.IllegalStateException:Can ' t Sendredirect () after data has committed to the client.
At Com.caucho.server.connection.AbstractHttpResponse.sendRedirect (abstracthttpresponse.java:558) ....
Browser address bar changes after jump
If you want to jump to a different host, after the jump, the statement after this statement will continue to execute, as the new thread, but the operation of the response has no meaning;
If you want to jump to the same host, the statement following the statement is completed before you jump





2) Response.setheader ("Location", "");
Out.flush () is not allowed before this statement, and if so, the page will not jump.
Browser address bar changes after jump
The statement after this statement finishes execution before it jumps.



3) <jsp:forward page= ""/>
Out.flush () is not allowed before this statement, and if so, there will be an exception:
Java.lang.IllegalStateException:forward () 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)
The browser address bar does not change after the jump, but can only jump to the current host
The statement after the execution of this statement is completed before it jumps ==============================================================
Example: login.jsp---->loginservlet.java----->userdao.java----->success.jsp
See the following project deployment structure: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" >
<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 are my page" >
<!--
<link rel= "stylesheet" type= "Text/css" href= "Styles.css" >
-->
<body>
<form action= "Loginservlet" method= "POST" >
User name: <input type= "text" name= "uname"/><br/>
Password: <input type= "password" name= "PS"/><br/>
Text field: <textarea rows= "cols=" name= "text" ></textarea><br/>
<input type= "Submit" value= "submitted" >
</form>
</body>
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");

Set Session Scope properties
Request.getsession (). setattribute ("The", "Li");

Set Request Scope properties
Request.setattribute ("n", "Xiao Man");

Userdao user = new Userdao ();

Boolean flag = User.finduser (Username,password);
if (flag) {
The address that needs to be forwarded or sent will be transcoding. This in the target page to better value, lest garbled generation
String url = "Forward/success.jsp?first= passes the first argument &second= passing the second argument"; 
url = new String (url.getbytes ("UTF-8"), "iso8859-1"); 

Client jumps. Only parameters in the session-scoped attribute and URL are passed down
Response.sendredirect (URL);

Server-side jumps. Parameters in the Request object and URL are passed down
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" >
<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 are my page" >
<!--
<link rel= "stylesheet" type= "Text/css" href= "Styles.css" >
-->
<body>
Servlet Login succeeded. <br/><br/>
<!--get the session Range property value set in the Servlet-->
<%= "The attribute value obtained in session" + Session.getattribute ("Chinese")%><br/>
<!--Gets the value of the parameter passed through the URL. and decode it. Otherwise it will be garbled-->
<%= "The first parameter in the URL:" + New String (Request.getparameter ("a") getBytes ("Iso8859-1"), "UTF-8")%>
<br/>
<%= "second parameter in URL:" + New String (Request.getparameter ("second"). GetBytes ("Iso8859-1"), "UTF-8")%>

<br/>
<!--gets the property value of the request set in the servlet. and decode it. Otherwise it will be garbled-->
<%= "The attribute value obtained in Request:" + Request.getattribute ("n")%>
<br/>
<!--get the data submitted by the form. The same needs to be decoded-->
<%=new String (Request.getparameter ("text"). GetBytes ("Iso8859-1"), "UTF-8")%>
</body>
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" >
<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 are my page" >
<!--
<link rel= "stylesheet" type= "Text/css" href= "Styles.css" >
-->
<body>
servlet input error, <a href= "forward/login.jsp" > Please login again </a>
</body>
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;
To connect to the database, query the data in the UserInfo table
1. Connecting to the database
Public Connection Getcon () {
1. Load the database driver: Microsoft developed a database driver jar package, added to the Web-inf/lib directory
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",&

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.