Chapter 5 Built-in object : resopnse

 

  You can operate server response use this object, example set HTTP head attribute.

 

 

5.1 Redirect

You can add link into web page, then user can click the link to visit other page. But this operate need user click link, but sometimes we hope at server side can automatically guide (redirect) client to another page. For example, online examinations, system will automatically jump terminal page when examination concluded. The “sendRedirect” method can do it.

 

public void sendRedirect(String url) throws IOException

Sends a temporary redirect response to the client using the specified redirect location URL. The URL can be absolute (for example, https://hostname/path/file.html) or relative(for example, ../path/file.html). Only enable buffer function then can use this method. And behind this method must follow “return” syntax.

Parameters: url- the redirect location URL

Throws: IOException - If an I/O error has occurred.

 

  For example “redirect.dqm”, source code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<%@page buffer="true" import="java.util.Random"%>

<%

String yahoo = "http://www.yahoo.com";

String sun = "http://www.sun.com";

 

Random rdom = new Random();

int rs = rdom.nextInt(10);

if (rs >=5) {

  response.sendRedirect(yahoo);return;

}

else {

  response.sendRedirect(sun);return;

}

%>

 

Visit this dqm file, maybe will open “yahoo” homepage, maybe will open “sun” homepage. If random number larger than five then redirect to “yahoo” website(source code line: 8 to 10), else redirect to “sun” website(source code line: 11 to 13).

 

Behind “sendRedirect” method must follow “return” syntax, so sometimes will happen status of unreachable statement. Example below source code, the unreachable statement at line 2.

1

2

response.sendRedirect(yahoo);return;

out.print("hello");

 

Please change code to:

1

2

3

4

f (true) {

response.sendRedirect(yahoo);return;

}

out.print("hello");

 

The compiler will check the dynamic document, if behind “sendRedirect” method not follow “return” syntax then will prompt error information. But if “sendRedirect” method in a bean, and use this bean to redirect, then compiler can’t check it. So please don’t forget add “return” too.

For example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

<%@page buffer="true" import="java.util.Random"%>

<%

String yahoo = "http://www.yahoo.com";

String sun = "http://www.sun.com";

 

Random rdom = new Random();

int rs = rdom.nextInt(10);

if (rs >=5) {

  myRedirect(response, yahoo);return;

}

else {

  myRedirect(response, sun);return;

}%><%!

private void myRedirect(DResponseItface response, String url) throws IOException {

  response.sendRedirect(url);

}

%>

 

That “sendRedirect” method writed in declaration(source code line: 13 to 17). To add a declaration, you must use the <%! and %> sequences to enclose your declarations. So at source code line 9 and 12, if not add “return” then compiler also not prompt any errors. But please don’t forget add “return” too.

 

 

5.2 Set HTTP head’s attribute

Http content inclue “http head” and “http body”. Http head can define some parameters of transmit, so you can add or modify some parameters to enable some special function.

 

1. public void setHeader(String name, String value,String charsetName) throws IOException

Adds a field to the response header with the given name and value(using the specified charset encoding this value). If the field had already been set, the new value overwrites the previous one. The containsHeader method can be used to test for the presence of a header before setting its value. Only enable buffer function then can use this method.

Parameters: name - the name of the header field.

value - the header field's value.

charsetName - the name of a supported charset, for example BIG-5, UTF-8, GBK… Use it to encoding “value” parameter’s value.

Throws: If happen problem when add a field to the response header then this method will throws IOExeption.

 

2. public void setHeader(String name, String value) throws IOException

Adds a field to the response header with the given name and value(using default charset encoding this value, the default charset is set by “webconfig.xml->systemSet->dataEnc”, please refer to section 2.1). If the field had already been set, the new value overwrites the previous one. The containsHeader method can be used to test for the presence of a header before setting its value. Only enable buffer function then can use this method.

Parameters: name - the name of the header field.

value - the header field's value.

Throws: If happen problem when add a field to the response header then this method will throws IOExeption.

 

But what can we do use this method? Ok for example, when users visit a website, we do not want to allow users to directly see the results in browser, but want to download it, so we can add a new http head to achieves the goal. The dqm file “httphead.dqm”, souce code:

1

2

 

3

4

5

6

<%@page buffer="true"%>

<%response.setHeader("Content-Disposition", "attachment;filename=http_compression.txt");%>

 

Why Compress?

 

Most user's knowledge of compression is from compressing a group of files that they download, extract, and open. But compression can also be used passively to compress documents as they are being transferred to a client's browser. Because it's a passive process, the server can reduce the size of the pages sent, therefore reducing the download time for users and their bandwidth usage.

 

The browser will prompt to download "http_compression.txt” file when you visiting this dqm file. Not to directly show content in the browser. You can try to delete source code line 2, then visit this dqm file again, then you will find the content was directly shown in browser. You can seen we add a new http head “Content-Disposition” to achieves the goal, this http head’s value is “attachment;filename=http_compression.txt”, the “http_compression.txt” is download file’s name.

Section F2.3 will introduce how use “http head” to output international content.

 

 

5.3 Setup ContentType

Section 3.2 introduced that page directive can define MIME type, now response object can define it too.

 

public void setContentType(String contentType)

Sets the content type for this response. This type may later be implicitly modified by addition of properties such as the MIME charset=<value> if the service finds it necessary, and the appropriate media type property has not been set. If use this method many times then the last set is available. Only enable buffer function then can use this method.

Parameters: contentType - the content's MIME type.

 

Notice: There is a greate difference between “contenttype” attribute of page directive and current method is that current method can use String variable, “contenttype” attribute can’t use variable.

 

 

5.4 Method of encodeURL

Because session function is base on cookie function(session function please refer to chapter 8), so if browser disable cookie then session also expired. Even browse disable cookie function that session function will normal when use “encodeURL” method. The basic principle is that if the browser does not support cookie function then this method will rewrite the request URL, add session information to request URL.

 

public String encodeURL(String url)

Encodes the specified URL by including the session ID in it, or, if encoding is not needed, returns the URL unchanged. The implementation of this method should include the logic to determine whether the session ID needs to be encoded in the URL. For example, if the browser supports cookies, or session tracking is turned off, URL encoding is unnecessary.

Parameters: the url to be encoded.

Returns: the encoded URL if encoding is needed; the unchanged URL otherwise.

 

This method first will check the current dqm file whether enable session function(How to enable or disable session function please refer to section 3.2). If disabled session function then this method will return the URL unchanged.

 

Foe example, a URL before revision: <a herf="yourfile.dqm">

After uses the “encodeURL” method to revise:

<a herf="<%=response.encodeURL("yourfile.dqm")%>">

When the browser does not support cookies, the URL will be automatically revised to “yourfile.dqm? DQMSESSIONID=XXX”, the “XXX” represents sessionID.

 

Notice: When cookie is not available, this method will automatically add sessionID to URL, sessionID parameter name is "DQMSESSIONID", it’s a reservation name, so please don’t use this name to transmit parameter or data.

 

 

5.5 Using cookie

HTTP cookies are used by Web servers to differentiate users and to maintain data related to the user during navigation, possibly across multiple visits. Using cookie that server can save some data into client, and server can read these data when client visit again.

Use cookie can do some special features, such as when user first visit may inquire the visitor name, then save the visitor name to user's browser. On next time this user visit again, server can take visitor's name from the browser, ok now you can use visitor's name to say hello.

 

1.       public void addCookie(DCookie cookie)

Adds the specified cookie to the response. It can be called multiple times to set more than one cookie.

Parameters: the Cookie to return to the client

 

And how to use it and how to create DCookie we will introduce at chapter 7.

 

 

 

5.6 Insert static document

In section 3.2 we introduced “include” directive, here we will also introduce “includeFile” method. But these two usages also have the difference. Use “include” directive to insert a document, if this document’s content has fragments of java program, then it’s java program will executed too. And ths method will check the document which inserts always, the dqm file that use “include” directive will be recompiled automatically if it changes.

The “includeFile” method don’t check the document which inserts, the dqm file that use “includeFile” method will not be recompiled automatically if it changes. This method only for insert static document, the document content which inserts will be output intact.

 

1.       public void includeFile(String fileName) throws java.io.IOException

To insert a static document, it’s content will be output to client intact.

Parameters: filename – static document file name of need to insert. It can use relative path or absolute path. Relative path is relative to the current dqm file's path. For example: “../xxx.txt”, “test/xxx.txt”. Absolute path’s example is “c:\\xxx.txt”, “/xxx.txt”.

Throws: If happen problem when output then this method will throws IOExeption.

 

 

For example, a dqm file name is “includeFile.dqm”, source code:

1

2

3

4

5

<pre>

Below is in the includeFile.txt document's content-----------------------------

<%response.includeFile("includeFile.txt");%>

Above is in the includeFile.txt document's content-----------------------------

</pre>

 

Output result:

Below is in the includeFile.txt document's content-----------------------------

  The Sherlock Holmes Journal is published twice a year, usually in July and December. It is the official voice of the Society and contains its Transactions, news and reviews, letters and editorial notes. It is also home to the most erudite scholarship, publishing learned articles from Holmesians world-wide who have something to say on any aspect of Sherlock Holmes and his world. It has been appearing without a break since the first issue in May 1952.

  The most recent issue, Vol 28 No 2 Summer 2007, contains the following articles, as well as the usual notes, reviews and letters

Above is in the includeFile.txt document's content-----------------------------

 

We can seen from result that dqm file output “includeFile.txt” document’s content intact(at source code line 3).

 

Notice: From the above example you can seen that use relative path(at source code line 3).

The “includeFile.txt” file and “includeFile.dqm” file in the same directory.

 

 

5.7 Option output

In the BBS web application maybe happen this situation, the user can upload files to BBS, But downloads these files need some conditions, for example condition of user already sign in BBS. Then how to achieve this function? Of course we can use “out” method to code this program(use “out” method to do it please refer to section 4.2 and section 4.5). But code this program is not easy, if you want to support resume download then it’s a not small program. If you want to fully comply with the HTTP protocol then it will become a big project. So what better way? Next we will introduce “outBinFile” method.

 

1.       public void outBinFile(File out_bin_file) throws IOException

Output the file to client.. Only enable buffer function then can use this method. And behind this method must follow “return” syntax.

Parameters: out_bin_file – the file need to be output.

Throws: If happen problem when output then this method will throws IOExeption.

 

First example, dqm file “outputfile.dqm”, it can output a file to client. If request url has a “type” parameter and it’s value is “download”, then can download file, other status will prompt can’t to download file. Source code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

<%@ page buffer="true"%>

 

<html>

 

<head>

<meta http-equiv="Content-Language" content="zh-cn">

<meta http-equiv="Content-Type" content="text/html; charset=gb2312">

<title>Download Page</title>

</head>

 

<body>

 

<%

String type = request.getParameter("type");

 

if ("download".equals(type)) { //can download file

  File downFile = new File("c:\\kgweb.rar");

  if (downFile.exists()) {

    response.outBinFile(downFile);

    return;

  }

}

%>

 

<p align="center"><b><font color="#FF0000">Sorry, can not download!</font></b></p>

 

</body>

 

</html>

 

You can seen from source code line 16, if “type” parameter’s value is “download” then output the specified file(At source code line:17). Here we specified the output file is “c:\kgweb.rar”, reader please change it when you test this program.

 

Notice: If use relative path at soure code line 17, for example chang it to File downFile = new File("kgweb.rar"), that mean the “kgweb.rar” file was located at kangaroo-egg installed folder(please refer to section 1.2). And please check the file is existed berfor output it (source code line 18).

 

When we use above parameter to visit “output.dqm”, then the browser will prompts the user to download files. Please refer to picuter 5-7-1.

Picture 5-7-1

 

Seen picture 5-7-1 that URL has “type” parameter and it’s value is “download”, so that browser was prompted the user to download file. But notice that file name of need to download is “outputfile.dqm”, don’t worry, we will introduce how to change it later. Other we can seen that downloading file size is 40.2M, because c:\kgweb.rar file size is 40.2M.

You can use the URL (in picture 5-7-1) to test resume download, the results you will not be disappointed. This method not only support resume download, and all of the HTTP protocol specification transmission function will complete support, example ff the client requests has “if-modified-since” head tag, then it will be based on conditions to output the request document or output HTTP304 information.

If the visit URL hasn’t parameter or the file of need to output dosen’t exist , then program will promptthe file can’t be downloaded (source code line 25, and see picture 5-7-2).

Picture 5-7-2

 

Reference to the above example we can achieve different option output.

 

Next we have to solve the output filename problem, “response” object has another “outBinFile” method, use this method you can specify output file name

 

2.       public void outBinFile(File out_bin_file, String saveAsNameStr) throws IOException

Output the file to client, and use default charset to reset output file’s name. The default charset is set by “webconfig.xml->systemSet->dataEnc”, please refer to section 2.1. Only enable buffer function then can use this method. And behind this method must follow “return” syntax.

Parameters: out_bin_file – the file need to be output.

saveAsNameStr – Output file’s name of reset by default charset.

Throws: If happen problem when output then this method will throws IOExeption.

 

 

3.       public void outBinFile(File out_bin_file, String saveAsNameStr, String charsetName) throws IOException

Output the file to client, and use specified charset to reset output file’s name. Only enable buffer function then can use this method. And behind this method must follow “return” syntax.

Parameters: out_bin_file – the file need to be output.

saveAsNameStr – Output file’s name of reset by default charset.

charsetName - specified charset name, the name of a supported charset, for example BIG-5, UTF-8, GBK…

Throws: If happen problem when output then this method will throws IOExeption.

 

 

The principle of above No.2 method please refer to No.2 method of section 5.2. The principle of above No.3 method please refer to No.1 method of section 5.2.

 

  So we changed “outputfile.dqm” file source code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

<%@ page buffer="true"%>

 

<html>

 

<head>

<meta http-equiv="Content-Language" content="zh-cn">

<meta http-equiv="Content-Type" content="text/html; charset=gb2312">

<title>Download Page</title>

</head>

 

<body>

 

<%

String type = request.getParameter("type");

 

if ("download".equals(type)) { //can download file

  File downFile = new File("c:\\kgweb.rar");

  if (downFile.exists()) {

    response.outBinFile(downFile, downFile.getName(), "GBK");

    return;

  }

}

%>

 

<p align="center"><b><font color="#FF0000">Sorry, can not download!</font></b></p>

 

</body>

 

</html>

 

Again visit this dqm file with parameter you will see download file’s name has been changed. Please refer to picuter 5-7-3.

Picture 5-7-3

 

Behind “outBinFile” method must follow “return” syntax, so sometimes will happen status of unreachable statement. Example below source code, the unreachable statement at line 2.

1

2

response.outBinFile(new File("c:\\kgweb.rar"));return;

out.print("hello");

 

Please change code to:

1

2

3

4

f (true) {

response.outBinFile(new File("c:\\kgweb.rar"));return;

}

out.print("hello");

 

The compiler will check the dynamic document, if behind “outBinFile” method not follow “return” syntax then will prompt error information. But if “outBinFile” method in a bean, and use this bean to option output file, then compiler can’t check it. So please don’t forget add “return” too. For example:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

<%@ page buffer="true"%>

 

<html>

 

<head>

<meta http-equiv="Content-Language" content="zh-cn">

<meta http-equiv="Content-Type" content="text/html; charset=gb2312">

<title>Download Page</title>

</head>

 

<body>

 

<%

String type = request.getParameter("type");

 

if ("download".equals(type)) { //can download file

  File downFile = new File("c:\\kgweb.rar");

  if (downFile.exists()) {

    myOutBinFile(response, downFile); return;

  }

}

%>

 

<p align="center"><b><font color="#FF0000">Sorry, can not download!</font></b></p>

 

</body>

 

</html>

<%!

private void myOutBinFile(DResponseItface response, File outFile) throws IOException {

  response.outBinFile(outFile);

}

%>

 

That “outBinFile” method writed in declaration(source code line: 30 to 33). So at source code line 19, if not add “return” then compiler also not prompt any errors. But please don’t forget add “return” too.