例1、向客户端输出中文数据—-创建web project为day06,并创建ResponseDemo1.java
package it.cast.response;
import*;
public class ResponseDemo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)throws Exception {
String data="中国";
OutputStream out=response.getOutputStream();
out.write(data.getBytes("UTF-8"));//这里实际上是写给response的,服务器检测发现response有数据就返回给客户机浏览器显示
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws Exception {
doGet(request, response);
}
}
关联服务器,并启动,在IE中打开:http://localhost:8080/servlet/ResponseDemo1
得到程序运行结果:涓浗 (乱码)
原因:
解决方法:1、在浏览器的查看编码其他选择UTF-8即可(不推荐);
2、在程序中控制浏览以指定的码表打开文件:
//程序以什么码表输出,程序就一定要控制浏览器以什么码表打开
response.setHeader(”Content-type”,”text/html;charset=UTF-8”);
3、用html技术中的meta标签模拟一个http响应头,来控制浏览器的行为:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String data="中国";
OutputStream out=response.getOutputStream();
out.write("<meta http-equiv='content-type' content='text/html;charset=UTF-8'>".getBytes());①
out.write(data.getBytes("UTF-8"));
}
注意:要在IE中打开:http:// http://localhost:8080/day06/servlet/ResponseDemo1
注意事项:1、上面①处如果写成
out.write("<meta http-equiv='content-type'content='text/html,charset=UTF-8'>".getBytes());
浏览器会提示下载!!!
2、如果将doGet写成:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws Exception {
OutputStream out=response.getOutputStream();
out.write(1);
}
在浏览器中显示的是乱码,而不是1.要想看到1的话,应该改为:
out.write((1+””).getBytes());//将1变为字符串
例2、用PrintWriter输出中文字符!ResponseDemo1.java
package it.cast.response;
import.*;
public class ResponseDemo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String data="中国";
PrintWriter out=response.getWriter();
out.write(data);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
运行结果出现乱码,原因:
解决方法:
public void doGet(HttpServletRequest request, HttpServletResponse response){
//设置response使用的码表,以控制response以什么码表向浏览器写出数据
response.setCharacterEncoding("UTF-8");
//指定浏览器以什么码表打开服务器发送的数据
response.setHeader("content-type", "text/html;charset=UTF-8");
//上面一行等同于response.setContentType("text/html;charset=UTF-8");
String data="中国";
PrintWriter out=response.getWriter();//只能写字符和字符串
out.write(data);
}
例3、文件下载。ResponseDemo2.java,在WebRoot文件夹中新建文件夹download并放入两张图片
1.jpg和 日本妞.jpg
package it.cast.response;
import *;
public class ResponseDemo2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//读取web资源:在Servlet中都是用ServletContext去读,其他程序中用类装载器
String path=this.getServletContext().getRealPath("/download/1.jpg");
//这里的第一个/表示web应用
String filename=path.substring(path.lastIndexOf("\\")+1);
response.setHeader("content-disposition", "attachment;filename="+filename);
FileInputStream in=new FileInputStream(path);
int len=0;
byte[] buf=new byte[1024];
OutputStream out=response.getOutputStream();
while((len=in.read(buf))>0){
out.write(buf,0,len);
}
if(in!=null){
in.close();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
注意:中文乱码问题:将上面的文件名改为:日本妞.jpg,将会出现乱码问题,如何解决?
package it.cast.response;
import *;
public class ResponseDemo2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String path=this.getServletContext().getRealPath("/download/日本妞.jpg");
String filename=path.substring(path.lastIndexOf("\\")+1);
//如果下载文件时中文文件,则文件名需要经过url编码
response.setHeader("content-disposition", "attachment;filename="+
URLEncoder.encode(filename,”UTF-8”));
FileInputStream in=new FileInputStream(path);
int len=0;
byte[] buf=new byte[1024];
OutputStream out=response.getOutputStream();
while((len=in.read(buf))>0){
out.write(buf,0,len);
}
if(in!=null){
in.close();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
例4、生成随机图片(用户注册中常用,防止恶意注册)
Step:创建ResponseDemo3.java
package it.cast.response;
import *;
//输出一张随即图片
public class ResponseDemo3 extends HttpServlet {
public static final int WIDTH=120;
public static final int HEIGHT=35;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
BufferedImage image=new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_RGB);
Graphics g=image.getGraphics();
//1、设置背景色
setBackGround(g);
//2、设置边框
setBorder(g);
//3、画干扰线
drawRandomLine(g);
//4、些随机数
drawRandomNum((Graphics2D)g);
//5、图形写给浏览器
response.setContentType("image/jpeg");
//6、发头控制浏览器不要缓存图片
response.setDateHeader("expries", -1);
response.setHeader("Cache-Control","no-cache");
response.setHeader("Pragma","no-cache");
ImageIO.write(image, "jpg", response.getOutputStream());
}
private void drawRandomNum(Graphics2D g) {
g.setColor(Color.RED);
String base="\u4e98\u4e76\u5f54\u7a45\u5af2\u6f22\u4f01\u4f98\u4f45\u5f34\u8a23";
g.setFont(new Font("宋体",Font.BOLD,20));
int x=5;
for(int i=0;i<4;i++){
//汉字的区间:[\u4e00-\u9fa5]这里的u表示Unicode,java中采用Unicode编码
//所以可以这样来些一个中文字符:char c='\u4e00'; (等同于char c='一';)
int degree=new Random().nextInt()%30;//-30~30
String ch=base.charAt(new Random().nextInt(base.length()))+"";
g.rotate(degree*Math.PI/180, x, 20);//设置旋转的弧度
g.drawString(ch, x, 20);
g.rotate(-degree*Math.PI/180, x, 20);
x+=30;
}
}
private void drawRandomLine(Graphics g) {
g.setColor(Color.GREEN);
for(int i=0;i<5;i++){
int x1=new Random().nextInt(WIDTH);
int y1=new Random().nextInt(HEIGHT);
int x2=new Random().nextInt(WIDTH);
int y2=new Random().nextInt(HEIGHT);
g.drawLine(x1,y1,x2,y2);
}
}
private void setBorder(Graphics g) {
g.setColor(Color.BLUE);
g.drawRect(1, 1, WIDTH-2,HEIGHT-2);
}
private void setBackGround(Graphics g) {
g.setColor(Color.WHITE);
g.fillRect(0, 0, WIDTH, HEIGHT);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Step2、在webRoot目录下创建register.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>register.html</title>
<script type="text/javascript"">
function changeImage(img){
img.src=img.src+"?"+new Date().getTime();
//为什么不写成img.src=img.src;(即为img.src=/day06/servlet/ResponseDemo3)呢?与缓存有关,如果后面不跟随机数,意味着一点击图片,浏览器认为这个图片有缓存,就拿缓存了,而后面加了随机数,表示地址发生变化了,与缓存不一样了,所以要加new Date()
}
</script> //这里使用javascript实现点击一下图片就换一张的特效
</head>
<body>
<form action="">
用户名:<input type="text" name="username"><br/>
密码:<input type="password" name="password"><br/>
认证码:<input type="text" name="checkcode">
<img src="/day06/servlet/ResponseDemo3" onclick="changeImage(this)" alt=”换一张” style=”cursor:hand”><br/>
<input type="submit" value="注册">
</form>
</body>
</html>
例5、发送http头,控制浏览器定时刷新网页(refresh).
Step1、创建ResponseDemo4.java
package it.cast.response;
import .*;
//控制浏览器定时刷新
public class ResponseDemo4 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//test1(response);
//test2(response);
test3(request,response);
}
private void test3(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
//假设这是一个用于处理登录的servlet,假设程序运行到此,用户登录成功了
//实际开发中常用的,与JSP配合使用
String message="<meta http-equiv='refresh' content='9;url=/day06/index.jsp'>恭喜你,登陆成功,本浏览器将在3秒后,跳到首页,如果没有跳转,请点击<a href=''>超链接</a>";
this.getServletContext().setAttribute("message", message);
this.getServletContext().getRequestDispatcher("/message.jsp").forward(request, response);
}
private void test2(HttpServletResponse response) throws IOException {
//假设这是一个用于处理登录的servlet
//假设程序运行到此,用户登录成功了
response.setCharacterEncoding("UTF-8");//改变response的码表
response.setContentType("text/html;charset=UTF-8");//通知浏览器打开html页面的码表形式
response.setHeader("refresh", "3;url='/day06/index.jsp'");
response.getWriter().write("恭喜你,登陆成功,本浏览器将在3秒后,跳到首页,如果没有跳转,请点击<a href=''>超链接</a>");
}
private void test1(HttpServletResponse response) throws IOException {
response.setHeader("refresh", "3");//每个3秒刷新一次
String data=new Random().nextInt(1000000)+"";
response.getWriter().write(data);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Step2、创建message.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'message.jsp' starting page</title>
</head>
<body>
<% String message=(String)application.getAttribute("message"); out.write(message); %>
</body>
</html>
例6、用Expires头控制并查看浏览器缓存。(用于网站当中那些不变的图片、css等信息)
Step1、ResponseDemo5
package it.cast.response;
import *;
//控制浏览器缓存
public class ResponseDemo5 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setDateHeader("expires",System.currentTimeMillis()+1000*3600);//缓存一小时,注意这里的时间值一定要是当前时间值+要缓存的时间
String data="aaaaaaa";
response.getWriter().write(data);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Step2、查看浏览器缓存信息的方法:
工具->Internet选项->常规->Internet临时文件->删除文件->删除cookie->设置->查看文件->在浏览器中打开
http://localhost:8080/day06/index.jsp –>点击超链接并刷新Internet临时文件的文件夹,便可看到浏览器的缓存文件信息
例7、请求重定向。
/* 重定向的特点: 1、浏览器会向服务器发送两次,意味着就有两个request\response 2、用重定向技术,浏览器地址栏会发生变化 用户登录和显示购物车时,通常会用到重定向技术 */
package it.cast.response;
import *;
public class ResponseDemo6 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)throws Exception {
response.setStatus(302);
response.setHeader("location", "/day06/index.jsp");
//上面两行代码等同于 response.sendRedirect("/day06/index.jsp");
}
public void doPost(HttpServletRequest request, HttpServletResponse response)throws Exception {
doGet(request, response);
}
}
例8、Request的常用方法举例一。
package it.cast.request;
import *;
public class RequestDemo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)throws Exception {
System.out.println(request.getRequestURI());
System.out.println(request.getRequestURL());
System.out.println(request.getQueryString());
//ie中键入:http://localhost:8080/day06/servlet/RequestDemo1?name=aaa
//上面一行将会打印出:name=aaa
System.out.println(request.getRemoteAddr());
System.out.println(request.getRemoteHost());
System.out.println(request.getRemotePort());
System.out.println(request.getMethod());
}
public void doPost(HttpServletRequest request, HttpServletResponse response)throws Exception {
doGet(request, response);
}
}
在IE中键入:http://localhost:8080/day06/servlet/RequestDemo1?name=aaa
得到运行结果:
http://localhost:8080/day06/servlet/RequestDemo1
name=aaa
127.0.0.1
127.0.0.1
9893
GET
例9、Request常用方法二,获取请求头和请求数据。
Step1、创建RequestDemo2.java
package it.cast.request;
import *;
public class RequestDemo2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取请求头
test1(request);
//获取请求数据(获取请求数据时一般来说要先检查再使用)
test2(request);
}
private void test2(HttpServletRequest request) throws IOException {
System.out.println("------获取数据方式1--------");
String value=request.getParameter("username");
if(value!=null&&value.trim().equals("")){
System.out.println(value);
}
System.out.println("------获取数据方式2--------");
Enumeration e=request.getParameterNames();
while(e.hasMoreElements()){
String name=(String)e.nextElement();
value=request.getParameter(name);
System.out.println(name+"="+value);
}
System.out.println("------获取数据方式3--------");
String[] values=request.getParameterValues("username");
for(int i=0;values!=null&&i<values.length;i++){
System.out.println(values[i]);
}
System.out.println("------获取数据方式4--------");
Map map=request.getParameterMap();
//Map<String,String[]>
User user=new User();
try {
BeanUtils.populate(user, map);//将map中的数据填充到user(bean)
} catch (Exception e1) {
e1.printStackTrace();
}
System.out.println(user.getPassword());
System.out.println("------获取数据方式5(文件上传)--------");
InputStream in=request.getInputStream();
int len=0;
byte buf[]=new byte[1024];
while((len=in.read(buf))>0){
System.out.println(new String(buf,0,len));
}
}
//获取请求头
private void test1(HttpServletRequest request) {
String headValue=request.getHeader("Accept-Encoding");
System.out.println(headValue);
System.out.println("-----------------------");
Enumeration e=request.getHeaders("Accept-Encoding");
while(e.hasMoreElements()){
String value=(String)e.nextElement();
System.out.println(value);
}
System.out.println("-----------------------");
e=request.getHeaderNames();
while(e.hasMoreElements()){
String name=(String)e.nextElement();
String value=request.getHeader(name);
System.out.println(name+"="+value);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Step2、将commons-beanutils-1.8.3.jar和commons-logging-1.1.1.jar拷贝到WebRootWEB-INFlib当中,并创建class
User.java
package it.cast.request;
public class User {
private String username[];
private String password;
public String[] getUsername() {
return username;
}
public void setUsername(String[] username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Step3、创建test.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!-- 通常有两种方式带数据给服务器: 1、超链接 2、表单提交 -->
<html>
<head>
<title>带数据给requestDemo2</title>
</head>
<body>
<a href="/day06/servlet/RequestDemo2?username=xxx">点点</a>
<form action="/day06/servlet/RequestDemo2" method="post">
用户名1:<input type="text" name="username"><br/>
用户名2:<input type="text" name="username"><br/>
密码:<input type="text" name="password"><br/>
<input type="submit" value="提交"><br/>
</form>
</body>
</html>
Step4、在IE中键入http://localhost:8080/day06/test.html ,并填写用户名和密码!
例10、通过表单手机客户端数据。
Step1、form.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>form.html</title>
</head>
<body>
<form action="/day06/servlet/RequestDemo3" method="post">
用户名:<input type="text" name="username"><br/>
密码:<input type="password" name="password"><br/>
性别:<input type="radio" name="gender" value="male">男
<input type="radio" name="gender" value="female">女
<br/>
所在地:
<select name="city">
<option value="beijing">北京</option>
<option value="shanghai">上海</option>
<option value="changsha">长沙</option>
</select>
<br/>
爱好:
<input type="checkbox" name="likes" value="sing">唱歌
<input type="checkbox" name="likes" value="dance">跳舞
<input type="checkbox" name="likes" value="basketball">篮球
<input type="checkbox" name="likes" value="football">足球
<br/>
备注:
<textarea rows="6" cols="60" name="description"></textarea><br/>
大头照:
<input type="file" name="image"><br/>
<input type="hidden" name="id" value="12345">
<input type="submit" value="提交"><br/>
</form>
</body>
</html>
Step2、RequestDemo3.java
package it.cast.request;
import *;
public class RequestDemo3 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("---------------");
System.out.println(request.getParameter("username"));
System.out.println(request.getParameter("password"));
System.out.println(request.getParameter("gender"));
System.out.println(request.getParameter("city"));
String likes[]=request.getParameterValues("likes");
for(int i=0;likes!=null&&i<likes.length;i++){
System.out.println(likes[i]);
}
System.out.println(request.getParameter("description"));
System.out.println(request.getParameter("id"));
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Step2、在IE中键入http://localhost:8080/day06/form.html
填入相关数据以后,点击提交,可以再命令行窗口中看到相应的数据!!!
例11、请求参数的中文乱码问题。
Step1、form.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>中文乱码问题</title>
</head>
<body>
<a href="/day06/servlet/RequestDemo4?username=中国">点击</a>
<form action="/day06/servlet/RequestDemo4" method="post">
用户名(post):<input type="text" name="username"><br/>
<input type="submit" value="提交"><br/>
</form>
<form action="/day06/servlet/RequestDemo4" method="get">
用户名(get):<input type="text" name="username"><br/>
<input type="submit" value="提交"><br/>
</form>
</body>
</html>
Step2、RequestDemo4.java
package it.cast.request;
import *;
public class RequestDemo4 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username=request.getParameter("username");//包含了超链接和表单里面的username
System.out.println(username);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Step3、在IE中打开:http://localhost:8080/day06/form2.html
输入:中国
在命令行窗口中会出现乱码 ??
解决方法:
Step1、form2.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>中文乱码问题</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!-- 上面一行设置了浏览器打开此网页的编码方式为UTF-8 -->
</head>
<body>
<!-- 超链接提交的中文,服务器想不乱码,也只能手工处理 -->
<a href="/day06/servlet/RequestDemo4?username=中国">点击</a>
<form action="/day06/servlet/RequestDemo4" method="post">
用户名(post):<input type="text" name="username"><br/>
<input type="submit" value="提交"><br/>
</form>
<form action="/day06/servlet/RequestDemo4" method="get">
用户名(get):<input type="text" name="username"><br/>
<input type="submit" value="提交"><br/>
</form>
</body>
</html>
Step2、ResponseDemo4.java
package it.cast.request;
import *;
public class RequestDemo4 extends HttpServlet {
//Request的码表默认为iso8859-1
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("---------------");
//test1(request);
test2(request);
}
//表单中POST方式的乱码解决方式
private void test2(HttpServletRequest request)
throws UnsupportedEncodingException {
request.setCharacterEncoding("UTF-8");//将Request码表改为UTF-8
String username=request.getParameter("username");
System.out.println(username);
}
//表单中GET方式的乱码解决方式(手工处理)
private void test1(HttpServletRequest request)
throws UnsupportedEncodingException {
String username=request.getParameter("username");
username=new String(username.getBytes("iso8859-1"),"UTF-8");
System.out.println(username);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
例12、Request的转发技术
Step1、RequestDemo5.java
package it.cast.request;
import
//请求转发以及使用Request域对象把数据带给转发资源
public class RequestDemo5 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String data="fandong";
request.setAttribute("data", data);//使用Request域对象把数据带给转发资源
//request也可以实现转发
request.getRequestDispatcher("/message.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Step2、message.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'message.jsp' starting page</title>
</head>
<body>
<% String data=(String)request.getAttribute("data"); out.write(data); %>
<% String message=(String)application.getAttribute("message"); out.write(message); %>
</body>
</html>
在IE中输入http://localhst:8080/day06/servlet/RequestDemo5
结果:fandong
例13、在servlet程序当中,servlet程序中写入的部分内容已经被真真地传送给了客户端,forward方法将跑出lllegalStateException异常。
package it.cast.request;
import
public class RequestDemo6 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if(true){
request.getRequestDispatcher("/index.jsp").forward(request, response);
return;//每次页面跳转完之后一定要return
}
request.getRequestDispatcher("/message.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
例14、RequestDemo7.java(forword是会清空Response的数据)
package it.cast.request;
import
public class RequestDemo7 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String data="aaaaaaaaa";
response.getWriter().write(data);//这一步实际上是将data写入了Response(缓冲区),并没有写入浏览器,只有当流关闭(刷新了之后才会写入浏览器)
request.getRequestDispatcher("index.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
/* * 在浏览器中键入http://localhost:8080/day06/servlet/RequestDemo7将会看到:fandong * 而并不是我们所期望的aaaaaaaaaaaafandong *请求转发的特点 *1、客户端只发一次请求,而服务器有多个资源调用 *2、客户端浏览地址栏没有变化 */
Index.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>
<title>My JSP 'index.jsp' starting page</title>
</head>
<body>
<a href="/day06/servlet/ResponseDemo5">fandong</a>
</body>
</html>
例15、web工程中各类地址的写法
package it.cast.url;
import
//1、想要获取URL就打/;
//2、想要获取硬盘上的资源就用\
public class ServletDemo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//1、地址给服务器用的/代表web应用webroot
request.getRequestDispatcher("/index.jsp").forward(request, response);
//2、地址给浏览器用的,/代表网站
response.sendRedirect("/day06/index.jsp");
//3、地址给服务器用的/代表web应用webroot
this.getServletContext().getRealPath("/index.jsp");
//4、地址给服务器用的/代表web应用webroot
this.getServletContext().getResourceAsStream("/WEB-INF/web.xml");
//5、地址给浏览器用的,/代表网站
/* * <a href="/day06/index.jsp">点点</a> * <form action="/day06/index.jsp"> * </form> */
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
/*写地址最好以/开头,如果是给服务器用的地址/代表当前的web应用 * 如果这个地址是给浏览器用的,/就代表网站(网站下面有多个web应用) */
例16、resquest常见应用之防盗链.
Step、RequestDemo9.java
package it.cast.request;
import
public class RequestDemo9 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String referer = request.getHeader("referer");
if(referer==null|| !referer.startsWith("http://localhost")){
response.sendRedirect("/day06/index.jsp");
return;//表示下面的代码不带执行
}
String data="凤姐日记";
response.getWriter().write(data);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Step2、index.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>
<title>My JSP 'index.jsp' starting page</title>
</head>
<body>
<a href="/day06/servlet/ResponseDemo9">看凤姐</a>
</body>
</html>