Response案例
程序员文章站
2022-06-09 12:58:50
...
一、验证码生成点击换
public class CodeServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//参数1:宽度 参数2:高度 参数三:字符个数 参数4:干扰线的条数
//生成图片函数
ValidateCode vc = new ValidateCode(135, 35, 4, 10);
//把图片写入到页面中
vc.write(response.getOutputStream());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
<script type="text/javascript">
function changecode(){
document.getElementById("img").src ="/webday10.login/codeServlet?time="+new Date().getTime();
}
</script>
<div id="div1">
验证码:
<input type="text" id="inputPassword" name="checkcode" placeholder="请输入验证码" />
<img id="img" src="/webday10.login/codeServlet" onclick="changecode()"/>
</div>
</body>
2、文件下载
public class ServletDemo1 extends HttpServlet{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//response的乱码设
response.setContentType("text/html;charset=UTF-8");
//request的post提交乱码设置
/* request.setCharacterEncoding("UTF-8");*/
//request的get提交乱码设置
//filename = new String(filename.getBytes("iso-8859-1"),"UTF-8");
String method = request.getMethod();
System.out.println(method);
//1、获取请求参数
//获取文件名称
String filename = request.getParameter("filename");
filename = new String(filename.getBytes("iso-8859-1"),"UTF-8");
System.out.println(filename);
//获取服务器中的tomcat中的路径
ServletContext appliction = this.getServletContext();
System.out.println(appliction);
//获取当前文件的路径
InputStream is = appliction.getResourceAsStream("/WEB-INF/classes/"+filename);
//告知浏览器要下载文件的类型
response.setHeader("content-disposition","attchment;filename="+filename);
//告知浏览器下载文件的类型
System.out.println("attchment;filename="+filename);
response.setHeader("content-type",appliction.getMimeType(filename));
System.out.println(appliction.getMimeType(filename));
//响应数据
ServletOutputStream os = response.getOutputStream();
int len= 0 ;
byte[] b= new byte[1024];
while((len=is.read(b)) !=-1){
os.write(b,0,len);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
<a href="/webday10/ServletDemo2?filename=1.jpg">下载jpg</a>
<a href="/webday10/ServletDemo2?filename=2.rar">下载rar</a>
<a href="/webday10/ServletDemo2?filename=3.zip">下载zip</a>
<a href="/webday10/ServletDemo2?filename=阿.jpg">下载杨幂</a>
下一篇: 椰树椰子汁,为什么不是白的