新闻发布项目——Servlet类(doNewsAddServlet)

package bdqn.newsManageServlet.Servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import bdqn.newsManageServlet.Dao.newsTbDao;
import bdqn.newsManageServlet.Dao.Impl.newsTbDaoImpl;
import bdqn.newsManageServlet.Service.categoryTBService;
import bdqn.newsManageServlet.Service.Impl.categoryTBServiceImpl;
import bdqn.newsManageServlet.entity.categoryTB;
import bdqn.newsManageServlet.entity.newsTb;

public class doNewsAddServlet extends HttpServlet {

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		//添加新聞
		//获取相对应的值
		request.setCharacterEncoding("utf-8");
		newsTb news = new newsTb();
		String categoryName = "";//主题
		String title = "";//标题
		String author = "";//作者
		String summary = "";//摘要
		String content = "";//内容
		String picPath = "";//文件路径
		int id = 0;//类别id
		//判断是不是文件上传
		boolean ismultipart = ServletFileUpload.isMultipartContent(request);
		if (ismultipart) {
			//创建文件工厂
			FileItemFactory fac = new DiskFileItemFactory();
			//创建文件上传对象
			ServletFileUpload fileUpload = new ServletFileUpload(fac);
			//解析请求 
			List<FileItem> fileItemlist;
			try {
				fileItemlist = fileUpload.parseRequest(request);
		
			//遍历集合,获取响应的数据 
			try {
				for (FileItem item : fileItemlist) {
					//判断是普通的表单还是文件表单
					if (item.isFormField()) {
						//普通表单
						String fileName = item.getFieldName();
						//主题
						if (fileName.equals("slt")) {
							categoryName = item.getString("utf-8");
							categoryTBService cateService = new categoryTBServiceImpl();
							categoryTB cate = cateService
									.getCategoryIdByName(categoryName);
							//类别的id
							id = cate.getCategoryID();
						} else if (fileName.equals("title")) {
							//标题
							title = item.getString("utf-8");
						} else if (fileName.equals("author")) {
							//作者
							author = item.getString("utf-8");
						} else if (fileName.equals("summary")) {
							//摘要
							summary = item.getString("utf-8");
						} else if (fileName.equals("content")) {
							//内容
							content = item.getString("utf-8");
						}

					} else {
						//文件表单
						//获取文件名全路径
						String fullfile = item.getName();
						File file1 = new File(fullfile);
						//控制文件上传类型
						//通过Arrays类的aList()方法创建固定长度的集合
						List<String> fileType=Arrays.asList("gif","bmp","jpg");
						String ext=fullfile.substring(fullfile.lastIndexOf(".")+1);
						if(fileType.contains(ext)){
						//上传成功!
						//获取文件名,不包含文件路径
						String filename = file1.getName();
						//取得application对象
						ServletContext application=this.getServletContext();
						//调用application里面的属性和方法
						String uploadPath = application
								.getRealPath("adminManage/");
						File file2 = new File(uploadPath, filename);
						item.write(file2);
						picPath=file2.toString();
						//上传成功!
						}else{
						request.setAttribute("mesg", "文件类型只能是图片类型");
						request.getRequestDispatcher("addNews.jsp").forward(request,response);
						return;
						}
					}
				}

			} catch (Exception ex) {
				ex.printStackTrace();
			}
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		/* 	//根据类别名臣获取类别id
		 String categoryName = request.getParameter("slt");
		 categoryTBService cateService = new categoryTBServiceImpl();
		 categoryTB cate = cateService.getCategoryIdByName(categoryName);
		 //类别的id
		 int id = cate.getCategoryID();
		 String title = request.getParameter("title");//标题
		 String author = request.getParameter("author");//作者
		 String summary = request.getParameter("summary");//摘要
		 String content = request.getParameter("content");//内容
		 String picPath = request.getParameter("picPath");//上传图片路径 */
		//把内容添加到数据库中

		//封装
		newsTbDao ndao = new newsTbDaoImpl();
		//	newsTb news = new newsTb();
		news.setCategoryID(id);
		news.setTitle(title);
		news.setAuthor(author);
		news.setSummary(summary);
		news.setContent(content);
		news.setPicPath(picPath);
		int rel = ndao.addNewsTb(news);
		if (rel > 0) {
			out.print("<script>alert('添加成功!');location.href='adminManage/editNews.jsp';</script>");
		} else {
			out.print("<script>alert('添加失败!');location.href='adminManage/addNews.jsp';</script>");
		}
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}

原文地址:https://www.cnblogs.com/a1111/p/12816504.html