3.3 response对象

response对象,表示一次http的应答。 可能是直接应答一个页面,也可以应答若干个字符,这些字符可以是xml格式,也是可以json格式等等。
1.直接应答一个页面,效果就是网页跳转到别的页面 
修改一下上一节的页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<%
String p=request.getParameter( "pp" );
String p1=request.getParameter( "pa" );
System.out.println(p1);
out.println( "<style>" );
out.println( "p{font-weight:bold;color:blue;}" );
out.println( "</style>" );
%>
</head>
<body>
<
out.println( "<p>" );
out.println("URL里面的pp参数的值是:"+p);
out.println( "你好,世界" );
out.println( "</p>" );
if(p.equals("abc")){
 response.sendRedirect( "p2.jsp" );
}
%>
<a href="?pp=我是测试&pa=aaabbc">pp参数为空,点击这里</a>
</body>
</html>
27行代码增加了一个条件判断,假如参数pp的值是abc,那么跳转到页面p2.jsp。
我们创建一个p2.jsp,检验一下是否会跳转:
p2.jsp的内容随便写就可以了。
测试的时候,当URL的参数pp的值是abc的时候,就会跳转到p2.jsp

2.应答一个json格式的字符串
设置UTF-8是为了支持应答中包含中文,setContentType("application/json; charset=utf-8");指定了应答的格式,是json,最后是应答内容。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
response.setCharacterEncoding( "UTF-8" ); 
response.setContentType( "application/json; charset=utf-8" ); 
response.getWriter().print( "{'abc':'123'}" );
%>
3.应答一个xml格式的字符串:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<% 
response.setCharacterEncoding( "UTF-8" ); 
response.setContentType( "text/xml" ); 
response.getWriter().print( "第一章" );
%>