如何添加信息传入到数据库?



1.在新闻列表页,点击添加。

新闻标题<input type="text" name="title" id="title" value=''/>
<button type="submit" class="page-btn">GO</button>
<button type="button" onclick="addNews();" class="page-btn">增加</button>
<input type="hidden" name="currentPageNo" value="1"/>
<input type="hidden" name="pageSize" value="10"/>

<input type="hidden" name="totalPageCount" value="2"/>

2、在新闻列表jsp中写跳转到 添加页;

<script>
  function addNews(){
  window.location="newsDetailCreateSimple.jsp";
  }

</script>


3、在添加页 的表单 action属性 改成 跳转到 doAdd.jsp页,该页面为了写 将数据传入到数据库的 逻辑代码

<!--实现添加数据  -->
<%
    request.setCharacterEncoding("utf-8");
int categoryId= Integer.parseInt(request.getParameter("categoryId"))  ;
String title= request.getParameter("title");
String author =request.getParameter("author");
String summary=request.getParameter("summary");
String content= request.getParameter("newscontent");

News news= new News();
news.setCategoryId(categoryId);
news.setTitle(title);
news.setAuthor(author);
news.setSummary(summary);
news.setContent(content);
news.setCreateDate(new Date());

 
  
boolean flag=newsService.add(news);

if(flag){%>
<jsp:forward  page="newsDetailList.jsp"/>

<%}else{%>
/* 如果添加失败,提示用户添加失败 */
<jsp:forward page="newsDetailCreateSimple.jsp"/>
<% }%>

Service层

//添加数据
public boolean add(News news);

service实现层

//添加数据
public boolean add(News news){
return newsDao.add(news) ;

}

dao层

//增
public boolean add(News news);

dao实现层

//增
@Override
public boolean add(News news) {
// TODO Auto-generated method stub
boolean flag=false;
String sql="insert into news_detail(id,  categoryId,  title,  summary,content,picPath,createDate) values(?,?,?,?,?,?,?)";
Object[] params={news.getId(),news.getCategoryId(),news.getTitle(),news.getSummary()
,news.getContent(),news.getPicPath(),news.getCreateDate()};
int i=this.executeUpdate(sql, params);
if(i>0){
System.out.println("添加成功");
flag=true;
}
return flag;

}

补充:公共方法 写在baseDao。java中

//增删改
public int executeUpdate(String sql ,Object [] params){
int updateRows=0;
if(this.getConnection()){
//获得sql语句
try {
ps=cnt.prepareStatement(sql);
//给占位符的赋值
for(int i=0;i<params.length;i++){
ps.setObject(i+1,params[i] );
}
//执行 增删改,返回影响的行数
updateRows=ps.executeUpdate();

} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

return updateRows;

}

猜你喜欢

转载自blog.csdn.net/java_stud/article/details/80541873