基于MVC三层架构实现旅游管理系统项目

基于mvc三成架构实现 “旅游管理系统”

1、MVC三层架构描述

  • 1.1、用户界面层(User Interface Layer),其中,用户界面层用来展示数据以及接收用户输入的数据,给用户的交互提供界面
  • 1.2、 业务逻辑层(Business Logic Layer),其中,业务逻辑层,是项目的核心部分,接收到用户请求数据之后进行业务处理
  • 1.3、 数据访问层(Data Access Layer),其中,数据访问层,又称为数据持久层,对业务逻辑层处理的数据进行持久化操作
  • 1.4、都是对项目进行分层、三层架构是对项目结构划分的大概的思路,没有明确指出如何具体划分、而MVC可以看做是对三层架构具体实现,通常使用MVC作为web层的具体实现
  • 1.5、提高代码的复用性、维护性、扩展性

2、项目开发流程分析

  • 2.1、把项目需求转变成看得见的图片(美工)
  • 2.2、.负责人同意之后,交给web前端工程师,根据图片设计成html页面,纯静态页面
  • 2.3、后端工程师(Java工程师),将静态的网站改造成动态网站(网站内容可以通过台进行管理)
  • 2.4、后台,对数据库进行增、删、改、查:维护给用户展示的数据
  • 2.5、前台,从数据库查询内容后渲染到前台:给用户展示页面及其数据

3、该项目前后端分离实现功能

  • 3.1、后端实现功能有:登录注册、增、删、改、查、分页(显示页数)、多条件搜索、用户权限、过滤器、文件上传(图片上传)、用到技术:mvc与三层架构、

  • -3.2、前端实现功能有(后台添加数据显示到前端页面上):导航栏、搜索栏、轮播图、登录注册、用到技术:H5(布局)、css(样式)、js(动态)

4、项目演示

  • 4.1、后台演示(GIF)

  • 4.2、前台演示,后台添加数据前台显示(GIF)

5、搭建项目结构

基于MVC三层架构实现旅游管理系统项目_第1张图片

6、用到的jar包

  • commons-dbutils-1.7.jar
  • commons-fileupload-1.4.jar
  • commons-io-2.6.jar
  • commons-lang-2.6.jar
  • druid-1.1.20.jar
  • jsoup-1.14.1.jar
  • jstl-1.2.jar
  • mysql-connector-java-5.1.49.jar
  • 下载相关jar包链接已提供:https://mvnrepository.com/

7、数据库结构

  • 7.1、登录注册(数据库)
    基于MVC三层架构实现旅游管理系统项目_第2张图片

  • 7.2、商家管理
    基于MVC三层架构实现旅游管理系统项目_第3张图片

8、注册登录代码(后台)

  • 8.1后台代码(注册+登录)
  • 8.1.1、bean
package com.bean;

public class UserHou {
	private Integer id;
	private String username;
	private String  userpwd;
	private String nickname;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getUserpwd() {
		return userpwd;
	}
	public void setUserpwd(String userpwd) {
		this.userpwd = userpwd;
	}
	public String getNickname() {
		return nickname;
	}
	public void setNickname(String nickname) {
		this.nickname = nickname;
	}
	
	
}

  • 8.2后台代码(注册+登录)
  • 8.1.2、dao层
package com.dao;

import java.util.List;

import com.bean.Role;
import com.bean.UserHou;

public interface UserHouDao {
	Integer register(String username,String userpwd,String nickname) throws  Exception;
	
	List<UserHou> list() throws Exception;
	List<UserHou> quer(String id, String username) throws Exception;
	
	Integer delete(String id) throws Exception;
	
	UserHou alterid(String id) throws Exception;
	Integer alterUserHou(UserHou userHou) throws Exception;
	
	
}

  • 8.3后台代码(注册+登录)
  • 8.1.3、dao.Impl
package com.dao.impl;


import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.alibaba.druid.util.StringUtils;
import com.bean.Role;
import com.bean.UserHou;
import com.dao.UserHouDao;


public class UserHouDaoImpl extends BaesDao implements UserHouDao{

	@Override
	public Integer register(String username, String userpwd, String nickname) throws Exception {
		// TODO Auto-generated method stub
		QueryRunner qr = initQueryRunner();
		String sql = "insert into t_admin_user(username,userpwd,nickname) values (?,?,?)";
		int i = qr.execute(sql,username,userpwd,nickname);
		return i;
	}

	@Override
	public List<UserHou> list() throws Exception {
		// TODO Auto-generated method stub
		QueryRunner qr = initQueryRunner();
		String sql = "select * from t_admin_user";
		List<UserHou> list = qr.query(sql, new BeanListHandler<UserHou>(UserHou.class));
		return list;
	}

	@Override
	public Integer delete(String id) throws Exception {
		// TODO Auto-generated method stub
		QueryRunner qr = initQueryRunner();
		String sql = "delete from t_admin_user where id = ?";
		int i = qr.execute(sql, id);
		return i;
	}

