Servlet

一.基础

1.servlet结构

@WebServlet("/student/*")
public class StudentServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    }
}

2.request方法

// 请求方式,协议名称,报头信息
request.getMethod();
request.getProtocol();
request.getHeader("x-forwarded-for");
Enumeration<String> list = request.getHeaderNames();

//客户端的ip,主机名,端口
request.getRemoteAddr();
request.getRemoteHost();
request.getRemotePort();
//服务端的ip,主机名,端口
request.getLocalAddr();
request.getLocalName();
request.getLocalPort();

//编码方式
request.getCharacterEncoding();
request.setCharacterEncoding("UTF-8");
request.getContentType();

//http
String scheme = request.getScheme();
//域名或ip地址
String serverName = request.getServerName();
//端口号
int serverPort = request.getServerPort();
// /项目名
String contextPath = request.getContextPath();
// /servlet路径
String servletPath = request.getServletPath();
// /额外路径
String pathInfo = request.getPathInfo();
if(pathInfo==null) pathInfo = "";

//获取完整路径两种方法
String url = scheme + "://" + serverName + ":" + serverPort+ contextPath + servletPath + pathInfo;
StringBuffer requestUrl = request.getRequestURL();
// /项目名/servlet路径/额外路径
String requestUri = request.getRequestURI();
//查询字符串
String query = request.getQueryString();

//获取客户端传过来的数据
String id = request.getParameter("file");
String[] checkbox = request.getParameterValues("checkbox");
//在同一个request中保存获取数据
request.setAttribute("data", 1);
request.getAttribute("data");
request.removeAttribute("data");

//获取session和cookie
HttpSession session = request.getSession();
Cookie[] cookes = request.getCookies();

//获取application两种方式
ServletContext application = getServletContext();
application = session.getServletContext();
//获取实际路径
String path = application.getRealPath("/upload");

3.response方法

//添加cookie
Cookie cookie = new Cookie("id","1001");
response.addCookie(cookie);
//设置状态,发送错误
response.setStatus(404);
response.sendError(404, "找不到资源");
//判断是否提交
response.isCommitted();

//设置编码,与contentType相互覆盖
response.setCharacterEncoding("GBK");
response.getCharacterEncoding();
//文档内容类型和编码,以下2种方式等价   
response.setContentType("text/html;charset=UTF-8");
response.getContentType();
response.setHeader("Content-Type","application/json;charset=GBK");
response.getHeader("Content-Type");

Student student = new Student(1001,"张三");
JSONObject json = JSONObject.fromObject(student);
//输出字符流
PrintWriter writer = response.getWriter();
writer.println(json.toString());
writer.append("Hi").append("!");
writer.close();

//获取文件输入流,读取二进制数据写入输出流
BufferedInputStream input = new BufferedInputStream(new FileInputStream(realPath));
ServletOutputStream output = response.getOutputStream();
byte[] buffer = new byte[input.available()];
input.read(buffer);
output.write(buffer);
output.close();

//转发(根目录:WebUrl/项目)
request.getRequestDispatcher("/teacher/list").forward(request, response);
//重定向(根目录:WebUrl)
response.sendRedirect(contextPath+"/teacher/list");

4.Content-type
在Http协议消息头中,使用Content-Type来表示具体请求中的媒体类型信息
常见的媒体格式类型如下:

text/html : HTML格式
text/plain :纯文本格式
text/xml : XML格式
image/gif :gif图片格式
image/jpeg :jpg图片格式
image/png:png图片格式

以application开头的媒体格式类型:

application/xhtml+xml :XHTML格式
application/xml : XML数据格式
application/atom+xml :Atom XML聚合格式
application/json : JSON数据格式
application/pdf :pdf格式
application/msword : Word文档格式
application/octet-stream : 二进制流数据(如常见的文件下载)
application/x-www-form-urlencoded : 表单中默认的encType,表单数据被编码为key/value格式发送到服务器
multipart/form-data : 需要在表单中进行文件上传时,就需要使用该格式

二.文件上传下载

1.文件上传

<form action="student/upload" id="form" method="post" enctype="multipart/form-data">
        <input type="file" name="name">
        <button>提交</button>
</form>
//提交整个表单
var formData = new FormData($("#form")[0]);
//提交单个文件
var formData = new FormData();
formData.append("file",$("#upload")[0].files[0]);
$.ajax({
    url:"teacher/upload",
    data:formData,
    type:"post",
    dataType:"json",
    //不设置Content-Type请求头
    contentType:false,
    //不处理发送的数据
    processData:false, 
    success:function(data) {
        alert("成功:"+JSON.stringify(data));
    },
    error:function(data) {
        alert("失败:"+JSON.stringify(data));
    }
});
public class MyFile {

    private String path;
    private String name;

    public String getPath() {
        return path;
    }
    public void setPath(String path) {
        this.path = path;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}
public static List<MyFile> upload(HttpServletRequest request) throws Exception{
    //请求类型不是文件上传
    if(!ServletFileUpload.isMultipartContent(request)) {
        return null;
    }
    List<MyFile> myFiles = new ArrayList<MyFile>();
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);

    ServletContext application = request.getSession().getServletContext();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    String date = sdf.format(new Date());
    //获取相对路径和绝对路径
    String basePath = "/uploadFile/"+date+"/";
    String realPath = application.getRealPath(basePath);

    List<FileItem> items = upload.parseRequest(request);

       for(FileItem item : items) {
        //数据是文件格式
        if (!item.isFormField()) {
            //设置文件名
            String name = item.getName();
            String suffix = name.substring(name.lastIndexOf("."), name.length());
            String fileName = UuidUtil.getUuid()+suffix;

            File file = new File(realPath, fileName);
            file.getParentFile().mkdirs();
            item.write(file);

            MyFile myFile = new MyFile();
            myFile.setName(name);
            myFile.setPath(basePath+fileName);
            myFiles.add(myFile);
        }
       }
    return myFiles;
}

2.文件下载

public static void download(HttpServletResponse response,HttpServletRequest request,MyFile myFile) throws Exception {
    //将文件名编码(防止中文乱码)
    String fileName = URLEncoder.encode(myFile.getName(),"utf-8");
    //获取文件绝对路径
    ServletContext application = request.getSession().getServletContext();
    String realPath = application.getRealPath(myFile.getPath());
    //设置返回类型为文件类型
    response.setHeader("Content-Disposition", "attachment;filename="+fileName);
    //获取文件输入流,读取二进制数据写入输出流
    BufferedInputStream input = new BufferedInputStream(new FileInputStream(realPath));
    ServletOutputStream output = response.getOutputStream();
    byte[] buffer = new byte[input.available()];
    input.read(buffer);
    output.write(buffer);
    output.close();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值