NewsAddAction.java
上传用户:jishiqi_cj
上传日期:2022-08-08
资源大小:24765k
文件大小:2k
源码类别:

Java编程

开发平台:

Java

  1. package StudyNews;
  2. import javax.servlet.http.HttpServletRequest;
  3. import javax.servlet.http.HttpServletResponse;
  4. import org.apache.struts.action.Action;
  5. import org.apache.struts.action.ActionForm;
  6. import org.apache.struts.action.ActionForward;
  7. import org.apache.struts.action.ActionMapping;
  8. import javax.servlet.ServletContext;
  9. import javax.sql.DataSource;
  10. import java.sql.Connection;
  11. import java.sql.Statement;
  12. import java.sql.ResultSet;
  13. import java.sql.SQLException;
  14. import java.util.*;
  15. import javax.servlet.http.*;
  16. import org.apache.struts.validator.DynaValidatorForm;
  17. import org.apache.struts.action.ActionMessage;
  18. import org.apache.struts.action.ActionMessages;
  19. public final class NewsAddAction extends Action{  
  20. public ActionForward execute(
  21. ActionMapping mapping,
  22. ActionForm form,
  23. HttpServletRequest request,  
  24. HttpServletResponse response) throws Exception {
  25. //避免重复提交
  26. if (!isTokenValid(request)){
  27.   saveToken(request);
  28.   return (new ActionForward(mapping.getInput())); 
  29.   }
  30.   resetToken(request);
  31.  
  32.     DynaValidatorForm newsForm = (DynaValidatorForm) form;         
  33. String title = (String)newsForm.get("title");
  34. String content = (String)newsForm.get("content");
  35. String author = (String)newsForm.get("author");
  36. String keyword = (String)newsForm.get("keyword");
  37. Integer newsType = (Integer)newsForm.get("type");
  38.         HttpSession session = request.getSession();
  39. Vector newsList = new Vector();
  40.     ServletContext context = servlet.getServletContext();
  41. DataSource dataSource = 
  42. (DataSource)context.getAttribute(Constants.DATASOURCE_KEY);
  43.         DB db = new DB(dataSource);
  44.         
  45. String PageForward;
  46. News news=new News();
  47. news.setTitle(title);
  48. news.setContent(content);
  49. news.setAuthor(author);
  50. news.setKeyword(keyword);
  51. news.setType(newsType.intValue());
  52. ActionMessages errors = new ActionMessages();
  53. if (news.Insert(db)){
  54. newsList = News.SearchNewsTitle(db);
  55. session.setAttribute(Constants.NEWS_LIST_KEY,newsList);
  56. PageForward="toAdminMain";
  57. }
  58. else{
  59.             errors.add(ActionMessages.GLOBAL_MESSAGE,
  60.                            new ActionMessage("errors.insertFail"));
  61. if (!errors.isEmpty()) {
  62. saveErrors(request, errors);
  63.   PageForward="toWrong";  
  64. }
  65.    
  66. db.close();
  67.     return (mapping.findForward(PageForward));
  68.   }
  69. }