	@Override
	public List<UserHou> quer(String nickname, String username) throws Exception {
		// TODO Auto-generated method stub
		QueryRunner qr = initQueryRunner();
		String sql = "select * from t_admin_user";
		boolean booId = false;
		boolean booUsName = false;
		if(!StringUtils.isEmpty(nickname)){
			sql += " where nickname like '%"+nickname+"%'";
			booId = true;
		}
		if(!StringUtils.isEmpty(username)){
			if(booId){
				sql += " and username like '%"+username+"%'";
			}else{
				sql += " where username like '%"+username+"%'";
			}
			booUsName = true;
		}
		List<UserHou> quer = qr.query(sql, new BeanListHandler<UserHou>(UserHou.class));
		return quer;
	}

	@Override
	public UserHou alterid(String id) throws Exception {
		// TODO Auto-generated method stub
		QueryRunner qr = initQueryRunner();
		String sql = "select * from t_admin_user where id = ?";
		UserHou alterId = qr.query(sql, new BeanHandler<UserHou>(UserHou.class),id);
		return alterId;
	}

	@Override
	public Integer alterUserHou(UserHou userHou) throws Exception {
		// TODO Auto-generated method stub
		QueryRunner qr = initQueryRunner();
		String sql = "update t_admin_user set username = ?,nickname = ? where id = ?";
		int i = qr.execute(sql, userHou.getNickname(),userHou.getUsername(),userHou.getId());
		return i;
	}
}

  • 8.4后台代码(注册+登录)
  • 8.1.4、service层
package com.service;

import java.util.List;

import com.bean.Role;
import com.bean.UserHou;

public interface UserHouService {
	Integer register(String username,String userpwd,String password2,String nickname) throws Exception;
	
	boolean username(String username);
	boolean userpwd(String userpwd);
	boolean password2(String password2);
	boolean nickname(String nickname);
	
	List<UserHou> list() throws Exception;
	List<UserHou> quer(String id,String usernmae) throws Exception;
	
	UserHou alterId(String id) throws Exception;
	boolean alterUserHou(UserHou userHou) throws Exception;
	
	boolean delete(String id) throws Exception;
	
	
	
}

  • 8.5后台代码(注册+登录)
  • 8.1.5、service.impl
package com.service.impl;

import java.util.List;

import com.bean.Role;
import com.bean.UserHou;
import com.dao.RoleDao;
import com.dao.UserHouDao;
import com.dao.impl.RoleDaoImpl;
import com.dao.impl.UserHouDaoImpl;
import com.service.UserHouService;


public class UserServiceHouImpl implements UserHouService{
	private UserHouDao userHouDao = new UserHouDaoImpl();
	private RoleDao roleDao = new RoleDaoImpl();
	
	@Override
	public Integer register(String username, String userpwd,String password2, String nickname) throws Exception {
		// TODO Auto-generated method stub
		if(userpwd.equals(password2)){
			return userHouDao.register(username, userpwd, nickname);
		}else{
			return -1;
		}
		
	}

	@Override
	public boolean username(String username) {
		// TODO Auto-generated method stub
		if(username != null && !username.equals("")){
			return true;
		}
		return false;
	}

	@Override
	public boolean userpwd(String userpwd) {
		// TODO Auto-generated method stub
		if(userpwd != null && !userpwd.equals("")){
			return true;
		}
		return false;
	}

	@Override
	public boolean password2(String password2) {
		// TODO Auto-generated method stub
		if(password2 != null && !password2.equals("")){
			return true;
		}
		return false;
	}

	@Override
	public boolean nickname(String nickname) {
		// TODO Auto-generated method stub
		if(nickname != null && !nickname.equals("")){
			return true;
		}
		return false;
	}

	@Override
	public List<UserHou> list() throws Exception {
		// TODO Auto-generated method stub
		return userHouDao.list();
	}

	@Override
	public boolean delete(String id) throws Exception {
		// TODO Auto-generated method stub
		int i = userHouDao.delete(id);
		return i > 0;
	}

	@Override
	public List<UserHou> quer(String id, String usernmae) throws Exception {
		// TODO Auto-generated method stub
		return userHouDao.quer(id, usernmae);
	}

	@Override
	public UserHou alterId(String id) throws Exception {
		// TODO Auto-generated method stub
		return userHouDao.alterid(id);
	}

	@Override
	public boolean alterUserHou(UserHou userHou) throws Exception {
		// TODO Auto-generated method stub
		int i = userHouDao.alterUserHou(userHou);
		return i > 0;
	}
	

	
	
}

  • 8.6后台代码(注册+登录)
  • 8.1.6、Filter(过滤器)
package com.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebFilter("/*")
public class CharsetFilter implements Filter{

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest req = (HttpServletRequest) arg0;
		HttpServletResponse resp = (HttpServletResponse) arg1;
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		arg2.doFilter(arg0, arg1);
		
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}

  • 8.7后台代码(注册+登录)
  • 8.1.7、servlet层都继承BaseServlet一个类实现注册登录
  • BaseServlet(代码)
