Implement front-end and back-end "tourism management system" based on mvc three component architecture
1. MVC three-tier architecture description
- 1.1. User Interface Layer, in which the User Interface Layer is used to display data and receive data input by users to provide an interface for user interaction
- 1.2. Business Logic Layer, in which the Business Logic Layer is the core part of the project and carries out business processing after receiving the user's request data
- 1.3. Data Access Layer, in which the Data Access Layer, also known as the data persistence layer, performs persistence operations on the data processed by the business logic layer
- 1.4. The three-tier architecture is the general idea of dividing the project structure. It does not clearly indicate how to divide the project structure. MVC can be regarded as the specific implementation of the three-tier architecture. MVC is usually used as the specific implementation of the web layer
- 1.5. Improve code reusability, maintainability and expansibility
2. Project development process analysis
- 2.1 transform project requirements into visible pictures (Art)
- 2.2. With the consent of the person in charge, submit it to the web front-end engineer and design it into html page and pure static page according to the picture
- 2.3. Back end Engineer (Java Engineer), transforming static website into dynamic website (website content can be managed through console)
- 2.4. In the background, add, delete, modify and query the database: maintain the data displayed to users
- 2.5. Front desk: query the content from the database and render it to the front desk: show the user the page and its data
3. The front and rear ends of the project are separated to realize the function
-
3.1. The back-end implementation functions include: login registration, add, delete, modify, query, pagination (number of pages displayed), multi condition search, user permission, filter, file upload (picture upload), technologies used: mvc and three-tier architecture
-
-3.2. The front-end implementation functions include (adding data to the front-end page in the background): navigation bar, search bar, rotation map, login and registration, and technologies used: H5 (layout), CSS (style), js (dynamic)
4. Project demonstration
- 4.1 background demonstration (GIF)
- 4.2. Foreground demonstration, adding data in the background, foreground display (GIF)
5. Build project structure
6. jar package used
- 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
- The link to download the relevant jar package has been provided: https://mvnrepository.com/
7. Database structure
-
7.1. Login registration (database)
-
7.2 merchant management
8. Registration login code (background)
- 8.1 background code (Registration + login)
- 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 background code (Registration + login)
- 8.1.2 dao layer
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 background code (Registration + login)
- 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 background code (Registration + login)
- 8.1.4. service layer
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 background code (Registration + login)
- 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 background code (Registration + login)
- 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 background code (Registration + login)
- 8.1.7 the servlet layer inherits a class of BaseServlet to realize registration and login
- Baseservlet (code)
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 background code (Registration + login)
- 8.1.8. A class registration and login in servlet layer
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('Registration succeeded!');"); out.write("location.href='"+req.getContextPath()+"/user/login'"); out.write("</script>"); out.close(); }else{ out.write("<script>"); out.write("alert('Registration failed. The second password is inconsistent!');"); out.write("location.href='"+req.getContextPath()+"/user/register'"); out.write("</script>"); out.close(); } }else if(userSer.password2(password2)){ out.write("<script>"); out.write("alert('Please enter: user name, real nickname, password');"); out.write("location.href='"+req.getContextPath()+"/user/register'"); out.write("</script>"); out.close(); }else if(userSer.username(username)){ out.write("<script>"); out.write("alert('Please enter: real name, secondary verification code and password');"); out.write("location.href='"+req.getContextPath()+"/user/register'"); out.write("</script>"); out.close(); }else if(userSer.userpassword(userpassword)){ out.write("<script>"); out.write("alert('Please enter: user name, secondary verification code, real name');"); out.write("location.href='"+req.getContextPath()+"/user/register'"); out.write("</script>"); out.close(); }else if(userSer.nickname(nickname)){ out.write("<script>"); out.write("alert('Please enter: user name, secondary verification code and password');"); out.write("location.href='"+req.getContextPath()+"/user/register'"); out.write("</script>"); out.close(); }else{ out.write("<script>"); out.write("alert('The registered content cannot be empty');"); 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('Login succeeded!');"); 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('Incorrect account or password, login failed!');"); 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('Please enter the login password');"); out.write("location.href='"+req.getContextPath()+"/user/login'"); out.write("</script>"); out.close(); }else if(userSer.userpassword(userpassword)){ out.write("<script>"); out.write("alert('Please enter login account');"); out.write("location.href='"+req.getContextPath()+"/user/login'"); out.write("</script>"); out.close(); }else{ out.write("<script>"); out.write("alert('Login information cannot be empty!');"); 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 background code (Registration + login)
- 8.1.9. login.jsp page (login)
<%@ 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>Document</title> <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">Tourism Management System -- Login entry</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="enter one user name"> </div> <div class="form-group"> <input type="password" name="userpassword" class="form-control" id="exampleInputPassword1" placeholder="Please input a password"> </div> <div style="clear: both;"> <input type="submit" value="Sign in" class="btn"> </div> <div style="clear: both;padding-top:20px;"> <a href="${rootPath }/user/register">register</a> <a style="float:right" href="${rootPath }">return</a> </div> </form> </div> </div> </body> </html>
- 8.10 background code (Registration + login)
- 8.1.10 register.jsp page (Registration)
<%@ 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>Document</title> <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">Tourism Management System -- register</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="enter one user name"> </div> <div class="form-group"> <input type="text" name="nickname" class="form-control" id="exampleInputEmail1" placeholder="Please enter a nickname"> </div> <div class="form-group"> <input type="password" name="userpassword" class="form-control" id="exampleInputPassword1" placeholder="Please input a password"> </div> <div class="form-group"> <input type="password" name="password2" class="form-control" id="exampleInputPassword1" placeholder="Secondary password verification"> </div> <div style="clear: both;"> <input type="submit" value="register" class="btn"> </div> <div style="clear: both;padding-top:20px;"> <a href="${rootPath }/user/login">Sign in</a> <a style="float:right" href="${rootPath }">return</a> </div> </form> </div> </div> </body> </html>
9. Add, delete, modify query page (background)
- 9.1 background code, merchant management (addition, deletion, modification, query page)
- 9.1.1 bean (entity class)
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 background code, merchant management (addition, deletion, modification, query page)
- 9.1.2 page
package com.bean; import java.util.ArrayList; import java.util.List; /** * The use method of this class must strictly follow the following process * 1 Calculated total records rowCount * 2 Initialize using the construction method with parameters, for example, page page1 = new page (3, 5, 57); * 3 Set the current page record page1.setList(list1); * * * @author Administrator * * @param <T> */ public class Page<T> { /** * Number of pages before the current page number */ private static final int BeforePageNumbCount = 4; /** * Number of pages after the current page number */ private static final int AfterPageNumbCount = 3; /** * Current page number */ private int currPage; /** * Total records */ private int rowCount; /** * Records per page * This parameter is the second parameter arg2 in limit arg1 and arg2 */ private int pageSize; /** * PageCount */ private int pageCount; /** * Previous page */ private int prevPageNumb; /** * Next page */ private int nextPageNumb; /** * Index of the first record on the current page * This variable is the first parameter arg1 of limit arg1 and arg2 */ private int currPageFirstRowIndex; /** * Current page record list */ private List<T> list; /** * Page number list to display the page number */ private List<Integer> pageButtonNumbs ; /** * Initialization, regardless of the number of list records * * @param _currPage * @param rowCount */ public Page(int _currPage, int _pageSize, int _rowCount){ this.pageSize = _pageSize; this.rowCount = _rowCount; // Calculate total pages this.pageCount = this.rowCount / this.pageSize; if(this.rowCount% this.pageSize !=0 ){ this.pageCount ++ ; } // Correct current page this.currPage = _currPage ; if(this.currPage< 1 ){ this.currPage = 1; } if(this.currPage > this.pageCount && this.pageCount > 0){ this.currPage = this.pageCount; } // Calculates the index of the first record on the current page this.currPageFirstRowIndex = (this.currPage-1)* this.pageSize ; // Calculate and correct previous and subsequent pages 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; } // Calculate page number button list 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 background code, merchant management (addition, deletion, modification, query page)
- 9.1.3 dao layer
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 background code, merchant management (addition, deletion, modification, query page)
- 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. Write and read the sql of the category list String sql = "select * from busi limit "+ limitArg1 + ","+ limitArg2 ; // 3 execute sql and return list BeanListHandler<BuSi> rsh = new BeanListHandler<>(BuSi.class); List<BuSi> list = qr1.query(sql, rsh); // list parameters_ page inside _page.setList(list); return _page; } @Override public int getCount() throws Exception { // TODO Auto-generated method stub // 1 get QueryRunner object QueryRunner qr1 = initQueryRunner(); // 2. Write and read the sql of the category list String sql = "select count(1) from busi "; // 3 execute sql and return list ScalarHandler<Long> rsh = new ScalarHandler<>(); int cnt1 = qr1.query(sql, rsh).intValue(); return cnt1; } }
- 9.4 background code, merchant management (addition, deletion, modification, query page)
- 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 background code, merchant management (addition, deletion, modification, query page)
- 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 get total records int rowCount = buSiDao.getCount(); // 2 initialize the Page object // Only the list variable is missing from the page1 object Page<BuSi> page1 = new Page(currPage,pageSize, rowCount); // 3 get the number of records on the current page page1 = buSiDao.pageList( page1 ); return page1; } }
- 9.6 background code, merchant management (addition, deletion, modification, query page)
- 9.1.6 servlet layer
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 background code, merchant management (addition, deletion, modification, query page)
- 9.1.7. Add.jsp (add page)
<%@ 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>Document</title> <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">Add merchant</h3> <form action="${APP_PATH}/buSi/addPost" method="post"> <div class="form-group"> <label for="user">Merchant Name:</label> <input type="text" class="form-control" name="sname" placeholder="Please enter the merchant name"> </div> <div class="form-group"> <label for="pass">contact number:</label> <input type="text" class="form-control" name="contact" placeholder="Please enter the contact number"> </div> <div class="form-group"> <label for="pass">Contact address:</label> <textarea class="form-control" rows="10" name="address"></textarea> </div> <div class="text-center"> <input type="submit" class="btn btn-primary" value="Submit"> <button type="reset" class="btn btn-default">Reset</button> </div> </form> </div> </body> </html>
- 9.8 background code, merchant management (addition, deletion, modification, query page)
- 9.1.8. Edit.jsp (modify page)
<%@ 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>Document</title> <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">Modify merchant</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">Modify merchant Name:</label> <input type="text" class="form-control" name="sname" value="${buSi.sname }"> </div> <div class="form-group"> <label for="pass">Modify contact number:</label> <input type="text" class="form-control" name="contact" value="${buSi.contact }"> </div> <div class="form-group"> <label for="pass">Modify contact address:</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="preservation"> <button type="reset" class="btn btn-default">Reset</button> </div> </form> </div> </body> </html>
- 9.10 background code, merchant management (addition, deletion, modification, query page)
- 9.1.10 list.jsp (display page)
<%@ 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>Document</title> <!-- Relative path to start searching relative to the location of the currently accessed file --> <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">Merchant list</h3> <div> <!-- Add and delete buttons --> <div style="float: right;margin: 10px 0px;"> <a class="btn btn-primary" href="${APP_PATH}/buSi/add">Add merchant</a> <a class="btn btn-primary" href="" id="delSelected">Delete selected</a> </div> </div> <table class="table table-bordered clearfix"> <tr class="success"> <th><input type="checkbox" id="firstCb"></th> <th>Merchant number</th> <th>Merchant name</th> <th>contact number</th> <th>Contact address</th> <th>operation</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 }">modify</a> <a class="btn btn-default btn-sm" href="${APP_PATH }/buSi/delete?id=${bs.id }">delete</a></td> </tr> </c:forEach> </table> <!-- Paging navigation --> <div> <!-- Paging navigation --> <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>A total of 100 records are displayed in 20 pages</span> </div> </div> </div> </body> </html>
10. Background code, file upload (picture upload)
- 10.1. utils, FileUploadUtils class
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 { /** * Parse the request of file upload form * * 1 Common control name is key * 2 File control name_url is the access address of the file * name_srcFileName Is the original name of the file * * @param req * @param charset * @return */ public static Map<String, String> parseUploadRequest(HttpServletRequest req, String charset) { // Initialization returns map1, which is used to store all values Map<String,String> map1 = new HashMap(); // Get ROOT folder String ROOTPath = getROOTPath(); // Define storage root folder String saveFolder = "upload"; String saveDirPath = ROOTPath + "\\"+ saveFolder ; // Path to dir String dirUrl = "/"+saveFolder+"/"; try { req.setCharacterEncoding(charset); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 3. Parse the request object to get list < fileitem > filist DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload fileUpload = new ServletFileUpload(factory); try { List<FileItem> fiList = fileUpload.parseRequest(req); for (FileItem fi1 : fiList) { // If this is a normal control if (fi1.isFormField()) { // fname == route_id String fname = fi1.getFieldName(); // fvalue == 1 String fvalue = fi1.getString( charset ); map1.put(fname, fvalue) ; } // If this is a file control else { // Control name property String fname = fi1.getFieldName(); // original file name String srcFileName = fi1.getName(); String fileUrl = dirUrl+ srcFileName ; map1.put(fname+"_url", fileUrl ); map1.put(fname+"_srcFileName" , srcFileName ) ; // Get input stream InputStream is = fi1.getInputStream(); String savePath = saveDirPath + "\\" + srcFileName; FileOutputStream os1 = new FileOutputStream(savePath); // The input stream is passed to the output stream 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; } /** * Get the ROOT path of the ROOT project of tomcat * @return */ private static String getROOTPath(){ // 1 get the ROOT path of the ROOT project String classesPath = FileUploadUtils.class.getResource("/").getPath(); File f1 = new File(classesPath); // Get the path of webapps folder of tomcat webappsPath String webappsPath = f1.getParentFile().getParentFile().getParentFile().getAbsolutePath(); String rootPath = webappsPath +"\\ROOT"; return rootPath; } }
11. Summary
11.1. Part of the function code of the tourism management system project has been sent, and the whole project link has been sent: Baidu online disk of tourism management system (extraction code: qm11)