java web登陆注册_Java Web项目案例之---登录和注册(精华版)

packageservlet;importentity.User;importorg.apache.commons.fileupload.FileItem;importorg.apache.commons.fileupload.FileUploadException;importorg.apache.commons.fileupload.disk.DiskFileItemFactory;importorg.apache.commons.fileupload.servlet.ServletFileUpload;importutil.UploadUtil;importjavax.servlet.ServletContext;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;importjava.util.ArrayList;importjava.util.HashMap;importjava.util.List;importjava.util.Map;

@WebServlet("/LoginServlet")public class LoginServlet extendsHttpServlet {

@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throwsServletException, IOException {//数据的接收//文件上传基本操作

try{//定义一个Map集合存放接收到的数据

Map map=new HashMap();//1.创建一个磁盘文件项工厂对象

DiskFileItemFactory diskFileItemFactory=newDiskFileItemFactory();//2.创建一个核心解析类

ServletFileUpload servletFileUpload=newServletFileUpload(diskFileItemFactory);//3.解析request请求

List list=servletFileUpload.parseRequest(req);//定义一个List集合,用于保存复选框中的值

List hobbyList=new ArrayList();//4.遍历集合,获得每个FileItem,判断是表单项还是文件上传项

String url=null;for(FileItem fileItem:list){//判断是否是普通表单项

if(fileItem.isFormField()){//接收表单项参数的值

String name=fileItem.getFieldName();

String value=fileItem.getString("UTF-8");if("hobby".equals(name)){//接收复选框的值

String hobbyvalue=fileItem.getString("UTF-8");//将值存入hobbyList集合中

hobbyList.add(hobbyvalue);

hobbyvalue=hobbyList.toString().substring(1,hobbyList.toString().length()-1);

map.put(name,hobbyvalue);

}else{

map.put(name,value);

}

}else{//文件上传项//文件上传功能//获得文件上传的名称

String fileName=fileItem.getName();//通过工具获得唯一文件名

String uuidFileName=UploadUtil.getUUIDFileName(fileName);//获得文件上传数据 输入流

InputStream is=fileItem.getInputStream();//获得文件上传相对路径

String path=this.getServletContext().getRealPath("/upload");//将输入流对接到输出流

url=path+"//"+uuidFileName;

OutputStream os=newFileOutputStream(url);int len=0;byte[] b=new byte[1024];while((len=is.read(b))!=-1){

os.write(b,0,len);

}

is.close();

os.close();

}

}

User user=newUser();

user.setUsername(map.get("username"));

user.setPassword(map.get("password"));

user.setSex(map.get("sex"));

user.setHobby(map.get("hobby"));

user.setPath(url);

List userlist=(List)this.getServletContext().getAttribute("list");

userlist.add(user);

System.out.println(user.getUsername()+","+user.getPassword()+","+user.getSex()+","+user.getHobby()+","+user.getPath());

resp.sendRedirect("login.jsp");

}catch(FileUploadException e) {

e.printStackTrace();

}

}

@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throwsServletException, IOException {

doPost(req, resp);

}

}

你可能感兴趣的:(java,web登陆注册)