package com.web.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class BaseServlet extends HttpServlet{
	@Override
	protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String uri = arg0.getRequestURI();
		String methodName = uri.substring(uri.lastIndexOf("/")+1);
		try {
			Method m = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
			m.invoke(this, arg0,arg1);
		
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

  • 8.8后台代码(注册+登录)
  • 8.1.8、servlet层的一个类注册和登录
package com.web.servlet.home;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.bean.UserHome;
import com.service.UserService;
import com.service.impl.UserServiceImpl;
import com.web.servlet.BaseServlet;
@WebServlet("/user/*")
public class UserServlet extends BaseServlet{
	private UserService userSer = new UserServiceImpl();
	public void register(HttpServletRequest req,HttpServletResponse resp){
		try {
			req.getRequestDispatcher("/WEB-INF/user/register.jsp").forward(req, resp);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void registerPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException{
		String username = req.getParameter("username");
		String userpassword = req.getParameter("userpassword");
		String password2 = req.getParameter("password2");
		String nickname = req.getParameter("nickname");
		Integer icn = null;
		PrintWriter out = resp.getWriter();
		if(userSer.password2(password2)&&userSer.username(username) && userSer.userpassword(userpassword) && userSer.nickname(nickname)){
			try {
				 icn = userSer.register(username, userpassword, password2, nickname);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(icn > 0){
				out.write("<script>");
				out.write("alert('注册成功!');");
				out.write("location.href='"+req.getContextPath()+"/user/login'");
				out.write("script>");
				out.close();
			}else{
				out.write("<script>");
				out.write("alert('注册失败 二次密码不一致!');");
				out.write("location.href='"+req.getContextPath()+"/user/register'");
				out.write("script>");
				out.close();
			}
		}else if(userSer.password2(password2)){
			out.write("<script>");
			out.write("alert('请输入:用户名,真实昵称,密码');");
			out.write("location.href='"+req.getContextPath()+"/user/register'");
			out.write("script>");
			out.close();
			
		}else if(userSer.username(username)){
			out.write("<script>");
			out.write("alert('请输入:真实姓名,二次验证码,密码');");
			out.write("location.href='"+req.getContextPath()+"/user/register'");
			out.write("script>");
			out.close();
		}else if(userSer.userpassword(userpassword)){
			out.write("<script>");
			out.write("alert('请输入:用户名,二次验证码,真实姓名');");
			out.write("location.href='"+req.getContextPath()+"/user/register'");
			out.write("script>");
			out.close();
		}else if(userSer.nickname(nickname)){
			out.write("<script>");
			out.write("alert('请输入:用户名,二次验证码,密码');");
			out.write("location.href='"+req.getContextPath()+"/user/register'");
			out.write("script>");
			out.close();
		}else{
			out.write("<script>");
			out.write("alert('注册的内容不能为空');");
			out.write("location.href='"+req.getContextPath()+"/user/register'");
			out.write("script>");
			out.close();
		}
		
		
	}
	public void login(HttpServletRequest req,HttpServletResponse resp){
		try {
			req.getRequestDispatcher("/WEB-INF/user/login.jsp").forward(req, resp);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void loginPost(HttpServletRequest req,HttpServletResponse resp) throws IOException{
		String username = req.getParameter("username");
		String userpassword = req.getParameter("userpassword");
		PrintWriter out = resp.getWriter();
		if(userSer.username(username) && userSer.userpassword(userpassword)){
			try {
				UserHome user = userSer.login(username, userpassword);
				if(user != null){
					HttpSession hs = req.getSession();
					hs.setAttribute("user", user);
					out.write("<script>");
					out.write("alert('登录成功!');");
					out.write("location.href='"+req.getContextPath()+"/indexHome'");
					out.write("script>");
					out.close();
				}else{
					HttpSession hs = req.getSession();
					hs.setAttribute("user", user);
					out.write("<script>");
					out.write("alert('账号或密码有误登录失败!');");
					out.write("location.href='"+req.getContextPath()+"/user/login'");
					out.write("script>");
					out.close();
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}else if(userSer.username(username)){
			out.write("<script>");
			out.write("alert('请输入登录密码');");
			out.write("location.href='"+req.getContextPath()+"/user/login'");
			out.write("script>");
			out.close();
		}else if(userSer.userpassword(userpassword)){
			out.write("<script>");
			out.write("alert('请输入登录账号');");
			out.write("location.href='"+req.getContextPath()+"/user/login'");
			out.write("script>");
			out.close();
		}else{
			out.write("<script>");
			out.write("alert('登录信息不能为空!');");
			out.write("location.href='"+req.getContextPath()+"/user/login'");
			out.write("script>");
			out.close();
		}
		
	}
	
	public void logout(HttpServletRequest req,HttpServletResponse resp) throws IOException{
		req.getSession().removeAttribute("user");
		resp.sendRedirect(req.getContextPath()+"/indexHome");  
	}
	
	
	public void indexHome(HttpServletRequest req,HttpServletResponse resp){
		try {
			req.getRequestDispatcher("/WEB-INF/indexHome.jsp").forward(req, resp);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

  • 8.9后台代码(注册+登录)
  • 8.1.9、login.jsp页面(登录)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<% request.setAttribute("rootPath",request.getContextPath()); %>
 <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>  
DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documenttitle>
  
    <link rel="stylesheet" href="${rootPath }/css/bootstrap.min.css">

    <style>
        h3{
            font-size: 26px;
            color: #eee;
            margin: 0px auto 40px auto;
            text-align: center;
            font-weight: bold;
        }
        h3,label{
            color: #fff;
        }
        body{
            background-color: #2d3a4b;
        }
        .container{
            width: 400px;     
            margin: 200px auto;      
        }

        .capt-input{
            width: 50%;
            display: inline-block;
            margin-left: 20px;
        }

        .captcha{
            float: left;
            width: 20%;
            
        }
        .captcha-input{
            float: left;
        }
        .form-control{
            background: transparent;
            border:1px solid rgba(255, 255, 255, 0.1);
            height: 50px;
            color:#fff
        }
        .login input[type=submit]{
            width: 100%;
            background-color: #3a8ee6;
            border-color: #3a8ee6;
            color: #FFF;
            font-weight: 500;
            padding: 10px;
            font-size: 14px;
            border-radius: 4px;
        }
       
    style>
head>
<body>
    <div class="container">
        
        <h3 class="text-center">旅游管理系统 -- 登录入口h3> 
        <div class="login">
            <form action="${rootPath }/user/loginPost" method="POST">
                <div class="form-group">
                  <input type="text" name="username" class="form-control" id="exampleInputEmail1" placeholder="请输入用户名">
                div>
                <div class="form-group">
                  <input type="password" name="userpassword" class="form-control" id="exampleInputPassword1" placeholder="请输入密码">
                div>
                
                <div style="clear: both;">
                    <input type="submit" value="登录" class="btn">
                div>
                 <div style="clear: both;padding-top:20px;">
                 	
                 		<a href="${rootPath }/user/register">注册a>
	                    <a style="float:right" href="${rootPath }">返回a>
        
                div>
            form>
        div>
    div>
body>
html>
  • 8.10后台代码(注册+登录)
  • 8.1.10、register.jsp页面(注册)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
  <% request.setAttribute("rootPath",request.getContextPath()); %>
  <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>    
DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documenttitle>
    <link rel="stylesheet" href="${rootPath }/css/bootstrap.min.css">

    <style>
        h3{
            font-size: 26px;
            color: #eee;
            margin: 0px auto 40px auto;
            text-align: center;
            font-weight: bold;
        }
        h3,label{
            color: #fff;
        }
        body{
            background-color: #2d3a4b;
        }
        .container{
            width: 400px;     
            margin: 100px auto;      
        }

        .capt-input{
            width: 50%;
            display: inline-block;
            margin-left: 20px;
        }

        .captcha{
            float: left;
            width: 20%;
            
        }
        .captcha-input{
            float: left;
        }
        .form-control{
            background: transparent;
            border:1px solid rgba(255, 255, 255, 0.1);
            height: 50px;
            color:#fff
        }
        .login input[type=submit]{
            width: 100%;
            background: #3a8ee6;
            border-color: #3a8ee6;
            color: #FFF;
            font-weight: 500;
            padding: 10px;
            font-size: 14px;
            border-radius: 4px;
        }
       
    style>
head>
<body>
    <div class="container">
        
        <h3 class="text-center">旅游管理系统 -- 注册h3> 
        <div class="login">
            <form action="${pageContext.request.contextPath}/user/registerPost" method="post">
                <div class="form-group">
                  <input type="text" name="username" class="form-control" id="exampleInputEmail1" placeholder="请输入用户名">
                div>
                <div class="form-group">
                  <input type="text" name="nickname" class="form-control" id="exampleInputEmail1" placeholder="请输入昵称">
                div>
                <div class="form-group">
                  <input type="password" name="userpassword" class="form-control" id="exampleInputPassword1" placeholder="请输入密码">
                div>
                <div class="form-group">
                  <input type="password" name="password2" class="form-control" id="exampleInputPassword1" placeholder="二次密码验证">
                div>
              
                <div style="clear: both;">
                    <input type="submit" value="注册" class="btn">
                div>
                <div style="clear: both;padding-top:20px;">
                    <a href="${rootPath }/user/login">登录a>
                    <a style="float:right" href="${rootPath }">返回a>
                    
                div>
            form>
        div>
    div>
body>
html>

9、增删改查分页(后台)

  • 9.1、后台代码 ,商家管理(增删改查分页)
  • 9.1.1、bean(实体类)
package com.bean;

public class BuSi {
	private Integer id;
	private String sname;
	private String contact;
	private String address;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getSname() {
		return sname;
	}
	public void setSname(String sname) {
		this.sname = sname;
	}
	public String getContact() {
		return contact;
	}
	public void setContact(String contact) {
		this.contact = contact;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	
}

  • 9.2、后台代码 ,商家管理(增删改查分页)
  • 9.1.2、page(分页)
package com.bean;

import java.util.ArrayList;
import java.util.List;

/**
 * 该类的使用方法必须严格按照一下流程 
 * 1 计算得到 总记录数 rowCount
 * 2 使用带参构造方法初始化,例如 Page  page1 = new  Page(3, 5, 57 );
 * 3 设置当前页记录 page1.setList(list1 ); 
 * 
 * 
 * @author Administrator
 *
 * @param <T>
 */
public class Page<T> {
	
	/**
	 * 当前页码前的页码数
	 */
	private static final int BeforePageNumbCount =  4;
	
	/**
	 * 当前页码后的页码数
	 */
	private static final int AfterPageNumbCount = 3;
	
	/**
	 * 当前页码
	 */
	private int currPage;
	/**
	 * 总记录数
	 */
	private int rowCount;
	/**
	 * 每页记录数
	 * 该参数就是 limit arg1,arg2 中的第2个参数 arg2 
	 */
	private int pageSize;
	/**
	 * 总页数
	 */
	private int pageCount;
	/**
	 * 前1页页码
	 */
	private int prevPageNumb;
	/**
	 * 后一页页码
	 */
	private int nextPageNumb;
	
	/**
	 * 当前页的第1个条记录的索引
	 * 该变量就是 limit arg1,arg2 的第一个参数 arg1  
	 */
	private int currPageFirstRowIndex;
	/**
	 * 当前页记录列表
	 */
	private List<T> list;
	/**
	 * 页码列表 , 即可显示的页码
	 */
	private List<Integer> pageButtonNumbs ;
	
	/**
	 * 初始化,不考虑 列表记录数
	 * 
	 * @param _currPage
	 * @param rowCount
	 */
	public Page(int _currPage, int _pageSize, int _rowCount){
		
		this.pageSize = _pageSize;
		this.rowCount = _rowCount;
		
		// 计算总页数
		this.pageCount = this.rowCount / this.pageSize;
		if(this.rowCount% this.pageSize !=0 ){
			this.pageCount ++ ;
		}
		
		// 修正当前页
		this.currPage = _currPage ; 
		if(this.currPage< 1 ){
			this.currPage = 1;
		}
		
		if(this.currPage > this.pageCount && this.pageCount > 0){
			this.currPage = this.pageCount;
		}
		
		// 计算当前页第一条记录的索引
		this.currPageFirstRowIndex = (this.currPage-1)* this.pageSize ;
		
		// 计算并修正 前一页 和 后一页
		this.prevPageNumb = this.currPage - 1;
		this.nextPageNumb = this.currPage + 1;
		
		if(this.prevPageNumb<1){
			this.prevPageNumb = 1;
		}
		if(this.prevPageNumb>1 && this.prevPageNumb >= this.pageCount){
			this.prevPageNumb = this.pageCount-1;
		}
		if(this.nextPageNumb <= 1 ){
			this.nextPageNumb = 2;
		}
		if(this.nextPageNumb >1 && this.nextPageNumb > this.pageCount){
			this.nextPageNumb = this.pageCount;
		}
		
		// 计算 页码按钮 列表 
		this.pageButtonNumbs = new ArrayList();
		for( int i = this.currPage-4 ; i <= this.currPage+3 ;i++){
			if(i<1 || i> this.pageCount ){
				continue;
			}
			this.pageButtonNumbs.add(i);
		}
		
		
	}

	public List<T> getList() {
		return list;
	}

	public void setList(List<T> list) {
		this.list = list;
	}

	public int getCurrPage() {
		return currPage;
	}

	public int getRowCount() {
		return rowCount;
	}

	public int getPageSize() {
		return pageSize;
	}

	public int getPageCount() {
		return pageCount;
	}

	public int getPrevPageNumb() {
		return prevPageNumb;
	}

	public int getNextPageNumb() {
		return nextPageNumb;
	}

	public List<Integer> getPageButtonNumbs() {
		return pageButtonNumbs;
	}

	public int getCurrPageFirstRowIndex() {
		return currPageFirstRowIndex;
	}
	
	
	

}

  • 9.3、后台代码 ,商家管理(增删改查分页)
  • 9.1.3、dao层
package com.dao;

import java.util.List;

import com.bean.BuSi;
import com.bean.Category;
import com.bean.Page;


public interface BuSiDao {
	Integer addBuSi(BuSi busi) throws Exception;
	
	
	List<BuSi> lsitBuSi() throws Exception;
//	List<BuSi> page(int currPage,int pageSize) throws Exception;
//	Integer gerCount() throws Exception;
	Page<BuSi> pageList(Page<BuSi> _page ) throws Exception;
	int getCount() throws Exception;
	
	
	Integer deleteBuSiId(String id) throws Exception;
	
	BuSi alterBuSiId(String id) throws Exception;
	Integer alterBuSi(BuSi busi) throws Exception;
	
}

  • 9.4、后台代码 ,商家管理(增删改查分页)
  • 9.1.4、dao.impl
package com.dao.impl;

import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.bean.BuSi;

import com.bean.Page;
import com.dao.BuSiDao;

public class BuSiDaoImpl extends BaesDao implements BuSiDao{

	@Override
	public Integer addBuSi(BuSi busi) throws Exception {
		// TODO Auto-generated method stub
		QueryRunner qr = initQueryRunner();
		String sql = "insert into busi(sname,contact,address) values (?,?,?)";
		int i = qr.execute(sql, busi.getSname(),busi.getContact(),busi.getAddress());
		return i;
	}



	@Override
	public Integer deleteBuSiId(String id) throws Exception {
		// TODO Auto-generated method stub
		QueryRunner qr = initQueryRunner();
		String sql = "delete from busi where id = ?";
		int i = qr.execute(sql, id);
		return i;
	}

	@Override
	public BuSi alterBuSiId(String id) throws Exception {
		// TODO Auto-generated method stub
		QueryRunner qr = initQueryRunner();
		String sql = "select * from busi where id = ?";
		BuSi i = qr.query(sql, new BeanHandler<BuSi>(BuSi.class),id);
		return i;
	}

	@Override
	public Integer alterBuSi(BuSi busi) throws Exception {
		// TODO Auto-generated method stub
		QueryRunner qr = initQueryRunner();
		String sql = "update busi set sname = ?,contact = ?,address = ? where id = ?";
		int i = qr.execute(sql, busi.getSname(),busi.getContact(),busi.getAddress(),busi.getId());
		return i;
	}

	@Override
	public List<BuSi> lsitBuSi() throws Exception {
		// TODO Auto-generated method stub
		QueryRunner qr = initQueryRunner();
		String sql = "select * from busi";
		List<BuSi> listCategory = qr.query(sql, new BeanListHandler<BuSi>(BuSi.class));
		return listCategory;
	}

	@Override
	public Page<BuSi> pageList(Page<BuSi> _page) throws Exception {
		// TODO Auto-generated method stub
		QueryRunner qr1 = initQueryRunner();
		
		// limit arg1, arg2 : 
		int limitArg1 = _page.getCurrPageFirstRowIndex();
		int limitArg2 = _page.getPageSize();
		
		// 2 写 读取 category 列表的 sql 
		String sql = "select * from busi limit "+ limitArg1 + ","+ limitArg2 ;
		
		// 3 执行 sql 返回 list 
		BeanListHandler<BuSi> rsh = new BeanListHandler<>(BuSi.class);
	
		List<BuSi> list = qr1.query(sql, rsh); 
			
		// list 放到参数 _page 里面
		_page.setList(list);
		return _page;
	}

	@Override
	public int getCount() throws Exception {
		// TODO Auto-generated method stub
		// 1 获取 QueryRunner 对象
		QueryRunner qr1 = initQueryRunner();
		
		// 2 写 读取 category 列表的 sql 
		String sql = "select count(1) from busi ";
		
		// 3 执行 sql 返回 list 
		ScalarHandler<Long> rsh = new ScalarHandler<>();

		int cnt1 = qr1.query(sql, rsh).intValue(); 
		return cnt1;
	}

}

  • 9.4、后台代码 ,商家管理(增删改查分页)
  • 9.1.4、service
package com.service;

import java.util.List;

import com.bean.BuSi;
import com.bean.Page;

public interface BuSiService {
	boolean addBuSi(BuSi busi) throws Exception;
	
	List<BuSi> listBuSi() throws Exception;
//	List<BuSi> page(int currPage,int pageSize) throws Exception;
//	Integer getCount() throws Exception;
	Page<BuSi> page(int currPage, int pageSize ) throws Exception ;
	
	boolean deleteBuSi(String id) throws Exception;
	
	BuSi alterBuSiId(String id) throws Exception;
	boolean alterBuSi(BuSi buSi) throws Exception;
}

  • 9.5、后台代码 ,商家管理(增删改查分页)
  • 9.1.5、service.impl
package com.service.impl;

import java.util.List;

import com.bean.BuSi;
import com.bean.Category;
import com.bean.Page;
import com.dao.BuSiDao;
import com.dao.impl.BuSiDaoImpl;
import com.service.BuSiService;

public class BuSiServiceImpl implements BuSiService{
private BuSiDao buSiDao = new BuSiDaoImpl();
	@Override
	public boolean addBuSi(BuSi busi) throws Exception {
		// TODO Auto-generated method stub
		int i = buSiDao.addBuSi(busi);
		return i > 0;
	}
//	@Override
//	public List<BuSi> page(int currPage, int pageSize) throws Exception {
//		// TODO Auto-generated method stub
//		return buSiDao.page(currPage, pageSize);
//	}

	
	
	@Override
	public boolean deleteBuSi(String id) throws Exception {
		// TODO Auto-generated method stub
		int i = buSiDao.deleteBuSiId(id);
		return i > 0;
	}
	@Override
	public BuSi alterBuSiId(String id) throws Exception {
		// TODO Auto-generated method stub
		return buSiDao.alterBuSiId(id);
	}
	@Override
	public boolean alterBuSi(BuSi buSi) throws Exception {
		// TODO Auto-generated method stub
		int i = buSiDao.alterBuSi(buSi);
		return i > 0;
	}
	@Override
	public List<BuSi> listBuSi() throws Exception {
		// TODO Auto-generated method stub
		return buSiDao.lsitBuSi();
	}


	@Override
	public Page<BuSi> page(int currPage, int pageSize) throws Exception {
		// TODO Auto-generated method stub
		// 1 获取总记录数
		int rowCount = buSiDao.getCount();
		
		// 2 初始化 Page 对象
		// page1 对象里面只缺  list 变量 
		Page<BuSi> page1 = new Page(currPage,pageSize, rowCount);
		
		// 3  获取 当前页记录数
		page1 = buSiDao.pageList( page1 );
		
		return page1;
	}

}

  • 9.6、后台代码 ,商家管理(增删改查分页)
  • 9.1.6、servlet层
package com.web.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bean.BuSi;
import com.bean.Category;
import com.bean.Page;
import com.service.BuSiService;
import com.service.impl.BuSiServiceImpl;

@WebServlet("/buSi/*")
public class BuSiServlet extends BaseServlet{
	private BuSiService buSiService = new BuSiServiceImpl();
	public void add(HttpServletRequest req,HttpServletResponse resp){
		try {
			req.getRequestDispatcher("/WEB-INF/busi/add.jsp").forward(req, resp);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void addPost(HttpServletRequest req,HttpServletResponse resp){
		String sname = req.getParameter("sname");
		String contact = req.getParameter("contact");
		String address = req.getParameter("address");
		BuSi buSi = new BuSi();
		buSi.setSname(sname);
		buSi.setContact(contact);
		buSi.setAddress(address);
		try {
			if(buSiService.addBuSi(buSi)){
				resp.sendRedirect(req.getContextPath()+"/buSi/page");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	public void alter(HttpServletRequest req,HttpServletResponse resp){
		String id = req.getParameter("id");
		try {
			BuSi buSi = buSiService.alterBuSiId(id);
			req.setAttribute("buSi", buSi);
			req.getRequestDispatcher("/WEB-INF/busi/edit.jsp").forward(req, resp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	public void alterPost(HttpServletRequest req,HttpServletResponse resp){
		String id = req.getParameter("id");
		String sname = req.getParameter("sname");
		String contact = req.getParameter("contact");
		String address = req.getParameter("address");
		BuSi buSi = new BuSi();
		buSi.setId(Integer.valueOf(id));
		buSi.setSname(sname);
		buSi.setContact(contact);
		buSi.setAddress(address);
		try {
			if(buSiService.alterBuSi(buSi)){
				resp.sendRedirect(req.getContextPath()+"/buSi/page");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void delete(HttpServletRequest req,HttpServletResponse resp){
		
		String id = req.getParameter("id");
		try {
			if(buSiService.deleteBuSi(id)){
				resp.sendRedirect(req.getContextPath()+"/buSi/page");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public void page(HttpServletRequest req,HttpServletResponse resp){

		String strCurrPage = req.getParameter("currPage");
		int currPage = 1;
		if(strCurrPage !=null && !strCurrPage.equals("")){
			currPage = Integer.valueOf(strCurrPage);
		}
		
		
		try {

			int PageSize = 3;
			Page<BuSi> page1 = buSiService.page(currPage, PageSize);
			
			req.setAttribute("page1", page1); 
			req.getRequestDispatcher("/WEB-INF/busi/list.jsp").forward(req, resp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}

  • 9.7、后台代码 ,商家管理(增删改查分页)
  • 9.1.7、add.jsp(添加页面)
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>    
DOCTYPE html>
<html lang="en">
<head>
	<%
		request.setAttribute("APP_PATH", request.getContextPath());
	%>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documenttitle>
    <link rel="stylesheet" href="${APP_PATH}/bootstrap/css/bootstrap.min.css">
	<script src="${APP_PATH}/bootstrap/js/jquery-2.1.0.min.js">script>
	<script src="${APP_PATH}/bootstrap/js/bootstrap.min.js">script>
	<style type="text/css">
		.cus-container{
           width: 600px;
       }
	style>
head>
<body>
	<div class="container cus-container">
        <h3 class="text-center">添加商家h3>

        <form action="${APP_PATH}/buSi/addPost" method="post">
            <div class="form-group">
              <label for="user">商家名称:label>
              <input type="text" class="form-control" name="sname" placeholder="请输入商家名称">
            div>
            
            <div class="form-group">
              <label for="pass">联系电话:label>
              <input type="text" class="form-control" name="contact" placeholder="请输入联系电话">
            div>
            <div class="form-group">
              <label for="pass">联系地址:label>
              <textarea  class="form-control" rows="10" name="address">textarea>
             
            div>

            <div class="text-center">
                <input type="submit" class="btn btn-primary" value="提交">
                <button type="reset" class="btn btn-default">重置button>   
            div>         
          form>
       
    div>
body>
html>
  • 9.8、后台代码 ,商家管理(增删改查分页)
  • 9.1.8、edit.jsp(修改页面)
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>    
DOCTYPE html>
<html lang="en">
<head>
	<%
		request.setAttribute("APP_PATH", request.getContextPath());
	%>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documenttitle>
    <link rel="stylesheet" href="${APP_PATH}/bootstrap/css/bootstrap.min.css">
	<script src="${APP_PATH}/bootstrap/js/jquery-2.1.0.min.js">script>
	<script src="${APP_PATH}/bootstrap/js/bootstrap.min.js">script>
head>
<body>
	<div class="container cus-container">
        <h3 class="text-center">修改商家h3>
	
        <form action="${APP_PATH}/buSi/alterPost" method="post">
       	  <input type="hidden" class="form-control" name="id" value="${buSi.id }">
            <div class="form-group">
              <label for="user">修改商家名称:label>
              <input type="text" class="form-control" name="sname"  value="${buSi.sname }">
            div>
            
            <div class="form-group">
              <label for="pass">修改联系电话:label>
              <input type="text" class="form-control" name="contact" value="${buSi.contact }">
            div>
            <div class="form-group">
              <label for="pass">修改联系地址:label>
              <textarea  class="form-control" rows="10" name="address" >${buSi.address }textarea>
             
            div>

            <div class="text-center">
                <input type="submit" class="btn btn-primary" value="保存">
                <button type="reset" class="btn btn-default">重置button>   
            div>         
          form>
       
    div>
body>
html>
  • 9.10、后台代码 ,商家管理(增删改查分页)
  • 9.1.10、list.jsp(展示页面)
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%> 
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>    
DOCTYPE html>
<html lang="en">
<head>
	<%
		request.setAttribute("APP_PATH", request.getContextPath());
	%>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documenttitle>
    
    <link rel="stylesheet" href="${APP_PATH}/bootstrap/css/bootstrap.min.css">
    <style>
       .cus-container{
           width: 100%;
       }
       
    style>
head>
<body>
   
    <div class="container cus-container">
    	
        <h3 class="text-center">商家列表h3>

        <div>
           
            
            <div style="float: right;margin: 10px 0px;">
                <a class="btn btn-primary" href="${APP_PATH}/buSi/add">添加商家a>
                <a class="btn btn-primary" href="" id="delSelected">删除选中a>
            div>
        div>

      
       <table class="table table-bordered clearfix">
        <tr class="success">
            <th><input type="checkbox" id="firstCb">th>
            <th>商家编号th>
            <th>商家名称th>
            <th>联系电话th>
            <th>联系地址th>
            
            <th>操作th>
        tr>        
        
     <c:forEach items="${page1.list}" var="bs">
     	<tr>
     		<td><input type="checkbox" name="gid" value="">td>
            <td>${bs.id }td>
            <td>${bs.sname }td>
            <td>${bs.contact }td>
            <td>${bs.address }td>
            <td><a class="btn btn-default btn-sm" href="${APP_PATH }/buSi/alter?id=${bs.id }">修改a> 
                <a class="btn btn-default btn-sm" href="${APP_PATH }/buSi/delete?id=${bs.id }">删除a>td>
        tr>
     c:forEach>
        
       
      table>

    
      <div>
          
        <nav style="float: left;">
            <ul class="pagination">
              <li>
                <a href="?currPage=${page1.prevPageNumb }" aria-label="Previous">
                  <span aria-hidden="true">«span>
                a>
              li>
              <c:forEach items="${page1.pageButtonNumbs }" var ="numb">
              <c:if test="${ numb != page1.currPage }"> <li><a href="?currPage=${ numb }"> ${numb }a>li> c:if>
              <c:if test="${ numb == page1.currPage }"> <li><a style="color: red"> ${numb }a>li> c:if>
              c:forEach>
             
              <li>
                <a href="?currPage=${page1.nextPageNumb }" aria-label="Next">
                  <span aria-hidden="true">»span>
                a>
              li>
            ul>
        nav>
        <div style="float: right;margin-top: 25px;">
            <span>共100条记录,分20页显示span>
        div>
      div>
    div>
body>
html>

10、后台代码 ,文件上传(图片上传)

  • 10.1、utils, FileUploadUtils类
package com.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploadUtils {

	/**
	 * 解析文件上传表单的request 
	 * 
	 * 1 普通控件 name 就是 key 
	 * 2 文件控件 name_url 是 文件的访问地址
	 *          name_srcFileName 是文件的原名 
	 * 
	 * @param req
	 * @param charset
	 * @return
	 */
	public static Map<String, String> parseUploadRequest(HttpServletRequest req, String charset) {

		// 初始化 返回 map1 ,用于存储所有的 值
		Map<String,String> map1 = new HashMap();
		
		
		// 获取 ROOT 根文件夹 
		String ROOTPath = getROOTPath();
		
		// 定义 存储 根文件夹
		String saveFolder = "upload";
		
		String saveDirPath = ROOTPath + "\\"+ saveFolder ; 
		
		// dir 的 路径 
		String dirUrl  = "/"+saveFolder+"/";
		
		try {
			req.setCharacterEncoding(charset);

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

		// 3 解析 request 对象,得到 List<FileItem> fiList
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload fileUpload = new ServletFileUpload(factory);

		try {
			List<FileItem> fiList = fileUpload.parseRequest(req);

			for (FileItem fi1 : fiList) {

				// 如果这是一个 普通控件的话
				if (fi1.isFormField()) {

					// fname == route_id
					String fname = fi1.getFieldName();
					// fvalue == 1
					String fvalue = fi1.getString( charset );

					map1.put(fname, fvalue) ;

				}
				// 如果这是一个 file 控件的话
				else {

					// 控件 name 属性
					String fname = fi1.getFieldName();
					
					// 原文件名
					String srcFileName = fi1.getName();
					
					String fileUrl = dirUrl+ srcFileName ; 
					
					map1.put(fname+"_url", fileUrl );
					map1.put(fname+"_srcFileName" ,  srcFileName ) ;

					// 获得输入流
					InputStream is = fi1.getInputStream();

					String savePath = saveDirPath + "\\" + srcFileName;

					FileOutputStream os1 = new FileOutputStream(savePath);

					// 输入流 传递到 输出流

					byte[] bs1 = new byte[10240];
					while (true) {
						int len = is.read(bs1, 0, bs1.length);
						if (len < 0) {
							break;
						}

						os1.write(bs1, 0, len);

					}

					os1.close();
					is.close();

				}

			}

		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return map1;

	}
	
	/**
	 * 获取 tomcat 的 ROOT 项目的根路径
	 * @return
	 */
	private static String getROOTPath(){
		
		// 1 获得 ROOT项目的根路径 rootPath 
		String classesPath = FileUploadUtils.class.getResource("/").getPath();
		File f1 = new File(classesPath);
		
		// 获得 tomcat 的 webapps 文件夹的路径  webappsPath
		String webappsPath = f1.getParentFile().getParentFile().getParentFile().getAbsolutePath();
		String rootPath = webappsPath +"\\ROOT";
		
		return rootPath;
		
	}

}

11、总结

11.1、旅游管理系统项目的功能代码发出了一部分,整个此项目链接已发送:旅游管理系统百度网盘(提取码:qm11)
带数据库

你可能感兴趣的:(MVC与三层架构项目,mvc,架构,前端,后端,java)