目录
1.功能介绍
2.工程准备
2.1pom.xml
2.2mybatis-config.xml
2.3SqlSessionFactoryUtils
2.4CheckCodeUtil
3.注册页面
3.1User
3.2UserMapper.xml
3.3UserMapper
3.4UserService
3.5register.html
3.6RegisterServlet
3.7CheckCodeServlet
4.登录页面
4.1login.html
4.2LoginServlet
4.3LoginFilter
5.后台主页面
5.1Brand
5.2BrandMapper
5.3BrandMapper.xml
5.4BrandService
5.5BrandServiceImpl
5.6BaseServlet
5.7BrandServlet
5.8PageBean
5.9brand.html
6.工程结构
7.代码下载
JavaWeb 综合案例
黑马程序员视频链接: 01-综合案例-环境搭建_哔哩哔哩_bilibili
1.功能介绍
所用技术及工具:Mybatis+Maven+Filter+Ajax+JSON+JavaScript+HTML+CSS+Element+VUE
2.工程准备
注:该项目的Tomcat启动地址应设为下图所示:
Maven配置:
4.0.0
org.example
brand-case
1.0-SNAPSHOT
war
8
8
javax.servlet
javax.servlet-api
3.1.0
provided
org.mybatis
mybatis
3.5.5
mysql
mysql-connector-java
5.1.34
com.alibaba
fastjson
1.2.62
org.apache.tomcat.maven
tomcat7-maven-plugin
2.2
Mybatis配置:
package com.util;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
//通过mybatis操作数据库的工具类,里面封装了对数据库的操作
//只能使用一次,一旦创建后可以重复使用
public class SqlSessionFactoryUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
//静态代码块会随着类的加载而自动执行,且只执行一次
try {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSessionFactory getSqlSessionFactory(){
return sqlSessionFactory;
}
}
验证码生成工具类:
package com.util;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Arrays;
import java.util.Random;
/**
* 生成验证码工具类
*/
public class CheckCodeUtil {
public static final String VERIFY_CODES = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static Random random = new Random();
public static void main(String[] args) throws Exception {
//调用主方法,在D盘产生名为a的验证码图片,并在服务端打印验证码内容
OutputStream fos=new FileOutputStream("d://a.jpg");
String s = CheckCodeUtil.outputVerifyImage(100, 50, fos, 4);
System.out.println(s);
//此为CheckCodeServlet写入,在jsp中可直接调用
// 如:“”
//ServletOutputStream os = response.getOutputStream();
//String s = CheckCodeUtil.outputVerifyImage(100, 50, os, 4);
}
/**
* 输出随机验证码图片流,并返回验证码值(一般传入输出流,响应response页面端,Web项目用的较多)
*
* @param width 图片宽度
* @param height 图片高度
* @param os 输出流
* @param verifySize 数据长度
* @return 验证码数据
* @throws IOException
*/
public static String outputVerifyImage(int width, int height, OutputStream os, int verifySize) throws IOException {
String verifyCode = generateVerifyCode(verifySize);
outputImage(width, height, os, verifyCode);
return verifyCode;
}
/**
* 使用系统默认字符源生成验证码
*
* @param verifySize 验证码长度
* @return
*/
public static String generateVerifyCode(int verifySize) {
return generateVerifyCode(verifySize, VERIFY_CODES);
}
/**
* 使用指定源生成验证码
*
* @param verifySize 验证码长度
* @param sources 验证码字符源
* @return
*/
public static String generateVerifyCode(int verifySize, String sources) {
// 未设定展示源的字码,赋默认值大写字母+数字
if (sources == null || sources.length() == 0) {
sources = VERIFY_CODES;
}
int codesLen = sources.length();
Random rand = new Random(System.currentTimeMillis());
StringBuilder verifyCode = new StringBuilder(verifySize);
for (int i = 0; i < verifySize; i++) {
verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
}
return verifyCode.toString();
}
/**
* 生成随机验证码文件,并返回验证码值 (生成图片形式,用的较少)
*
* @param w
* @param h
* @param outputFile
* @param verifySize
* @return
* @throws IOException
*/
public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException {
String verifyCode = generateVerifyCode(verifySize);
outputImage(w, h, outputFile, verifyCode);
return verifyCode;
}
/**
* 生成指定验证码图像文件
*
* @param w
* @param h
* @param outputFile
* @param code
* @throws IOException
*/
public static void outputImage(int w, int h, File outputFile, String code) throws IOException {
if (outputFile == null) {
return;
}
File dir = outputFile.getParentFile();
//文件不存在
if (!dir.exists()) {
//创建
dir.mkdirs();
}
try {
outputFile.createNewFile();
FileOutputStream fos = new FileOutputStream(outputFile);
outputImage(w, h, fos, code);
fos.close();
} catch (IOException e) {
throw e;
}
}
/**
* 输出指定验证码图片流
*
* @param w
* @param h
* @param os
* @param code
* @throws IOException
*/
public static void outputImage(int w, int h, OutputStream os, String code) throws IOException {
int verifySize = code.length();
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Random rand = new Random();
Graphics2D g2 = image.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// 创建颜色集合,使用java.awt包下的类
Color[] colors = new Color[5];
Color[] colorSpaces = new Color[]{Color.WHITE, Color.CYAN,
Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
Color.PINK, Color.YELLOW};
float[] fractions = new float[colors.length];
for (int i = 0; i < colors.length; i++) {
colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
fractions[i] = rand.nextFloat();
}
Arrays.sort(fractions);
// 设置边框色
g2.setColor(Color.GRAY);
g2.fillRect(0, 0, w, h);
Color c = getRandColor(200, 250);
// 设置背景色
g2.setColor(c);
g2.fillRect(0, 2, w, h - 4);
// 绘制干扰线
Random random = new Random();
// 设置线条的颜色
g2.setColor(getRandColor(160, 200));
for (int i = 0; i < 20; i++) {
int x = random.nextInt(w - 1);
int y = random.nextInt(h - 1);
int xl = random.nextInt(6) + 1;
int yl = random.nextInt(12) + 1;
g2.drawLine(x, y, x + xl + 40, y + yl + 20);
}
// 添加噪点
// 噪声率
float yawpRate = 0.05f;
int area = (int) (yawpRate * w * h);
for (int i = 0; i < area; i++) {
int x = random.nextInt(w);
int y = random.nextInt(h);
// 获取随机颜色
int rgb = getRandomIntColor();
image.setRGB(x, y, rgb);
}
// 添加图片扭曲
shear(g2, w, h, c);
g2.setColor(getRandColor(100, 160));
int fontSize = h - 4;
Font font = new Font("Algerian", Font.ITALIC, fontSize);
g2.setFont(font);
char[] chars = code.toCharArray();
for (int i = 0; i < verifySize; i++) {
AffineTransform affine = new AffineTransform();
affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize / 2, h / 2);
g2.setTransform(affine);
g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);
}
g2.dispose();
ImageIO.write(image, "jpg", os);
}
/**
* 随机颜色
*
* @param fc
* @param bc
* @return
*/
private static Color getRandColor(int fc, int bc) {
if (fc > 255) {
fc = 255;
}
if (bc > 255) {
bc = 255;
}
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
private static int getRandomIntColor() {
int[] rgb = getRandomRgb();
int color = 0;
for (int c : rgb) {
color = color << 8;
color = color | c;
}
return color;
}
private static int[] getRandomRgb() {
int[] rgb = new int[3];
for (int i = 0; i < 3; i++) {
rgb[i] = random.nextInt(255);
}
return rgb;
}
private static void shear(Graphics g, int w1, int h1, Color color) {
shearX(g, w1, h1, color);
shearY(g, w1, h1, color);
}
private static void shearX(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(2);
boolean borderGap = true;
int frames = 1;
int phase = random.nextInt(2);
for (int i = 0; i < h1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(0, i, w1, 1, (int) d, 0);
if (borderGap) {
g.setColor(color);
g.drawLine((int) d, i, 0, i);
g.drawLine((int) d + w1, i, w1, i);
}
}
}
private static void shearY(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(40) + 10; // 50;
boolean borderGap = true;
int frames = 20;
int phase = 7;
for (int i = 0; i < w1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(i, 0, 1, h1, 0, (int) d);
if (borderGap) {
g.setColor(color);
g.drawLine(i, (int) d, i, 0);
g.drawLine(i, (int) d + h1, i, h1);
}
}
}
}
3.注册页面
package com.pojo;
public class User {
private Integer id;
private String username;
private String password;
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
package com.mapper;
import com.pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
public interface UserMapper {
/**
* 根据用户名和密码查询用户对象
* @param username
* @param password
* @return
*/
@Select("select * from tb_user where username = #{username} and password = #{password}")
User select(@Param("username") String username, @Param("password") String password);
/**
* 根据用户名查询用户对象
* @param username
* @return
*/
@Select("select * from tb_user where username = #{username}")
User selectByUsername(String username);
/**
* 添加用户
* @param user
*/
@Insert("insert into tb_user values(null,#{username},#{password})")
void add(User user);
}
package com.service;
import com.mapper.UserMapper;
import com.pojo.User;
import com.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
public class UserService {
SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
/**
* 登录方法
* @param username
* @param password
* @return
*/
public User login(String username, String password) {
// 2.获取SqlSession
SqlSession sqlSession = factory.openSession();
// 3.获取UserMapper
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.select(username, password);
// 释放资源
sqlSession.close();
return user;
}
/**
* 注册方法
* @param user
* @return
*/
public boolean register(User user) {
// 2.获取SqlSession
SqlSession sqlSession = factory.openSession();
// 3.获取UserMapper
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// 4.判断用户名是否存在
User u = mapper.selectByUsername(user.getUsername());
if(u == null){
// 用户名不存在
mapper.add(user);
// 提交事务
sqlSession.commit();
}
sqlSession.close();
return u == null;
}
}
欢迎注册
package com.web.servlet;
import com.pojo.User;
import com.service.UserService;
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 java.io.IOException;
@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
/**
* 注册验证
*/
private UserService service = new UserService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1.获取用户名和密码数据
String username = request.getParameter("username");
String password = request.getParameter("password");
User user = new User();
user.setUsername(username);
user.setPassword(password);
// 获取用户输入验证码
String checkCode = request.getParameter("checkCode");
// 程序生成的验证码
HttpSession session = request.getSession();
String checkCodeGen = (String) session.getAttribute("checkCodeGen");
// 比对
if(!checkCodeGen.equalsIgnoreCase(checkCode)){
response.getWriter().write("1");
// 不允许注册
return;
}
// 2.调用service 注册
boolean flag = service.register(user);
// 3.判断注册成功与否
if(flag){
// 注册成功 跳转登陆页面
response.getWriter().write("success");
}else {
// 注册失败 跳转到注册页面
response.getWriter().write("error");
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
package com.web.servlet;
import com.util.CheckCodeUtil;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
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 java.io.IOException;
@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
// 生成验证码
ServletOutputStream os = response.getOutputStream();
String checkCode = CheckCodeUtil.outputVerifyImage(100, 50, os, 4);
// 存入Session
session.setAttribute("checkCodeGen",checkCode);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
4.登录页面
login
package com.web.servlet;
import com.pojo.User;
import com.service.UserService;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
/**
* 登录验证
*/
private UserService service = new UserService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1.获取用户名密码
String username = request.getParameter("username");
String password = request.getParameter("password");
// 获取复选框数据
String remember = request.getParameter("remember");
// 2.调用service查询
User user = service.login(username,password);
// 3.判断
if(user != null){
// 登陆成功 跳转到查询所有的BrandServlet
// 判断用户是否勾选记住我 空指针异常
if("true".equals(remember)){
// 勾选了 发送Cookie
// 1.创建Cookie对象
Cookie c_username = new Cookie("username",username);
Cookie c_password = new Cookie("password",password);
// 设置Cookie存活时间
c_username.setMaxAge(60 * 60 * 24 * 7);
c_password.setMaxAge(60 * 60 * 24 * 7);
// 2.发送
response.addCookie(c_username);
response.addCookie(c_password);
}
// 将登陆成功后的User对象 存储到session
HttpSession session = request.getSession();
session.setAttribute("user",user);
response.getWriter().write("success");
}else {
// 登陆失败
response.getWriter().write("error");
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
package com.web.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
/**
* 登陆验证的过滤器
*/
@WebFilter("/*")
public class LoginFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
HttpServletRequest req = (HttpServletRequest) request;
// 判断访问路径资源是否和登陆注册相关
String[] urls = {"login.html","/element-ui/","/imgs/","/css/","/js/","/loginServlet","register.html","/registerServlet","/checkCodeServlet"};
// 获取当前访问的资源路径
String url = req.getRequestURL().toString();
// 循环判断
for (String u : urls) {
if(url.contains(u)){
// 找到了
// 放行
chain.doFilter(request, response);
return;
}
}
// 1.判断session中是否有user
HttpSession session = req.getSession();
Object user = session.getAttribute("user");
// 2.判断user是否为null
if(user !=null){
// 登陆过了
// 放行
chain.doFilter(request, response);
}else {
// 没有登陆 存储提示信息 跳转到登陆页面
//req.getRequestDispatcher("/login.html").forward(req,response);
req.getRequestDispatcher("/login.html?"+System.currentTimeMillis()).forward(req,response);
}
}
public void init(FilterConfig config) throws ServletException {
}
public void destroy() {
}
}
5.后台主页面
package com.pojo;
public class Brand {
// id 主键
private Integer id;
// 品牌名称
private String brandName;
// 企业名称
private String companyName;
// 排序字段
private Integer ordered;
// 描述信息
private String description;
// 状态:0:禁用 1:启用
private Integer status;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getBrandName() {
return brandName;
}
public void setBrandName(String brandName) {
this.brandName = brandName;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public Integer getOrdered() {
return ordered;
}
public void setOrdered(Integer ordered) {
this.ordered = ordered;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getStatus() {
return status;
}
//逻辑视图
public String getStatusStr(){
if (status == null){
return "未知";
}
return status == 0 ? "禁用":"启用";
}
public void setStatus(Integer status) {
this.status = status;
}
@Override
public String toString() {
return "Brand{" +
"id=" + id +
", brandName='" + brandName + '\'' +
", companyName='" + companyName + '\'' +
", ordered=" + ordered +
", description='" + description + '\'' +
", status=" + status +
'}';
}
}
package com.mapper;
import com.pojo.Brand;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface BrandMapper {
//查询所有
List SelectAll();
//添加数据
void add(Brand brand);
//修改数据
void update(Brand brand);
//删除单个数据,通过id
void deleteById(Brand brand);
//批量删除数据
void deleteByIds(@Param("ids") int[] ids);
//分页查询
List selectByPage(@Param("begin") int begin,@Param("size") int size);
//查询数据总数
int selectTotalCount();
//在条件查询的基础上进行分页查询
List selectByPageAndCondition(@Param("begin") int begin,@Param("size") int size,@Param("brand") Brand brand);
//通过条件查询符合的数据总数
int selectTotalCountByCondition(Brand brand);
}
insert into tb_brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status});
update tb_brand set brand_name=#{brandName},company_name=#{companyName},ordered=#{ordered},
description=#{description},status=#{status} where id=#{id};
delete from tb_brand where id=#{id};
delete from tb_brand where id in
#{id}
package com.service;
import com.pojo.Brand;
import com.pojo.PageBean;
import java.util.List;
//原本方法可在BrandService直接实现,现在为了方便管理和动态处理,在接口实现类BrandServiceImpl实现
public interface BrandService {
//查询所有
/*这个建立的不是接口,是类
public class BrandService {
SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
public List selectAll(){
SqlSession sqlSession = sqlSessionFactory.openSession();
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
List brands = mapper.SelectAll();
sqlSession.close();
return brands;
}
}*/
List SelectAll();
//添加数据
void add(Brand brand);
//修改数据
void update(Brand brand);
//删除单个数据,通过id
void deleteById(Brand brand);
//批量删除数据
void deleteByIds(int[] ids);
//分页查询,(当前页码,每页展示数据数)
PageBean selectByPage(int currentPage,int pageSize);
//分页条件查询,(当前页码,每页展示数据数,条件)
PageBean selectByPageAndCondition(int currentPage,int pageSize,Brand brand);
}
package com.service.impl;
import com.mapper.BrandMapper;
import com.pojo.Brand;
import com.pojo.PageBean;
import com.service.BrandService;
import com.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import java.util.List;
public class BrandServiceImpl implements BrandService {
//1. 创建SqlSessionFactory 工厂对象
SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
@Override
public List SelectAll() {
//2. 获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//3. 获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//4. 调用方法
List brands = mapper.SelectAll();
//5. 释放资源
sqlSession.close();
return brands;
}
@Override
public void add(Brand brand) {
//2. 获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//3. 获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//4. 调用方法
mapper.add(brand);
//5. 执行操作,提交事务
sqlSession.commit();
//6. 释放资源
sqlSession.close();
}
@Override
public void update(Brand brand) {
//2. 获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//3. 获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//4. 调用方法
mapper.update(brand);
//5. 执行操作,提交事务
sqlSession.commit();
//6. 释放资源
sqlSession.close();
}
@Override
public void deleteById(Brand brand) {
//2. 获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//3. 获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//4. 调用方法
mapper.deleteById(brand);
//5. 执行操作,提交事务
sqlSession.commit();
//6. 释放资源
sqlSession.close();
}
@Override
public void deleteByIds(int[] ids) {
//2. 获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//3. 获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//4. 调用方法
mapper.deleteByIds(ids);
//5. 执行操作,提交事务
sqlSession.commit();
//6. 释放资源
sqlSession.close();
}
@Override
public PageBean selectByPage(int currentPage, int pageSize) {
//2. 获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//3. 获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//4.1 计算开始索引
int begin=(currentPage-1)*pageSize;
//4.2. 计算查询条目数
int size=pageSize;
//5. 查询当前页数据
List brands = mapper.selectByPage(begin, size);
//6. 查询总记录数
int totalCount = mapper.selectTotalCount();
//补充:如果最后一页没有数据不够导致没有显示完,自动补充空白行,美观
Brand brand1 = null;
int number1=totalCount-(currentPage-1)*pageSize;
if(number1 pageBean=new PageBean<>();
pageBean.setRows(brands);
pageBean.setTotalCount(totalCount);
//8. 释放资源
sqlSession.close();
return pageBean;
}
@Override
public PageBean selectByPageAndCondition(int currentPage, int pageSize, Brand brand) {
//2. 获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//3. 获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//4. 计算开始索引
int begin = (currentPage - 1) * pageSize;
// 计算查询条目数
int size = pageSize;
// 处理brand条件,模糊表达式
String brandName = brand.getBrandName();
if (brandName != null && brandName.length() > 0) {
brand.setBrandName("%" + brandName + "%");
}
String companyName = brand.getCompanyName();
if (companyName != null && companyName.length() > 0) {
brand.setCompanyName("%" + companyName + "%");
}
//5. 查询当前页数据
List rows = mapper.selectByPageAndCondition(begin, size, brand);
//6. 查询总记录数
int totalCount = mapper.selectTotalCountByCondition(brand);
//补充:如果最后一页没有数据不够导致没有显示完,自动补充空白行,美观
Brand brand1 = null;
int number1=totalCount-(currentPage-1)*pageSize;
if(number1 pageBean = new PageBean<>();
pageBean.setRows(rows);
pageBean.setTotalCount(totalCount);
//8. 释放资源
sqlSession.close();
return pageBean;
}
}
package com.web.servlet;
/*
替换HttpServlet,根据请求的最后一段路径来进行方法分发
* */
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class BaseServlet extends HttpServlet {
//根据请求的最后一段路径进行方法的分发
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.获取请求的路径
String uri = req.getRequestURI(); // 例如路径为:/brand-case/brand/selectAll
//2. 获取最后一段路径,方法名
//从路径的后面找到第一个“/”所处位置,然后最后的路径截下来,不携带“/”字符,如“selectAll”
int index = uri.lastIndexOf('/');
//将index位置开始进行索引,返回字符串(方法名)
String methodName = uri.substring(index + 1); // 获取到资源的二级路径 selectAll
//3. 执行方法
//3.1 获取BrandServlet /UserServlet 字节码对象 Class
/*
this为谁调用用它(this所在的方法,如service方法),它(this)代表谁
如:service方法被BrandServlet调用,this代表BrandServlet
*/
//System.out.println(this);
//下面是通过this获得字节码对象
Class extends BaseServlet> cls =this.getClass();
//3.2 获取方法 Method对象
try {
Method method = cls.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
//3.3 执行方法
method.invoke(this,req,resp);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
package com.web.servlet;
import com.alibaba.fastjson.JSON;
import com.pojo.Brand;
import com.pojo.PageBean;
import com.service.BrandService;
import com.service.impl.BrandServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;
@WebServlet("/brand/*")
public class BrandServlet extends BaseServlet{
//提供impl接口,减小耦合性,可以后进行动态获取实现类,只需要改变BrandServiceImpl
private BrandService brandService = new BrandServiceImpl();
public void SelectAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
//System.out.println("selectAll.....");
//1. 调用service查询
List brands = brandService.SelectAll();
//2. 转为JSON(用的Fastjson)
String jsonString = JSON.toJSONString(brands);
//3. 写数据
//告知浏览器响应的数据是什么, 告知浏览器使用什么字符集进行解码
response.setContentType("text/json;charset=utf-8");
response.getWriter().write(jsonString);
}
public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
//System.out.println("Add.....");
request.setCharacterEncoding("UTF-8");
//1. 接收品牌数据
BufferedReader br = request.getReader();
String params = br.readLine();//json字符串
//转为Brand对象
Brand brand = JSON.parseObject(params, Brand.class);
//2. 调用service添加
brandService.add(brand);
//3. 响应成功的标识
response.getWriter().write("success");
}
public void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
request.setCharacterEncoding("UTF-8");
//1. 接收品牌数据
BufferedReader br = request.getReader();
String params = br.readLine();//json字符串
//转为Brand对象
Brand brand = JSON.parseObject(params, Brand.class);
//2. 调用service修改
brandService.update(brand);
//3. 响应成功的标识
response.getWriter().write("success");
}
public void deleteById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
//1. 接收品牌数据
BufferedReader br = request.getReader();
String params = br.readLine();//json字符串
//转为Brand对象
Brand brand = JSON.parseObject(params, Brand.class);
//2. 调用service修改
brandService.deleteById(brand);
//3. 响应成功的标识
response.getWriter().write("success");
}
public void deleteByIds(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
//1. 接收品牌数据,像这样的[1,2,3,4],所以还用JSON
BufferedReader br = request.getReader();
String params = br.readLine();//json字符串
//转为 int[]数组
int[] ids = JSON.parseObject(params, int[].class);
//2. 调用service修改
brandService.deleteByIds(ids);
//3. 响应成功的标识
response.getWriter().write("success");
}
//分页查询
public void selectByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
//1. 接收参数,(当前页码,每页展示条数) 如:url?currentPage=1&pageSize=20
String currentPageX = request.getParameter("currentPage");
String pageSizeX = request.getParameter("pageSize");
int currentPage = Integer.parseInt(currentPageX);
int pageSize = Integer.parseInt(pageSizeX);
//2. 调用service
PageBean pageBean = brandService.selectByPage(currentPage, pageSize);
//2. 转为JSON(用的Fastjson)
String jsonString = JSON.toJSONString(pageBean);
//3. 写数据
//告知浏览器响应的数据是什么, 告知浏览器使用什么字符集进行解码
response.setContentType("text/json;charset=utf-8");
response.getWriter().write(jsonString);
}
//条件分页查询
public void selectByPageAndCondition(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 接收 当前页码 和 每页展示条数 url?currentPage=1&pageSize=5
String _currentPage = request.getParameter("currentPage");
String _pageSize = request.getParameter("pageSize");
int currentPage = Integer.parseInt(_currentPage);
int pageSize = Integer.parseInt(_pageSize);
// 获取查询条件对象
BufferedReader br = request.getReader();
String params = br.readLine();//json字符串
//转为 Brand
Brand brand = JSON.parseObject(params, Brand.class);
//2. 调用service查询
PageBean pageBean = brandService.selectByPageAndCondition(currentPage,pageSize,brand);
//2. 转为JSON
String jsonString = JSON.toJSONString(pageBean);
//3. 写数据
response.setContentType("text/json;charset=utf-8");
response.getWriter().write(jsonString);
}
}
package com.pojo;
import java.util.List;
//分页查询的javabean
/*为可以应用其他数据,创造一个泛型T
可在创建PageBean对象时进行指定,提高数据通用性*/
public class PageBean {
//总记录数
private int totalCount;
//当前页数据
private List rows;
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public List getRows() {
return rows;
}
public void setRows(List rows) {
this.rows = rows;
}
@Override
public String toString() {
return "PageBean{" +
"totalCount=" + totalCount +
", rows=" + rows +
'}';
}
}
主页面
Loading...
6.工程结构
7.代码下载
Gitte:品牌后台管理系统: JavaWeb综合案例——品牌后台管理系统 mybatis+maven+filter+ajax+json+js+html+css+element+VUE (gitee.com)
CSDN:黑马程序员最新版JavaWeb综合案例——品牌后台管理系统-Java文档类资源-CSDN文库https://download.csdn.net/download/weixin_59798969/86399430
可以点个免费的赞吗!!!