目录
一、项目结构描述
二、截图
三、关键代码
四、总结
operateServlet.java
package com.hedong.Control;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**1、这是操作中心,包括管理员登录、新闻的增删改查。
* 2、对于不同的操作,程序会去调用服务层的相应功能。
*/
/**
* Servlet implementation class operateServlet
*/
@WebServlet("/operateServlet")
public class operateServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public operateServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("utf-8");
PrintWriter out=response.getWriter();
//获取news参数和登录账号密码参数
String action=request.getParameter("action");
String myType=request.getParameter("newsType");
String myTitle=request.getParameter("newsTitle");
String myContent=request.getParameter("editorValue");
String writer=request.getParameter("newsWriter");
String myID=request.getParameter("newsID");
String User=request.getParameter("userName");
String Password=request.getParameter("passWord");
if(action.equals("add")) {
com.hedong.Service.NewsService newsService=new com.hedong.Service.NewsService();//调用服务层添加数据
newsService.InsertNews(myType,myTitle,myContent,writer);
response.sendRedirect("/NewsWebsite/GoPage?flag=showlist");//重新打开新闻管理页面
}else if(action.equals("dele")) {
com.hedong.Service.NewsService newsService=new com.hedong.Service.NewsService();//调用服务层删除数据
newsService.DeleteNews(myID);
response.sendRedirect("/NewsWebsite/GoPage?flag=showlist");//重新打开新闻管理页面
}else if(action.equals("edit")) {
com.hedong.Service.NewsService newsService=new com.hedong.Service.NewsService();//调用服务层获取数据
newsService.EditNews(myType,myTitle,myContent,writer,myID);
response.sendRedirect("/NewsWebsite/GoPage?flag=showlist");//重新打开新闻管理页面
}else if(action.equals("login")) {
com.hedong.Service.NewsService newsService=new com.hedong.Service.NewsService();//调用服务层判断数据
System.out.println(User+Password);
boolean isLogin=newsService.isUser(User,Password);
if(isLogin) {
//这个字符串将会在js中被接收
//1代表登录成功
//2代表用户名或密码为空
//3代表用户名或密码错误
request.getSession().setAttribute("user",User);
out.write("1");
}else if(User==""||Password==""){
out.write("2");
}else {
out.write("3");
}
out.close();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
DBHelper.java
package com.hedong.DAL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* 1、本类直接与MySQL相联系,包括数据库的连接、查询、更新、以及最后的释放。
*/
public class DBHelper {
// 此方法为获取数据库连接
public static Connection getConnection() {
Connection conn = null;
try {
String driver = "com.mysql.jdbc.Driver"; // 数据库驱动
String url = "jdbc:mysql://localhost:3306/dbnews?useUnicode=true&characterEncoding=UTF-8";//数据库
String user = "root"; // 用户名
String password = "root"; // 密码
Class.forName(driver);// 加载数据库驱动
if (null == conn) {
conn = DriverManager.getConnection(url, user, password);
}
} catch (ClassNotFoundException e) {
System.out.println("Sorry,can't find the Driver!");
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
/**
* 增删改【Add、Del、Update】
*
* @param sql
* @return int
*/
public static int executeNonQuery(String sql) {
int result = 0;
Connection conn = null;
Statement stmt = null;
try {
conn = getConnection();
stmt = conn.createStatement();
result = stmt.executeUpdate(sql);
} catch (SQLException err) {
err.printStackTrace();
free(null, stmt, conn);
} finally {
free(null, stmt, conn);
}
return result;
}
/**
* 增删改【Add、Delete、Update】
*
* @param sql
* @param obj
* @return int
*/
public static int executeNonQuery(String sql, Object... obj) {
int result = 0;
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
for (int i = 0; i < obj.length; i++) {
pstmt.setObject(i + 1, obj[i]);
}
result = pstmt.executeUpdate();
} catch (SQLException err) {
err.printStackTrace();
free(null, pstmt, conn);
} finally {
free(null, pstmt, conn);
}
return result;
}
/**
* 查【Query】
*
* @param sql
* @return ResultSet
*/
public static ResultSet executeQuery(String sql) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = getConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
} catch (SQLException err) {
err.printStackTrace();
free(rs, stmt, conn);
}
return rs;
}
/**
* 查【Query】
*
* @param sql
* @param obj
* @return ResultSet
*/
public static ResultSet executeQuery(String sql, Object... obj) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
for (int i = 0; i < obj.length; i++) {
pstmt.setObject(i + 1, obj[i]);
}
rs = pstmt.executeQuery();
} catch (SQLException err) {
err.printStackTrace();
free(rs, pstmt, conn);
}
return rs;
}
/**
* 改【edit】
*
* @param sql
* @param obj
* @return ResultSet
*/
public static int executeUpdate(String sql) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
int result=0;
try {
conn = getConnection();
stmt = conn.createStatement();
result = stmt.executeUpdate(sql);
} catch (SQLException err) {
err.printStackTrace();
free(rs, stmt, conn);
}
return result;
}
/**
* 判断记录是否存在
*
* @param sql
* @return Boolean
*/
public static Boolean isExist(String sql) {
ResultSet rs = null;
try {
rs = executeQuery(sql);
rs.last();
int count = rs.getRow();
if (count > 0) {
return true;
} else {
return false;
}
} catch (SQLException err) {
err.printStackTrace();
free(rs);
return false;
} finally {
free(rs);
}
}
/**
* 释放【ResultSet】资源
*
* @param rs
*/
public static void free(ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException err) {
err.printStackTrace();
}
}
/**
* 释放【Statement】资源
*
* @param st
*/
public static void free(Statement st) {
try {
if (st != null) {
st.close();
}
} catch (SQLException err) {
err.printStackTrace();
}
}
/**
* 释放【Connection】资源
*
* @param conn
*/
public static void free(Connection conn) {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException err) {
err.printStackTrace();
}
}
/**
* 释放所有数据资源
*
* @param rs
* @param st
* @param conn
*/
public static void free(ResultSet rs, Statement st, Connection conn) {
free(rs);
free(st);
free(conn);
}
}
NewsService.java
package com.hedong.Service;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
/**
* 1、服务层。包括新闻的增、删、改、查,以及用户账号密码验证。
*/
public class NewsService {
public void InsertNews(String myType,String myTitle,String myContent,String writer){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
String time= df.format(new Date());// new Date()为获取当前系统时间
String sql="insert into news_tb (newsType,newsTitle,newsContent,newsWriter,newsTime) values ('"+myType+"','"+myTitle+"','"+myContent+"','"+writer+"','"+time+"')";
int result= com.hedong.DAL.DBHelper.executeUpdate(sql);//调用数据修改层
if(result>0)
{
System.out.println("add sql over");
}
}
public void DeleteNews(String newsID){
String sql="delete from news_tb where newsID='"+newsID+"'";
int result= com.hedong.DAL.DBHelper.executeUpdate(sql);//调用数据修改层
if(result>0)
{
System.out.println("del sql over");
}
}
public void EditNews(String myType,String myTitle,String myContent,String writer,String myID){
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
String time= df.format(new Date());// new Date()为获取当前系统时间
String sql="update news_tb set newsType='"+myType+"',newsTitle='"+myTitle+"' , newsContent='"+myContent+"' , newsWriter='"+writer+"',newsTime='"+time+"' where newsID='"+myID+"'";
int result= com.hedong.DAL.DBHelper.executeUpdate(sql);//调用数据修改层
if(result>0)
{
System.out.println("edit sql over");
}
}
public boolean isUser(String user,String password) {
String sql="select * from login_tb where userID='"+user+"' and passWord='"+password+"'";
return com.hedong.DAL.DBHelper.isExist(sql);//调用数据判断层
}
public ArrayList QueryNews()
{
ArrayList arrNews=new ArrayList();
String sql="select * from news_tb ";
ResultSet rs= com.hedong.DAL.DBHelper.executeQuery(sql);//调用数据访问层
System.out.println("excuete sql over");
try {
while(rs.next())
{
com.hedong.Model.News model=new com.hedong.Model.News();
model.setNewsID(rs.getInt("newsID"));
model.setNewsType(rs.getString("newsType"));
model.setNewsTitle(rs.getString("newsTitle"));
model.setNewsContent(rs.getString("NewsContent"));
model.setNewsWriter(rs.getString("newsWriter"));
model.setNewsTime(rs.getDate("newsTime"));
arrNews.add(model);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return arrNews;
}
}