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

简介: 新闻发布项目——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
  }
}


相关文章
|
7月前
|
Java 应用服务中间件 程序员
如何利用Idea创建一个Servlet项目(新手向)(下)
如何利用Idea创建一个Servlet项目(新手向)(下)
162 0
|
7月前
|
Java 应用服务中间件 API
如何利用Idea创建一个Servlet项目(新手向)(上)
如何利用Idea创建一个Servlet项目(新手向)
397 0
|
7月前
新闻发布项目——Servlet类(doRegServlet )
新闻发布项目——Servlet类(doRegServlet )
|
6月前
|
Java 应用服务中间件 Maven
IDEA创建一个Servlet项目(tomcat10)
IDEA创建一个Servlet项目(tomcat10)
302 1
|
7月前
|
自然语言处理 Java 应用服务中间件
从零手写实现 tomcat-09-servlet 处理类
该文是一个关于手写实现 Apache Tomcat 简化版的系列教程摘要。作者希望通过亲自实现一个简单的 Tomcat,来深入理解其工作原理。系列教程包括了从入门介绍到解析处理 WAR 包、与 SpringBoot 集成等多个步骤。文章介绍了 Servlet 的概念,将其比作餐厅服务员,负责处理网络请求和响应。文中还详细阐述了 Servlet 的处理流程,并通过实例解释了如何实现一个基础的 Servlet。最后,提到了如何根据请求 URL 进行调度和处理,并给出了迷你版 Tomcat(Mini-Cat)的开源地址。
|
7月前
|
Java
springboot项目出现Exception in thread “main“ java.lang.NoClassDefFoundError: javax/servlet/Filter
springboot项目出现Exception in thread “main“ java.lang.NoClassDefFoundError: javax/servlet/Filter
266 0
|
4月前
|
缓存 安全 Java
Java服务器端技术:Servlet与JSP的集成与扩展
Java服务器端技术:Servlet与JSP的集成与扩展
41 3
|
4月前
|
存储 缓存 前端开发
Servlet与JSP在Java Web应用中的性能调优策略
Servlet与JSP在Java Web应用中的性能调优策略
41 1
|
4月前
|
存储 Java 关系型数据库
基于Servlet和JSP的Java Web应用开发指南
基于Servlet和JSP的Java Web应用开发指南
79 0
|
4月前
|
前端开发 安全 Java
在Java服务器端开发的浩瀚宇宙中,Servlet与JSP犹如两颗璀璨的明星,它们联袂登场,共同编织出动态网站的绚丽篇章。
在Java服务器端开发的浩瀚宇宙中,Servlet与JSP犹如两颗璀璨的明星,它们联袂登场,共同编织出动态网站的绚丽篇章。
31 0