.java文件写接口:
package com.byron.learnservlet;
import com.google.gson.*;
import org.dom4j.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletHelloworld extends HttpServlet {
private BufferedReader br;
@Override
public void init() throws ServletException {
// TODO Auto-generated method stub
System.out.println("init");
super.init();
}
@Override
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
super.init(config);
System.out.println("initconfig");
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
super.service(req, resp);
System.out.println("service");
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
// super.doGet(req, resp);
System.out.println("doGet");
try {
handlereq(req,resp);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
// super.doPost(req, resp);
System.out.println("doPost");
try {
handlereq(req,resp);
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void handlereq(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, DocumentException {
System.out.println(req.getServletPath());// /hello
System.out.println(req.getMethod()); // GET
System.out.println(req.getRequestURL()); // http://localhost:8888/learnjsp1/hello
// System.out.println(req.getRequestURI()); // /learnjsp1/hello
// System.out.println("123"+req.getCharacterEncoding()); // /learnjsp1/hello
// System.out.println("456"+req.getContentType()); // /learnjsp1/hello
//读取请求参数相关代码
//req.getParameterNames().hasMoreElements()排除无参数请求报错问题
System.out.println("开始处理请求");
// req.setCharacterEncoding("UTF-8");
// resp.setCharacterEncoding("UTF-8");
// resp.setContentType("text/html;charset=utf-8");
if(!req.getServletPath().contains("/hello4")&&(req.getParameterNames().hasMoreElements())) {
if(req.getParameterNames().nextElement().contains("<")) {
//读取请求参数
Enumeration<String> em = req.getParameterNames();
String name = (String) em.nextElement();
String value = req.getParameter(name);
String xmlstr = name+"="+value;
System.out.println("xmlstr:"+xmlstr);
Document document = DocumentHelper.parseText(xmlstr);
//获取根节点元素对象
Element root = document.getRootElement();
//遍历
listNodes(root);
}else {
//json读取请求参数
Enumeration<String> em = req.getParameterNames();
while (em.hasMoreElements()) {
String name = (String) em.nextElement();
String value = req.getParameter(name);
System.out.println(name+"="+value);
}
//json通过map读取参数
Map<String,String[]> map = req.getParameterMap();
Set<String> keys = map.keySet();
for(String key:keys ) {
String[] value = map.get(key);
System.out.println(key+"="+value[0]);
}
}
}
if(req.getServletPath().contains("/hello1")) {//给请求返回字符串
// 返回字符串
PrintWriter out = resp.getWriter();
out.println("fds");
out.close();
}
if(req.getServletPath().contains("/hello5")) {//给请求返回本地文件内容
String path ="/Users/bangqizhineng/Desktop/自己的文档/javacode"; // 这边文件目录需改成相对路径
File file = new File(path,"台湾王公馆.json");
FileReader fr = new FileReader(file); //字符输入流
br = new BufferedReader(fr);
String str = br.readLine();
PrintWriter out = resp.getWriter();
out.println(str);
out.close();
}
if(req.getServletPath().contains("/hello6")) {//给请求返回本地文件内容
resp.setContentType("image/png");
resp.setCharacterEncoding("utf-8");
String path ="/Users/bangqizhineng/Desktop/自己的文档/javacode/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/learnjsp1/WebContent/WEB-INF/c13b2a16-8a18-4696-a580-6ab88c5bd7ad_1.jpg"; // 这边文件目录需改成相对路径
FileInputStream fis = null;
File file = new File(path);
fis = new FileInputStream(file);
byte[] b = new byte[fis.available()];
fis.read(b);
OutputStream out = resp.getOutputStream();
out.write(b);
out.flush();
}
if(req.getServletPath().contains("/hello2")) {//json get post请求
//返回json
JsonObject responseJSONObject=new JsonObject();
responseJSONObject.addProperty("name","xuanyouwu尖峰时刻");
resp.setContentType("application/json; charset=utf-8");
PrintWriter out = resp.getWriter();
out.append(responseJSONObject.toString());
out.close();
}
if(req.getServletPath().contains("/hello3")) {//xml post 请求
Document xmldom = DocumentHelper.createDocument();
Element root = DocumentHelper.createElement("students");
xmldom.setRootElement(root);
root.addAttribute("name", "liming");
Element root1 = root.addElement("goodstudent");
root1.addAttribute("sort", "first").addAttribute("sort1", "first");
root1.addText("1");
//连续添加两个子节点
root1.addElement("3").addAttribute("3-1", "3").addAttribute("3-2", "3").addElement("4").addAttribute("4-1", "3").addAttribute("4-2", "3");
resp.setContentType("text/xml; charset=utf-8");
PrintWriter out = resp.getWriter();
out.append(xmldom.asXML());
out.close();
}
if(req.getServletPath().contains("/hello4")) {
//得到上传文件的保存目录,将上传的文件存放于WEB-INF目录下,不允许外界直接访问,保证上传文件的安全
String savePath = this.getServletContext().getRealPath("/WebContent/WEB-INF");
//上传时生成的临时文件保存目录
String tempPath = this.getServletContext().getRealPath("tem");
File tmpFile = new File(tempPath);
if (!tmpFile.exists()) {
//创建临时目录
tmpFile.mkdir();
}
//消息提示
String message = "";
try{
//使用Apache文件上传组件处理文件上传步骤:
//1、创建一个DiskFileItemFactory工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
//设置工厂的缓冲区的大小,当上传的文件大小超过缓冲区的大小时,就会生成一个临时文件存放到指定的临时目录当中。
factory.setSizeThreshold(1024*1000);//设置缓冲区的大小为100KB,如果不指定,那么缓冲区的大小默认是10KB
//设置上传时生成的临时文件的保存目录
factory.setRepository(tmpFile);
//2、创建一个文件上传解析器
ServletFileUpload upload = new ServletFileUpload(factory);
//监听文件上传进度
upload.setProgressListener(new ProgressListener(){
public void update(long pBytesRead, long pContentLength, int arg2) {
System.out.println("文件大小为:" + pContentLength + ",当前已处理:" + pBytesRead);
/**
* 文件大小为:14608,当前已处理:4096
文件大小为:14608,当前已处理:7367
文件大小为:14608,当前已处理:11419
文件大小为:14608,当前已处理:14608
*/
float f = pBytesRead/pContentLength;
// try {
// resp.getWriter().write(f+"");
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
});
//解决上传文件名的中文乱码
upload.setHeaderEncoding("UTF-8");
//3、判断提交上来的数据是否是上传表单的数据
if(!ServletFileUpload.isMultipartContent(req)){
//按照传统方式获取数据
return;
}
//设置上传单个文件的大小的最大值,目前是设置为1024*1024字节,也就是1MB
upload.setFileSizeMax(1024*1024);
//设置上传文件总量的最大值,最大值=同时上传的多个文件的大小的最大值的和,目前设置为10MB
upload.setSizeMax(1024*1024*10);
//4、使用ServletFileUpload解析器解析上传数据,解析结果返回的是一个List<FileItem>集合,每一个FileItem对应一个Form表单的输入项
List<FileItem> list = upload.parseRequest(req);
System.out.println(list.size());
for(FileItem item : list){
//如果fileitem中封装的是普通输入项的数据
if(item.isFormField()){
String name = item.getFieldName();
//解决普通输入项的数据的中文乱码问题
String value = item.getString("UTF-8");
//value = new String(value.getBytes("iso8859-1"),"UTF-8");
System.out.println(name + "=" + value);
}else{//如果fileitem中封装的是上传文件
//得到上传的文件名称,
String filename = item.getName();
System.out.println("上传的文件名称"+filename);
if(filename==null || filename.trim().equals("")){
continue;
}
//注意:不同的浏览器提交的文件名是不一样的,有些浏览器提交上来的文件名是带有路径的,如: c:\a\b\1.txt,而有些只是单纯的文件名,如:1.txt
//处理获取到的上传文件的文件名的路径部分,只保留文件名部分
filename = filename.substring(filename.lastIndexOf("\\")+1);
//得到上传文件的扩展名
String fileExtName = filename.substring(filename.lastIndexOf(".")+1);
//如果需要限制上传的文件类型,那么可以通过文件的扩展名来判断上传的文件类型是否合法
System.out.println("上传的文件的扩展名是:"+fileExtName);
//得到文件保存的名称
String saveFilename = makeFileName(filename);
//得到文件的保存目录
String realSavePath = savePath + "/" + saveFilename;
/*保存文件方法11111:*/
// File storeFile = new File(realSavePath);
// // 在控制台输出文件的上传路径
// System.out.println(realSavePath);
// // 保存文件到硬盘
// item.write(storeFile);
/*保存文件方法222222:*/
//获取item中的上传文件的输入流
InputStream in = item.getInputStream();
//创建一个文件输出流
FileOutputStream out = new FileOutputStream(realSavePath);
//创建一个缓冲区
byte buffer[] = new byte[1024];
//判断输入流中的数据是否已经读完的标识
int len = 0;
//循环将输入流读入到缓冲区当中,(len=in.read(buffer))>0就表示in里面还有数据
while((len=in.read(buffer))>0){
//使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中
out.write(buffer, 0, len);
}
//关闭输入流
in.close();
//关闭输出流
out.close();
//删除处理文件上传时生成的临时文件
item.delete();
System.out.println("文件上传成功!");
message = "文件上传成功!";
}
}
}catch (FileUploadBase.FileSizeLimitExceededException e) {
message= "单个文件超出最大值!!!";
e.printStackTrace();
return;
}catch (FileUploadBase.SizeLimitExceededException e) {
message= "上传文件的总的大小超出限制的最大值!!!";
e.printStackTrace();
return;
}catch (Exception e) {
System.out.println("文件上传失败!");
message= "文件上传失败!";
e.printStackTrace();
}
JsonObject responseJSONObject=new JsonObject();
responseJSONObject.addProperty("message","amfdsf555我的你");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
/*注意:前后端搭配
* resp.setContentType("text/html;charset=utf-8");
* mgr.responseSerializer = [AFHTTPResponseSerializer serializer];
* NSString *shabi = [[NSString alloc]initWithData:json encoding:NSUTF8StringEncoding];
* */
/*注意:前后端搭配
* resp.setContentType("application/json; charset=utf-8");
* mgr.responseSerializer = [ AFJSONResponseSerializer serializer];
* NSDictionary *dic = (NSDictionary *)json;
* */
System.out.println("dsds"+responseJSONObject.toString());
resp.getWriter().append(responseJSONObject.toString());
req.setAttribute("message",message);
//返回json
// JsonObject responseJSONObject=new JsonObject();
// responseJSONObject.addProperty("message",message);
//// resp.setCharacterEncoding("utf-8");
//// resp.setContentType("text/html;charset=utf-8");
//// resp.setContentType("application/json; charset=utf-8");
// PrintWriter outwriter = resp.getWriter();
// outwriter.append("11");
// outwriter.close();
}
}
//遍历当前节点下的所有节点
public void listNodes(Element node){
System.out.println("当前节点的名称:" + node.getName());
//首先获取当前节点的所有属性节点
List<Attribute> list = node.attributes();
//遍历属性节点
for(Attribute attribute : list){
System.out.println("属性"+attribute.getName() +":" + attribute.getValue());
}
//如果当前节点内容不为空,则输出
if(!(node.getTextTrim().equals(""))){
System.out.println( node.getName() + ":" + node.getText());
}
//同时迭代当前节点下面的所有子节点
//使用递归
Iterator<Element> iterator = node.elementIterator();
while(iterator.hasNext()){
Element e = iterator.next();
listNodes(e);
}
}
/**
* @Method: makeFileName
* @Description: 生成上传文件的文件名,文件名以:uuid+"_"+文件的原始名称
* @Anthor:孤傲苍狼
* @param filename 文件的原始名称
* @return uuid+"_"+文件的原始名称
*/
private String makeFileName(String filename){ //2.jpg
//为防止文件覆盖的现象发生,要为上传文件产生一个唯一的文件名
return UUID.randomUUID().toString() + "_" + filename;
}
/**
* 为防止一个目录下面出现太多文件,要使用hash算法打散存储
* @Method: makePath
* @Description:
* @Anthor:孤傲苍狼
*
* @param filename 文件名,要根据文件名生成存储目录
* @param savePath 文件存储路径
* @return 新的存储目录
*/
private String makePath(String filename,String savePath){
//得到文件名的hashCode的值,得到的就是filename这个字符串对象在内存中的地址
int hashcode = filename.hashCode();
int dir1 = hashcode&0xf; //0--15
int dir2 = (hashcode&0xf0)>>4; //0-15
//构造新的保存目录
String dir = savePath + "\\" + dir1 + "\\" + dir2; //upload\2\3 upload\3\5
//File既可以代表文件也可以代表目录
File file = new File(dir);
//如果目录不存在
if(!file.exists()){
//创建目录
file.mkdirs();
}
return dir;
}
@Override
public void destroy() {
// TODO Auto-generated method stub
super.destroy();
System.out.println("destroy");
}
}
web.xml文件写:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>learnjsp1</display-name>
<servlet>
<servlet-name>ServletHelloworld</servlet-name>
<servlet-class>com.byron.learnservlet.ServletHelloworld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletHelloworld</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.png</url-pattern>
</servlet-mapping>
<listener>
<listener-class>
org.apache.commons.fileupload.servlet.FileCleanerCleanup
</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
网友评论