第一步:创建实体类
创建beans包名,在其下创建3个实体类分别是:News、Sp、User
package beans;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import util.DBUtil;
public class Sp {
private String id;
private String photo;
private String spname;
private String spcontent;
private String flag;
private DBUtil db;
public Sp(){
db=new DBUtil();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getSpname() {
return spname;
}
public void setSpname(String spname) {
this.spname = spname;
}
public String getSpcontent() {
return spcontent;
}
public void setSpcontent(String spcontent) {
this.spcontent = spcontent;
}
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
//读取所有商品信息
public List<Map<String,String>> getAllSp(){
List<Map<String,String>> sp=null;//Map数组为空
String sql="select * from sp";//查询数据库语句
sp=db.getList(sql, null);
return sp;
}
//读取干果类所有商品
public List<Map<String,String>> getAllSp1(){
List<Map<String,String>> sp=null;//Map数组为空
String sql="select * from sp where flag='1'";//查询数据库语句
sp=db.getList(sql,null);
return sp;
}
//读取可乐类所有商品
public List<Map<String,String>> getAllSp2(){
List<Map<String,String>> sp=null;//Map数组为空
String sql="select * from sp where flag='2'";//查询数据库语句
sp=db.getList(sql,null);
return sp;
}
//读取鲜果牛奶类商品
public List<Map<String,String>> getAllSp3(){
List<Map<String,String>> sp=null;//Map数组为空
String sql="select * from sp where flag='3'";//查询数据库语句
sp=db.getList(sql,null);
return sp;
}
//读取冰淇凌类商品
public List<Map<String,String>> getAllSp4(){
List<Map<String,String>> sp=null;//Map数组为空
String sql="select * from sp where flag='4'";//查询数据库语句
sp=db.getList(sql,null);
return sp;
}
//读取辣条类商品
public List<Map<String,String>> getAllSp5(){
List<Map<String,String>> sp=null;//Map数组为空
String sql="select * from sp where flag='5'";//查询数据库语句
sp=db.getList(sql,null);
return sp;
}
//读取奶油类商品
public List<Map<String,String>> getAllSp6(){
List<Map<String,String>> sp=null;//Map数组为空
String sql="select * from sp where flag='6'";//查询数据库语句
sp=db.getList(sql,null);
return sp;
}
//读取饼干类商品
public List<Map<String,String>> getAllSp7(){
List<Map<String,String>> sp=null;//Map数组为空
String sql="select * from sp where flag='7'";//查询数据库语句
sp=db.getList(sql,null);
return sp;
}
//添加商品信息
public int addSp(){
int result=0;
String sql ="insert into sp values(null,?,?,?,?)";
String[] params={photo,spname,spcontent,flag};
result=db.update(sql, params);
return result;
}
//通过id读取商品信息
public Map<String,String> getSp(){
Map<String,String> sp=null;
String sql ="select * from sp where id=?";
String[] params={id};
sp=db.getMap(sql, params);
return sp;
}
//修改用户信息
public int updateSp(){
int result=0;
String sql="update sp set photo=?,spname=?,spcontent=?,flag=? where id=?";
String[] params={photo,spname,spcontent,flag,id};
result=db.update(sql, params);
return result;
}
//删除新闻信息
public int delSp(){
int result=0;
String sql ="delete from sp where id=?";
String[] params={id};
result=db.update(sql, params);
return result;
}
}
package beans;
import java.sql.Date;
import java.util.List;
import java.util.Map;
import util.DBUtil;
public class News {
private String id;
private String content;
private String newname;
private String newtime;
private String flag;
private String biaoti;
private DBUtil db;
public News(){
db=new DBUtil();
}
public String getId() {
return id;
}
public String getFlag() {
return flag;
}
public String getBiaoti() {
return biaoti;
}
public void setBiaoti(String biaoti) {
this.biaoti = biaoti;
}
public void setFlag(String flag) {
this.flag = flag;
}
public void setId(String id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getNewname() {
return newname;
}
public void setNewname(String newname) {
this.newname = newname;
}
public String getNewtime() {
return newtime;
}
public void setNewtime(String newtime) {
this.newtime = newtime;
}
//读取所有新闻信息
public List<Map<String,String>> getAllNews(){
List<Map<String,String>> news=null;//Map数组为空
String sql="select * from news";//查询数据库语句
news=db.getList(sql, null);
return news;
}
//添加新闻信息
public int addNew(){
int result=0;
String sql ="insert into news values(null,?,?,?,?,?)";
String[] params={biaoti,content,newname,newtime,flag};
result=db.update(sql, params);
return result;
}
//通过id读取新闻信息
public Map<String,String> getNew(){
Map<String,String> news=null;
String sql ="select * from news where id=?";
String[] params={id};
news=db.getMap(sql, params);
return news;
}
//修改新闻信息
public int updateNew(){
int result=0;
String sql="update news set biaoti=?,content=?,newname=?,flag=?where id=?";
String[] params={biaoti,content,newname,flag,id};
result=db.update(sql, params);
return result;
}
//删除新闻信息
public int delNew(){
int result=0;
String sql ="delete from news where id=?";
String[] params={id};
result=db.update(sql, params);
return result;
}
//根据新闻类型显示新闻
public List<Map<String,String>> getAllNews1(){
List<Map<String,String>> news=null;//Map数组为空
String sql="select * from news where flag='1'";//查询数据库语句
news=db.getList(sql,null);
return news;
}
public List<Map<String,String>> getAllNews2(){
List<Map<String,String>> news=null;//Map数组为空
String sql="select * from news where flag='2'";//查询数据库语句
news=db.getList(sql,null);
return news;
}
public List<Map<String,String>> getAllNews3(){
List<Map<String,String>> news=null;//Map数组为空
String sql="select * from news where flag='3'";//查询数据库语句
news=db.getList(sql,null);
return news;
}
}
package beans;
import java.util.List;
import java.util.Map;
import util.DBUtil;
public class User {
private String id;
private String adname;
private String adpass;
private DBUtil db;
public User(){
db=new DBUtil();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAdname() {
return adname;
}
public void setAdname(String adname) {
this.adname = adname;
}
public String getAdpass() {
return adpass;
}
public void setAdpass(String adpass) {
this.adpass = adpass;
}
//读取所有管理员信息
public List<Map<String,String>> getAllAdmin(){
List<Map<String,String>> admins=null;//Map数组为空
String sql="select * from admin";//查询数据库语句
admins=db.getList(sql, null);
return admins;
}
//查询用户是否存在
public boolean getUser(){
boolean exist=false;//Map数组为空
String sql="select * from admin where adname=? and adpass=?";//查询数据库语句
Map<String,String> m =db.getMap(sql, new String[]{adname,adpass});
if(m!=null){
exist=true;
}
return exist;
}
//添加用户信息
public int addAdmin(){
int result=0;
String sql ="insert into admin values(null,?,?)";
String[] params={adname,adpass};
result=db.update(sql, params);
return result;
}
//通过id读取用户信息
public Map<String,String> getAdmin(){
Map<String,String> admins=null;
String sql ="select * from admin where id=?";
String[] params={id};
admins=db.getMap(sql, params);
return admins;
}
//修改用户信息
public int updateAdmin(){
int result=0;
String sql="update admin set adname=?,adpass=? where id=?";
String[] params={adname,adpass,id};
result=db.update(sql, params);
return result;
}
//删除新闻信息
public int delAdmin(){
int result=0;
String sql ="delete from admin where id=?";
String[] params={id};
result=db.update(sql, params);
return result;
}
}
第二步:创建服务层
NewsController
package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import beans.News;
import beans.User;
@WebServlet("*.news")
public class NewsController extends HttpServlet {
private static final long serialVersionUID=1L;
/**
* Constructor of the object.
*/
public NewsController() {
super();
}
/**
* 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 {
doPost( request, response);
}
/**
* 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 {
request.setCharacterEncoding("utf-8");
String url=request.getServletPath();
if(url.equals("/index.news")){
HttpSession session = request.getSession();
if(session.getAttribute("adname")==null){
response.sendRedirect("login.html");
}else{
News News =new News();
request.setAttribute("news", News.getAllNews());//存储数据
request.getRequestDispatcher("admin_new.jsp").forward(request, response);}
}else if(url.equals("/add.news")){
//获取客户端传过来的值
String biaoti=request.getParameter("biaoti");
String content=request.getParameter("content");
String newname=request.getParameter("newname");
String flag=request.getParameter("flag");
News News=new News();
News.setBiaoti(biaoti);
News.setContent(content);
News.setNewname(newname);
News.setFlag(flag);
int r= News.addNew();//将新闻插入
if(r==1)
request.getRequestDispatcher("/index.news").forward(request, response);
else
request.getRequestDispatcher("failure.html").forward(request, response);
}else if(url.equals("/edit.news")){
String id=request.getParameter("id");
News News=new News();
News.setId(id);
request.setAttribute("news_update",News.getNew());
request.getRequestDispatcher("update_news.jsp").forward(request, response);
}else if(url.equals("/edit_do.news")){
String id=request.getParameter("id");
String biaoti=request.getParameter("biaoti");
String content=request.getParameter("content");
String newname=request.getParameter("newname");
String flag=request.getParameter("flag");
News News=new News();
News.setId(id);
News.setBiaoti(biaoti);
News.setFlag(flag);
News.setContent(content);
News.setNewname(newname);
int r=News.updateNew();
if(r==1)
request.getRequestDispatcher("/index.news").forward(request, response);
else
request.getRequestDispatcher("failure.html").forward(request, response);
}else if(url.equals("/del.news")){
String id =request.getParameter("id");
News News=new News();
News.setId(id);
int r=News.delNew();
if(r==1)
request.getRequestDispatcher("/index.news").forward(request, response);
else
request.getRequestDispatcher("failure.html").forward(request, response);
}else if(url.equals("/layout.news")){
HttpSession session = request.getSession();
session.removeAttribute("adname");
response.sendRedirect("login.html");
}
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
spController
package servlet;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import beans.Sp;
import beans.User;;
@WebServlet("*.sp")
@MultipartConfig
public class SpController extends HttpServlet {
private static final long serialVersionUID=1L;
/**
* Constructor of the object.
*/
public SpController() {
super();
}
/**
* 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 {
doPost( request, response);
}
/**
* 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 {
request.setCharacterEncoding("utf-8");
String url=request.getServletPath();
if(url.equals("/index.sp")){
HttpSession session = request.getSession();
if(session.getAttribute("adname")==null){
response.sendRedirect("login.html");
}else{
Sp sp=new Sp();
request.setAttribute("sp",sp.getAllSp());//存储数据
request.getRequestDispatcher("admin_sp.jsp").forward(request, response);}
}else if(url.equals("/layout.sp")){
HttpSession session = request.getSession();
session.removeAttribute("adname");
response.sendRedirect("login.html");
}
else if(url.equals("/add.sp")){
//获取客户端传过来的值
String photo=request.getParameter("photo");
String spname=request.getParameter("spname");
String spcontent=request.getParameter("spcontent");
String flag=request.getParameter("flag");
Sp sp=new Sp();
sp.setFlag(flag);
sp.setPhoto(photo);
sp.setSpcontent(spcontent);
sp.setSpname(spname);
//图片上传到指定文件夹;
// Part file = request.getPart("photo");
// PrintWriter out =response.getWriter();
// //从Part对象的头部信息中获得上传文件名
//
// String header=file.getHeader("content-disposition");
// //从上传文件名中分离出文件扩展名
// String filename=((header.split(";")[2]).split("=")[1]).replaceAll("\"","");
// String extname=filename.substring(filename.lastIndexOf(".")+1);
// //构造新文件名
// String newfilename =System.currentTimeMillis()+extname;
// //设置上传的地址
// String uploadpath= getServletContext().getRealPath("/img");
// try{
// file.write(uploadpath+File.separator+newfilename);
// out.println("上传成功");
// }catch(IOException e){
// out.println("上传失败");
// out.println("Error:"+e.toString());
// }
int r=sp.addSp();//将商品插入
if(r==1)
request.getRequestDispatcher("/index.sp").forward(request, response);
else
request.getRequestDispatcher("failure.html").forward(request, response);
}else if(url.equals("/edit.sp")){
String id=request.getParameter("id");
Sp sp=new Sp();
sp.setId(id);
request.setAttribute("sp_update",sp.getSp());
request.getRequestDispatcher("update_sp.jsp").forward(request, response);
}else if(url.equals("/edit_do.sp")){
String id=request.getParameter("id");
String photo=request.getParameter("photo");
String spname=request.getParameter("spname");
String spcontent=request.getParameter("spcontent");
String flag=request.getParameter("flag");
Sp sp=new Sp();
sp.setId(id);
sp.setFlag(flag);
sp.setPhoto(photo);
sp.setSpcontent(spcontent);
sp.setSpname(spname);
int r=sp.updateSp();
if(r==1)
request.getRequestDispatcher("/index.sp").forward(request, response);
else
request.getRequestDispatcher("failure.html").forward(request, response);
}else if(url.equals("/del.sp")){
String id =request.getParameter("id");
Sp sp=new Sp();
sp.setId(id);
int r=sp.delSp();
if(r==1)
request.getRequestDispatcher("/index.sp").forward(request, response);
else
request.getRequestDispatcher("failure.html").forward(request, response);
}
}
private String Int(String parameter) {
// TODO Auto-generated method stub
return null;
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
userController
package servlet;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import beans.User;;
@WebServlet("*.user")
public class UserController extends HttpServlet {
private static final long serialVersionUID=1L;
/**
* Constructor of the object.
*/
public UserController() {
super();
}
/**
* 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 {
doPost( request, response);
}
/**
* 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 {
request.setCharacterEncoding("utf-8");
String url=request.getServletPath();
if(url.equals("/index.user")){
HttpSession session = request.getSession();
if(session.getAttribute("adname")==null){
response.sendRedirect("login.html");
}else{
User user =new User();
request.setAttribute("user",user.getAllAdmin());//存储数据
request.getRequestDispatcher("admin_user.jsp").forward(request, response);}
}
else if(url.equals("/add.user")){
//获取客户端传过来的值
String adname=request.getParameter("adname");
String adpass=request.getParameter("adpass");
User user =new User();
user.setAdname(adname);
user.setAdpass(adpass);
int r=user.addAdmin();//将新闻插入
if(r==1)
request.getRequestDispatcher("/index.user").forward(request, response);
else
request.getRequestDispatcher("failure.html").forward(request, response);
}else if(url.equals("/login.user")){
String adname=request.getParameter("uname");
String adpass=request.getParameter("upass");
User user =new User();
user.setAdname(adname);
user.setAdpass(adpass);
boolean exist=user.getUser();
if(exist){
HttpSession session = request.getSession();
session.setAttribute("adname", adname);
request.getRequestDispatcher("/index.user").forward(request, response);
}else{
request.getRequestDispatcher("failure.html").forward(request, response);}
}else if(url.equals("/layout.user")){
HttpSession session = request.getSession();
session.removeAttribute("adname");
response.sendRedirect("login.html");
}
else if(url.equals("/edit.user")){
String id=request.getParameter("id");
User user=new User();
user.setId(id);
request.setAttribute("user_update",user.getAdmin());
request.getRequestDispatcher("update_user.jsp").forward(request, response);
}else if(url.equals("/edit_do.user")){
String id=request.getParameter("id");
String adname=request.getParameter("adname");
String adpass=request.getParameter("adpass");
User user=new User();
user.setId(id);
user.setAdname(adname);
user.setAdpass(adpass);
int r=user.updateAdmin();
if(r==1)
request.getRequestDispatcher("/index.user").forward(request, response);
else
request.getRequestDispatcher("failure.html").forward(request, response);
}else if(url.equals("/del.user")){
String id =request.getParameter("id");
User user=new User();
user.setId(id);
int r=user.delAdmin();
if(r==1)
request.getRequestDispatcher("/index.user").forward(request, response);
else
request.getRequestDispatcher("failure.html").forward(request, response);
}
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
第三步:连接数据库,创建DButil类
package util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DBUtil {
private String driver;
private String url;
private String username;
private String password;
private Connection con;
private PreparedStatement pstmt;
private ResultSet rs;
public void setDriver(String driver) {
this.driver = driver;
}
public void setUrl(String url) {
this.url = url;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
//构造方法,定义驱动程序连接用户名和密码信息
public DBUtil(){
driver="com.mysql.jdbc.Driver";
url="jdbc:mysql://localhost:3306/food?characterEncoding=utf8&serverTimezone=UTC";
username="root";
password="qPb12345";
}
//获取连接对象
private Connection getConnection(){
try{
Class.forName(driver);
con=DriverManager.getConnection(url, username, password);
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}
return con;
}
//获取语句对象
private PreparedStatement getPrepareStatement(String sql){
try{
pstmt=getConnection().prepareStatement(sql);
}catch(SQLException e){
e.printStackTrace();
}
return pstmt;
}
//给pstmtd的SQL语句设置参数
private void setParams(String sql ,String[] params){
pstmt=this.getPrepareStatement(sql);
if(params != null){
for(int i=0;i<params.length;i++){
try{
pstmt.setString(i+1, params[i]);
}catch(SQLException e){
e.printStackTrace();
}
}
}
}
//执行数据库查询操作将返回结果封装到List对象
public List<Map<String,String>> getList(String sql,String[] params){
List<Map<String,String>> list=new ArrayList<Map<String,String>>();
try{
this.setParams(sql, params);
ResultSet rs =pstmt.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
while(rs.next()){
Map<String,String> m = new HashMap<String,String>();
for(int i=1;i<=rsmd.getColumnCount();i++){
String colName=rsmd.getColumnName(i);
m.put(colName,rs.getString(colName));
}
list.add(m);
}
}catch(SQLException e){
e.printStackTrace();
}finally{
close();
}
return list;
}
//执行数据库查询操作时
public Map<String,String> getMap(String sql,String[] params){
List<Map<String,String>> list=getList(sql,params);
if(list.isEmpty())
return null;
else
return (Map<String,String>)list.get(0);
}
public boolean selBoolean(String sql) {
boolean flag=false;
try {
//1数据库访问
//2指定驱动2建立连接
Connection con = this.getConnection();
//3做命令对象
Statement st =con.createStatement();
//4执行命令
st.executeQuery("SET NAMES UTF8");
ResultSet rs =st.executeQuery(sql);
if(rs.next()){flag=true;}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flag;
}
//更新数据库时调用的 update 方法
public int update(String sql,String[] params) {
int recNo=0;
//表示受影响的记录行数
try{
//根据 sql语句和 params,设置 pstmt
setParams(sql,params);
recNo= pstmt.executeUpdate();//执行更新操作
}catch (Exception e) {
e.printStackTrace();
}finally{
close();}
return recNo;
}
//关闭对象
private void close(){
try{
if (rs != null)
rs.close();
if(pstmt != null)
pstmt.close();
if (con != null)
con.close();
}catch (SQLException e){
}
}}