目录
1.功能介绍
- 用户登录
- 用户注册(附有验证码功能)
- 条件查询
- 查询所有
- 新增品牌
- 批量删除
- 修改品牌
- 删除品牌
- 分页查询
2.前期准备
2.1准备数据库
-- 删除tb_brand表
drop table if exists tb_brand;
-- 创建tb_brand表
create table tb_brand
(
-- id 主键
id int primary key auto_increment,
-- 品牌名称
brand_name varchar(20),
-- 企业名称
company_name varchar(20),
-- 排序字段
ordered int,
-- 描述信息
description varchar(100),
-- 状态:0:禁用 1:启用
status int
);
-- 添加数据
insert into tb_brand (brand_name, company_name, ordered, description, status)
values
('华为', '华为技术有限公司', 100, '万物互联', 1),
('小米', '小米科技有限公司', 50, 'are you ok', 1),
('格力', '格力电器股份有限公司', 30, '让世界爱上中国造', 1),
('阿里巴巴', '阿里巴巴集团控股有限公司', 10, '买买买', 1),
('腾讯', '腾讯计算机系统有限公司', 50, '玩玩玩', 0),
('百度', '百度在线网络技术公司', 5, '搜搜搜', 0),
('京东', '北京京东世纪贸易有限公司', 40, '就是快', 1),
('小米', '小米科技有限公司', 50, 'are you ok', 1),
('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火', 0),
('华为', '华为技术有限公司', 100, '万物互联', 1),
('小米', '小米科技有限公司', 50, 'are you ok', 1),
('格力', '格力电器股份有限公司', 30, '让世界爱上中国造', 1),
('阿里巴巴', '阿里巴巴集团控股有限公司', 10, '买买买', 1),
('腾讯', '腾讯计算机系统有限公司', 50, '玩玩玩', 0),
('百度', '百度在线网络技术公司', 5, '搜搜搜', 0),
('京东', '北京京东世纪贸易有限公司', 40, '就是快', 1),
('华为', '华为技术有限公司', 100, '万物互联', 1),
('小米', '小米科技有限公司', 50, 'are you ok', 1),
('格力', '格力电器股份有限公司', 30, '让世界爱上中国造', 1),
('阿里巴巴', '阿里巴巴集团控股有限公司', 10, '买买买', 1),
('腾讯', '腾讯计算机系统有限公司', 50, '玩玩玩', 0),
('百度', '百度在线网络技术公司', 5, '搜搜搜', 0),
('京东', '北京京东世纪贸易有限公司', 40, '就是快', 1),
('小米', '小米科技有限公司', 50, 'are you ok', 1),
('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火', 0),
('华为', '华为技术有限公司', 100, '万物互联', 1),
('小米', '小米科技有限公司', 50, 'are you ok', 1),
('格力', '格力电器股份有限公司', 30, '让世界爱上中国造', 1),
('阿里巴巴', '阿里巴巴集团控股有限公司', 10, '买买买', 1),
('腾讯', '腾讯计算机系统有限公司', 50, '玩玩玩', 0),
('百度', '百度在线网络技术公司', 5, '搜搜搜', 0),
('京东', '北京京东世纪贸易有限公司', 40, '就是快', 1),
('华为', '华为技术有限公司', 100, '万物互联', 1),
('小米', '小米科技有限公司', 50, 'are you ok', 1),
('格力', '格力电器股份有限公司', 30, '让世界爱上中国造', 1),
('阿里巴巴', '阿里巴巴集团控股有限公司', 10, '买买买', 1),
('腾讯', '腾讯计算机系统有限公司', 50, '玩玩玩', 0),
('百度', '百度在线网络技术公司', 5, '搜搜搜', 0),
('京东', '北京京东世纪贸易有限公司', 40, '就是快', 1),
('小米', '小米科技有限公司', 50, 'are you ok', 1),
('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火', 0),
('华为', '华为技术有限公司', 100, '万物互联', 1),
('小米', '小米科技有限公司', 50, 'are you ok', 1),
('格力', '格力电器股份有限公司', 30, '让世界爱上中国造', 1),
('阿里巴巴', '阿里巴巴集团控股有限公司', 10, '买买买', 1),
('腾讯', '腾讯计算机系统有限公司', 50, '玩玩玩', 0),
('百度', '百度在线网络技术公司', 5, '搜搜搜', 0),
('京东', '北京京东世纪贸易有限公司', 40, '就是快', 1)
;
SELECT * FROM tb_brand;
2.2pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>login-register</artifactId>
<version>1.0-SNAPSHOT</version>
<!--重要!!!-->
<packaging>war</packaging>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<!--scope:依赖范围-->
<scope>provided</scope>
</dependency>
<!--json-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
</dependencies>
<!--alt + insert快速生成-->
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
</plugin>
</plugins>
</build>
</project>
2.3mybatis-config文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--数据库连接信息-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<!--根据自己的数据填写-->
<property name="url" value="jdbc:mysql:///mybatis?useSSL=false&useServerPrepStmts=true"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--加载sql的映射文件-->
<package name="com.zxp.Mapper"/>
</mappers>
</configuration>
3.用户登录注册
准备一个自己的登录页面的背景照片,放在webapp的css文件夹中
3.1html页面
3.1.1登录页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
<link href="css/login.css" rel="stylesheet">
</head>
<body>
<div id="loginDiv" style="height: 350px">
<form action="" id="form">
<h1 id="loginMsg">LOGIN IN</h1>
<div id="errorMsg">用户名或密码不正确</div>
<p>Username:<input id="username" name="username" type="text"></p>
<p>Password:<input id="password" name="password" type="password"></p>
<p>Remember:<input id="remember" name="remember" type="checkbox"></p>
<div id="subDiv">
<input type="submit" class="button" value="login up">
<input type="reset" class="button" value="reset">
<a href="register.html">没有账号?</a>
</div>
</form>
</div>
</body>
</html>
3.1.2注册页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>欢迎注册</title>
<link href="css/register.css" rel="stylesheet">
</head>
<body>
<div class="form-div">
<div class="reg-content">
<h1>欢迎注册</h1>
<span>已有帐号?</span> <a href="login.html">登录</a>
</div>
<form id="reg-form" action="#" method="get">
<table>
<tr>
<td>用户名</td>
<td class="inputs">
<input name="username" type="text" id="username">
<br>
<span id="username_err" class="err_msg" style="display: none">用户名不太受欢迎</span>
</td>
</tr>
<tr>
<td>密码</td>
<td class="inputs">
<input name="password" type="password" id="password">
<br>
<span id="password_err" class="err_msg" style="display: none">密码格式有误</span>
</td>
</tr>
<tr>
<td>验证码</td>
<td class="inputs">
<input name="checkCode" type="text" id="checkCode">
<img src="imgs/a.jpg">
<a href="#" id="changeImg">看不清?</a>
</td>
</tr>
</table>
<div class="buttons">
<input value="注 册" type="submit" id="reg_btn">
</div>
<br class="clear">
</form>
</div>
</body>
</html>
3.2css文件
3.2.1register css文件
* {
margin: 0;
padding: 0;
list-style-type: none;
}
.reg-content{
padding: 30px;
margin: 3px;
}
a, img {
border: 0;
}
body {
background-image: url("../imgs/reg_bg_min.jpg") ;
text-align: center;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
td, th {
padding: 0;
height: 90px;
}
.inputs{
vertical-align: top;
}
.clear {
clear: both;
}
.clear:before, .clear:after {
content: "";
display: table;
}
.clear:after {
clear: both;
}
.form-div {
background-color: rgba(255, 255, 255, 0.27);
border-radius: 10px;
border: 1px solid #aaa;
width: 424px;
margin-top: 150px;
margin-left:1050px;
padding: 30px 0 20px 0px;
font-size: 16px;
box-shadow: inset 0px 0px 10px rgba(255, 255, 255, 0.5), 0px 0px 15px rgba(75, 75, 75, 0.3);
text-align: left;
}
.form-div input[type="text"], .form-div input[type="password"], .form-div input[type="email"] {
width: 268px;
margin: 10px;
line-height: 20px;
font-size: 16px;
}
.form-div input[type="checkbox"] {
margin: 20px 0 20px 10px;
}
.form-div input[type="button"], .form-div input[type="submit"] {
margin: 10px 20px 0 0;
}
.form-div table {
margin: 0 auto;
text-align: right;
color: rgba(64, 64, 64, 1.00);
}
.form-div table img {
vertical-align: middle;
margin: 0 0 5px 0;
}
.footer {
color: rgba(64, 64, 64, 1.00);
font-size: 12px;
margin-top: 30px;
}
.form-div .buttons {
float: right;
}
input[type="text"], input[type="password"], input[type="email"] {
border-radius: 8px;
box-shadow: inset 0 2px 5px #eee;
padding: 10px;
border: 1px solid #D4D4D4;
color: #333333;
margin-top: 5px;
}
input[type="text"]:focus, input[type="password"]:focus, input[type="email"]:focus {
border: 1px solid #50afeb;
outline: none;
}
input[type="button"], input[type="submit"] {
padding: 7px 15px;
background-color: #3c6db0;
text-align: center;
border-radius: 5px;
overflow: hidden;
min-width: 80px;
border: none;
color: #FFF;
box-shadow: 1px 1px 1px rgba(75, 75, 75, 0.3);
}
input[type="button"]:hover, input[type="submit"]:hover {
background-color: #5a88c8;
}
input[type="button"]:active, input[type="submit"]:active {
background-color: #5a88c8;
}
.err_msg{
color: red;
padding-right: 170px;
}
#password_err,#tel_err{
padding-right: 195px;
}
#reg_btn{
margin-right:50px; width: 285px; height: 45px; margin-top:20px;
}
#checkCode{
width: 100px;
}
#changeImg{
color: aqua;
}
3.2.2login css文件
* {
margin: 0;
padding: 0;
}
html {
height: 100%;
width: 100%;
overflow: hidden;
margin: 0;
padding: 0;
background: url(../imgs/Desert1.jpg) no-repeat 0px 0px;
background-repeat: no-repeat;
background-size: 100% 100%;
-moz-background-size: 100% 100%;
}
body {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
}
#loginDiv {
width: 37%;
display: flex;
justify-content: center;
align-items: center;
height: 380px;
background-color: rgba(75, 81, 95, 0.3);
box-shadow: 7px 7px 17px rgba(52, 56, 66, 0.5);
border-radius: 5px;
}
#name_trip {
margin-left: 50px;
color: #00ffcc;
}
p {
margin-top: 30px;
margin-left: 20px;
color: azure;
}
#remember{
margin-left: 15px;
border-radius: 5px;
border-style: hidden;
background-color: rgba(216, 191, 216, 0.5);
outline: none;
padding-left: 10px;
height: 20px;
width: 20px;
}
#username{
width: 200px;
margin-left: 15px;
border-radius: 5px;
border-style: hidden;
height: 30px;
background-color: rgba(216, 191, 216, 0.5);
outline: none;
color: #f0edf3;
padding-left: 10px;
}
#password{
width: 202px;
margin-left: 15px;
border-radius: 5px;
border-style: hidden;
height: 30px;
background-color: rgba(216, 191, 216, 0.5);
outline: none;
color: #f0edf3;
padding-left: 10px;
}
.button {
border-color: cornsilk;
background-color: rgba(100, 149, 237, .7);
color: aliceblue;
border-style: hidden;
border-radius: 5px;
width: 100px;
height: 31px;
font-size: 16px;
}
#subDiv {
text-align: center;
margin-top: 30px;
}
#loginMsg{
text-align: center;
color: aliceblue;
}
#errorMsg{
text-align: center;
color:red;
}
3.3JSP文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
<link href="css/login.css" rel="stylesheet">
</head>
<body>
<div id="loginDiv" style="height: 350px">
<form action="/login-register/loginServlet" id="form">
<h1 id="loginMsg">LOGIN IN</h1>
<div id="errorMsg">${login_msg} ${register_msg}</div>
<p>Username:<input id="username" name="username" value="${cookie.username.value}" type="text"></p>
<p>Password:<input id="password" name="password" value="${cookie.password.value}" type="password"></p>
<p>Remember:<input id="remember" name="remember" value="1" type="checkbox"></p>
<div id="subDiv">
<input type="submit" class="button" value="login up">
<input type="reset" class="button" value="reset">
<a href="register.jsp">没有账号?</a>
</div>
</form>
</div>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>欢迎注册</title>
<link href="css/register.css" rel="stylesheet">
</head>
<body>
<div class="form-div">
<div class="reg-content">
<h1>欢迎注册</h1>
<span>已有帐号?</span> <a href="login.jsp">登录</a>
</div>
<form id="reg-form" action="/login-register/registerServlet" method="post">
<table>
<tr>
<td>用户名</td>
<td class="inputs">
<input name="username" type="text" id="username" value="${sessionScope.get("username")}">
<br>
<span id="username_err" class="err_msg">${register_msg}</span>
</td>
</tr>
<tr>
<td>密码</td>
<td class="inputs">
<input name="password" type="password" id="password" value="${sessionScope.get("password")}">
<br>
<span id="password_err" class="err_msg" style="display: none">密码格式有误</span>
</td>
</tr>
<tr>
<td>验证码</td>
<td class="inputs">
<input name="checkCode" type="text" id="checkCode">
<img id="checkCodeImage" src="/login-register/checkCodeServlet">
<a href="#" id="changeImg">看不清?</a>
</td>
</tr>
</table>
<div class="buttons">
<input value="注 册" type="submit" id="reg_btn">
</div>
<br class="clear">
</form>
</div>
<script>
document.getElementById("changeImg").onclick = function (){
document.getElementById("checkCodeImage").src="/login-register/checkCodeServlet?" + new Date().getMilliseconds();
}
</script>
</body>
</html>
3.4UserMapper
package com.zxp.web;
import com.zxp.pojo.User;
import com.zxp.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 userService = new UserService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
String remember = request.getParameter("remember");
User user = userService.login(username, password);
if (user != null){
if ("1".equals(remember)){
Cookie c_username = new Cookie("username",username);
Cookie c_password = new Cookie("password",password);
c_username.setMaxAge(60 * 60 * 24 * 7);
c_password.setMaxAge(60 * 60 * 24 * 7);
response.addCookie(c_username);
response.addCookie(c_password);
}
//将登陆成功的User对象存储到session中
HttpSession session = request.getSession();
session.setAttribute("user",user);
String contextPath = request.getContextPath();
response.sendRedirect(contextPath + "/selectAllServlet");
}else {
//存储错误信息到request
request.setAttribute("login_msg","用户名或密码错误");
//请求转发到login.jsp
request.getRequestDispatcher("/login.jsp").forward(request,response);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
namespace:名称空间,接口所在位置
select id:方法名称
resultType:返回值类型
-->
<mapper namespace="com.zxp.Mapper.UserMapper">
<select id="searchUserByUsername" resultType="com.zxp.pojo.User">
select * from tb_user where username = #{username};
</select>
<select id="select" resultType="com.zxp.pojo.User">
select * from tb_user where username = #{username} and password = #{password};
</select>
<insert id="add">
insert into tb_user values(null,#{username},#{password});
</insert>
</mapper>
3.5User类
package com.zxp.pojo;
public class User {
private String username;
private String password;
public User(String username, String password) {
this.username = username;
this.password = password;
}
public User() {
}
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{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
3.6验证码工具
package com.zxp.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 IOException {
OutputStream fos = new FileOutputStream("d://a.jpg");
String checkCode = CheckCodeUtil.outputVerifyImage(100, 50, fos, 4);
System.out.println(checkCode);
}
/**
* 输出随机验证码图片流,并返回验证码值(一般传入输出流,响应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.7Filter(未登录前禁止访问资源)
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 init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request1 = (HttpServletRequest) request;
//判断访问路径是否和登陆注册有关
String urls[] = {"/login.jsp","/imgs/","/css/"};
//获取当前访问的资源路径
String url = request1.getRequestURI();
for (String u : urls) {
if (url.contains(u)){
chain.doFilter(request,response);
return;
}
}
HttpSession session = request1.getSession();
Object user = session.getAttribute("user");
if (user != null){
//放行
chain.doFilter(request,response);
}else {
//返回登陆页面
request.setAttribute("login_msg","您尚未登录");
request.getRequestDispatcher("/login.jsp").forward(request,response);
}
}
@Override
public void destroy() {
}
}
3.8sqlSessionFactoryUtil
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;
public class SqlSessionFactoryUtil {
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;
}
}
3.9loginServlet
package com.zxp.web;
import com.zxp.pojo.User;
import com.zxp.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 userService = new UserService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
String remember = request.getParameter("remember");
User user = userService.login(username, password);
if (user != null){
if ("1".equals(remember)){
Cookie c_username = new Cookie("username",username);
Cookie c_password = new Cookie("password",password);
c_username.setMaxAge(60 * 60 * 24 * 7);
c_password.setMaxAge(60 * 60 * 24 * 7);
response.addCookie(c_username);
response.addCookie(c_password);
}
//将登陆成功的User对象存储到session中
HttpSession session = request.getSession();
session.setAttribute("user",user);
String contextPath = request.getContextPath();
response.sendRedirect(contextPath + "/selectAllServlet");
}else {
//存储错误信息到request
request.setAttribute("login_msg","用户名或密码错误");
//请求转发到login.jsp
request.getRequestDispatcher("/login.jsp").forward(request,response);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}
3.10registerServlet
package com.zxp.web;
import com.zxp.pojo.User;
import com.zxp.service.UserService;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet("/registerServlet")
public class registerServlet extends HttpServlet {
private UserService userService = new UserService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
String checkCode = request.getParameter("checkCode");
HttpSession session = request.getSession();
String verifyCode = (String) session.getAttribute("verifyCode");
if (!verifyCode.equalsIgnoreCase(checkCode)){
session.setAttribute("username",username);
session.setAttribute("password",password);
request.setAttribute("register_msg", "验证码错误,请重新新注册");
request.getRequestDispatcher("/register.jsp").forward(request, response);
return;
}
User user = new User();
user.setUsername(username);
user.setPassword(password);
boolean flag = userService.register(user);
if (flag) {
request.setAttribute("register_msg", "注册成功,请登录");
request.getRequestDispatcher("/login.jsp").forward(request, response);
session.invalidate();
} else {
//用户已经存在,跳转到注册页面
request.setAttribute("register_msg", "注册失败,请重新注册");
request.getRequestDispatcher("/register.jsp").forward(request, response);
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}
4.增删改查
4.1BrandMapper
import com.zxp.pojo.Brand;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface BrandMapper {
List<Brand> selectAll();
void addBrand(Brand brand);
void deleteById(int id);
void deleteByIds(@Param("ids") int[] ids);
void updateBrand(Brand brand);
List<Brand> selectByPage(@Param("begin") int begin, @Param("size") int size);
int selectTotalCount();
List<Brand> selectByPageAndCondition(@Param("begin") int begin, @Param("size") int size, @Param("brand") Brand brand);
int selectTotalCountByCondition(Brand brand);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
namespace:名称空间,接口所在位置
select id:方法名称
resultType:返回值类型
-->
<mapper namespace="com.zxp.Mapper.BrandMapper">
<resultMap id="brandResultMap" type="com.zxp.pojo.Brand">
<result column="brand_name" property="brandName"></result>
<result column="company_name" property="companyName"></result>
</resultMap>
<insert id="addBrand">
insert into tb_brand
values (null, #{brandName}, #{companyName}, #{ordered}, #{description}, #{status});
</insert>
<update id="updateBrand">
update tb_brand
set brand_name=#{brandName},
company_name=#{companyName},
ordered=#{ordered},
status=#{status}
where id = #{id};
</update>
<delete id="deleteById">
delete
from tb_brand
where id = #{id};
</delete>
<delete id="deleteByIds">
delete from tb_brand where id in
<foreach collection="ids" item="id" separator="," open="(" close=")">
#{id}
</foreach>
</delete>
<select id="selectAll" resultMap="brandResultMap">
select *
from tb_brand;
</select>
<select id="selectByPage" resultMap="brandResultMap">
select *
from tb_brand limit #{begin}, #{size};
</select>
<select id="selectTotalCount" resultType="java.lang.Integer">
select count(*)
from tb_brand;
</select>
<select id="selectByPageAndCondition" resultMap="brandResultMap">
select *
from tb_brand
<where>
<if test="brand.status != null">
and status = #{brand.status}
</if>
<if test="brand.companyName != null and brand.companyName != '' ">
and company_name like #{brand.companyName}
</if>
<if test="brand.brandName != null and brand.brandName != '' ">
and brand_name like #{brand.brandName}
</if>
</where>
limit #{begin}, #{size}
</select>
<select id="selectTotalCountByCondition" resultType="java.lang.Integer">
select count(*)
from tb_brand
<where>
<if test="status != null">
and status = #{status}
</if>
<if test="companyName != null and companyName != '' ">
and company_name like #{companyName}
</if>
<if test="brandName != null and brandName != '' ">
and brand_name like #{brandName}
</if>
</where>
</select>
</mapper>
4.2pojo
4.2.1Brand
package com.zxp.pojo;
public class Brand {
//int会有默认值所以不使用int
//主键
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 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 + '\'' +
'}';
}
}
4.2.2PageBean
package com.zxp.pojo;
import java.util.List;
public class PageBean<T>{
private int totalCount;
private List<T> rows;
public PageBean() {
}
public PageBean(int totalCount, List<T> rows) {
this.totalCount = totalCount;
this.rows = rows;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public List<T> getRows() {
return rows;
}
public void setRows(List<T> rows) {
this.rows = rows;
}
}
4.3Service
4.3.1BrandService
import com.zxp.pojo.Brand;
import com.zxp.pojo.PageBean;
import java.util.List;
public interface BrandService {
List<Brand> selectAll();
void add(Brand brand);
void deleteById(int id);
void deleteByIds(int[] ids);
void updateBrand(Brand brand);
PageBean<Brand> selectByPage(int currentPage,int pageSize);
PageBean<Brand> selectByPageAndCondition(int currentPage, int pageSize, Brand brand);
}
4.3.2实现类
package com.zxp.service.impl;
import com.zxp.Mapper.BrandMapper;
import com.zxp.pojo.Brand;
import com.zxp.pojo.PageBean;
import com.zxp.service.BrandService;
import com.zxp.util.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import java.util.List;
public class BrandServiceImpl implements BrandService {
//创建SqlSessionFactory对象
SqlSessionFactory factory = SqlSessionFactoryUtil.getSqlSessionFactory();
/**
* 查询全部数据
* @return
*/
@Override
public List<Brand> selectAll() {
//获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
List<Brand> brands = mapper.selectAll();
//释放资源
sqlSession.close();
return brands;
}
/**
* 添加数据
* @param brand
*/
@Override
public void add(Brand brand) {
//获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
mapper.addBrand(brand);
sqlSession.commit();
sqlSession.close();
}
/**
* 根据id删除数据
* @param id
*/
@Override
public void deleteById(int id) {
//获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
mapper.deleteById(id);
sqlSession.commit();
sqlSession.close();
}
/**
* 批量删除
* @param ids
*/
@Override
public void deleteByIds(int[] ids) {
//获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
mapper.deleteByIds(ids);
sqlSession.commit();
sqlSession.close();
}
/**
* 修改
* @param brand
*/
@Override
public void updateBrand(Brand brand) {
//获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
mapper.updateBrand(brand);
sqlSession.commit();
sqlSession.close();
}
@Override
public PageBean<Brand> selectByPage(int currentPage, int pageSize) {
//获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
int begin = (currentPage - 1) * pageSize;
int size = pageSize;
List<Brand> rows = mapper.selectByPage(begin, size);
int totalCount = mapper.selectTotalCount();
PageBean<Brand> pageBean = new PageBean<>();
pageBean.setRows(rows);
pageBean.setTotalCount(totalCount);
sqlSession.close();
return pageBean;
}
@Override
public PageBean<Brand> selectByPageAndCondition(int currentPage, int pageSize, Brand brand) {
//获取SqlSession对象
SqlSession sqlSession = factory.openSession();
//获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
int begin = (currentPage - 1) * pageSize;
int size = pageSize;
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 + "%");
}
List<Brand> rows = mapper.selectByPageAndCondition(begin, size, brand);
int totalCount = mapper.selectTotalCountByCondition(brand);
PageBean<Brand> pageBean = new PageBean<>();
pageBean.setRows(rows);
pageBean.setTotalCount(totalCount);
sqlSession.close();
return pageBean;
}
}
4.4Servlet
4.4.1BaseServlet
package com.zxp.web.servlet;
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();
//2.获取最后一段路径
int index = uri.lastIndexOf("/");
String methodName = uri.substring(index + 1);
//3.获取BrandServlet字节码对象Class(反射)
Class<? extends BaseServlet> cls = this.getClass();
try {
Method method = cls.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
//4.执行方法
method.invoke(this,req,resp);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
4.4.2BrandServlet
package com.zxp.web.servlet;
import com.alibaba.fastjson.JSON;
import com.zxp.pojo.Brand;
import com.zxp.pojo.PageBean;
import com.zxp.service.BrandService;
import com.zxp.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{
private BrandService brandService = new BrandServiceImpl();
/**
* 查询全部
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void selectAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
List<Brand> brands = brandService.selectAll();
//转为JSON
String jsonStr = JSON.toJSONString(brands);
//写数据(设置编码方式)
response.setContentType("text/json;charset=utf-8");
response.getWriter().write(jsonStr);
}
/**
* 添加数据
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
//获取请求体数据
BufferedReader br = request.getReader();
String params = br.readLine();
// 将JSON字符串转为Java对
Brand brand = JSON.parseObject(params, Brand.class);
//2. 调用service 添加
brandService.add(brand);
//3. 响应成功标识
response.getWriter().write("success");
}
/**
* 删除数据
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void deleteBrand(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
//获取请求体数据
BufferedReader br = request.getReader();
String params = br.readLine();
int id = JSON.parseObject(params,int.class);
brandService.deleteById(id);
response.getWriter().write("success");
}
/**
* 批量删除
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void deleteByIds(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取请求体数据
BufferedReader br = request.getReader();
String params = br.readLine();
int[] ids = JSON.parseObject(params,int[].class);
brandService.deleteByIds(ids);
response.getWriter().write("success");
}
/**
* 修改表格
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void updateBrand(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
//获取请求体数据
BufferedReader br = request.getReader();
String params = br.readLine();
Brand brand = JSON.parseObject(params,Brand.class);
brandService.updateBrand(brand);
response.getWriter().write("success");
}
/**
* 分页查询
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void selectByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
String _currentPage = request.getParameter("currentPage");
String _pageSize = request.getParameter("pageSize");
int currentPage = Integer.parseInt(_currentPage);
int pageSize = Integer.parseInt(_pageSize);
PageBean<Brand> pageBean = brandService.selectByPage(currentPage, pageSize);
//转为JSON
String jsonString = JSON.toJSONString(pageBean);
//写数据
response.setContentType("text/json;charset=utf-8");
response.getWriter().write(jsonString);
}
/**
* 查询
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void selectByPageAndCondition(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
BufferedReader br = request.getReader();
String params = br.readLine();
Brand brand = JSON.parseObject(params,Brand.class);
String _currentPage = request.getParameter("currentPage");
String _pageSize = request.getParameter("pageSize");
int currentPage = Integer.parseInt(_currentPage);
int pageSize = Integer.parseInt(_pageSize);
PageBean<Brand> pageBean = brandService.selectByPageAndCondition(currentPage, pageSize,brand);
//转为JSON
String jsonString = JSON.toJSONString(pageBean);
//写数据
response.setContentType("text/json;charset=utf-8");
response.getWriter().write(jsonString);
}
}
4.5BrandHTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.el-table .warning-row {
background: oldlace;
}
.el-table .success-row {
background: #f0f9eb;
}
</style>
</head>
<body>
<div id="app">
<el-form :inline="true" :model="brand" class="demo-form-inline">
<el-form-item label="当前状态">
<el-select v-model="brand.status" placeholder="当前状态">
<el-option label="启用" value="1"></el-option>
<el-option label="禁用" value="0"></el-option>
</el-select>
</el-form-item>
<el-form-item label="企业名称">
<el-input v-model="brand.companyName" placeholder="企业名称"></el-input>
</el-form-item>
<el-form-item label="品牌名称">
<el-input v-model="brand.brandName" placeholder="品牌名称"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit">查询</el-button>
</el-form-item>
</el-form>
<el-button type="success" @click="dialogVisible = true">新增</el-button>
<el-dialog
title="编辑品牌"
:visible.sync="dialogVisible"
width="30%">
<!--表单弹窗-->
<el-form ref="form" :model="brand" label-width="80px">
<el-form-item label="品牌名称">
<el-input v-model="brand.brandName"></el-input>
</el-form-item>
<el-form-item label="企业名称">
<el-input v-model="brand.companyName"></el-input>
</el-form-item>
<el-form-item label="排序">
<el-input v-model="brand.ordered"></el-input>
</el-form-item>
<el-form-item label="备注">
<el-input type="textarea" v-model="brand.description"></el-input>
</el-form-item>
<el-form-item label="状态">
<el-switch v-model="brand.status"
active-color="#13ce66"
inactive-color="#ff4949"
active-value="1"
inactive-value="0">
</el-switch>
</el-form-item>
<el-form-item>
<el-button type="primary" plain="true" @click="addBrand">提交</el-button>
<el-button @click="dialogVisible = false">取消</el-button>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
</span>
</el-dialog>
<el-button type="danger" @click="deleteByIds">批量删除</el-button>
<el-table
:data="tableData"
style="width: 100%"
:row-class-name="tableRowClassName"
@selection-change="handleSelectionChange">
<el-table-column
type="selection"
width="55">
</el-table-column>
<el-table-column
type="index"
width="55">
</el-table-column>
<el-table-column
prop="brandName"
label="品牌名称"
align="center">
</el-table-column>
<el-table-column
prop="companyName"
label="企业名称"
align="center">
</el-table-column>
<el-table-column
prop="ordered"
label="排序"
align="center">
</el-table-column>
<el-table-column
prop="status"
label="当前状态"
align="center">
</el-table-column>
<el-table-column
label="操作"
align="center">
<template slot-scope="scope">
<el-button type="primary" round @click="centerVisible=true">修改</el-button>
<!--修改数据的对话框表单-->
<el-dialog
title="修改品牌信息"
:visible.sync="centerVisible"
width="30%">
<el-form ref="form" :model=" brand" label-width="80px">
<el-form-item label="品牌名称">
<el-input v-model=" brand.brandName"></el-input>
</el-form-item>
<el-form-item label="企业名称">
<el-input v-model=" brand.companyName"></el-input>
</el-form-item>
<el-form-item label="排序">
<el-input v-model=" brand.ordered"></el-input>
</el-form-item>
<el-form-item label="备注">
<el-input type="textarea" v-model=" brand.description"></el-input>
</el-form-item>
<el-form-item label="状态">
<el-switch v-model=" brand.status"
active-text="启用"
inactive-text="禁用"
active-value="1"
inactive-value="0">
</el-switch>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="updateBrand(scope.row)">提交</el-button>
<el-button @click="centerVisible = false">取消</el-button>
</el-form-item>
</el-form>
</el-dialog>
<el-button type="danger" round @click="deleteById(scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<div class="block">
<el-pagination
:hide-on-single-page="value"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="currentPage"
:page-sizes="[5, 10, 15, 20]"
:page-size="5"
layout="total, sizes, prev, pager, next, jumper"
:total="totalCount">
</el-pagination>
</div>
</div>
<script src="js/vue.js"></script>
<script src="element-ui/lib/index.js"></script>
<link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css">
<script src="js/axios-0.18.0.js"></script>
<script>
new Vue({
el: "#app",
//页面加载完成后执行
mounted() {
this.selectAll();
},
data() {
return {
brand: {
status: '',
brandName: '',
companyName: '',
id: '',
ordered: '',
description: ''
},
//对话框是否展示
dialogVisible: false,
centerVisible: false,
tableData: [{
brandName: '',
companyName: '',
ordered: '',
status: ''
}],
//被选中的id数组
selectionIds: [],
multipleSelection: [],
//当前页码
totalCount: 100,
currentPage: 1,
pageSize: 5,
value: false
}
},
methods: {
onSubmit() {
this.selectAll();
},
selectAll() {
//当页面加载完成后,发送异步请求,获取数据
var _this = this; //提高this作用范围
axios({
method: "post",
url: "http://localhost:8080/login-register/brand/selectByPageAndCondition?currentPage=" + _this.currentPage + "&pageSize=" + _this.pageSize,
data:this.brand
}).then(function (resp) {
_this.tableData = resp.data.rows;
_this.totalCount = resp.data.totalCount;
})
},
//添加数据
addBrand() {
//发送ajax请求,添加数据
var _this = this;
axios({
method: "post",
url: "http://localhost:8080/login-register/brand/add",
data: _this.brand
}).then(function (resp) {
if (resp.data == "success") {
//添加成功
_this.dialogVisible = false;
_this.selectAll();
_this.$message({
message: '恭喜你,添加成功',
type: 'success'
});
}
})
},
deleteById(row) {
var _this = this;
this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
//发送ajax请求,添加数据
axios({
method: "post",
url: "http://localhost:8080/login-register/brand/deleteById",
data: row.id
}).then(function (resp) {
if (resp.data == "success") {
//添加成功
_this.selectAll();
_this.$message({
message: '恭喜你,删除成功',
type: 'success'
});
}
})
}).catch(() => {
this.$message({
type: 'info',
message: '已取消删除'
});
});
},
deleteByIds() {
this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
for (let i = 0; i < this.multipleSelection.length; i++) {
let selectionElement = this.multipleSelection[i];
this.selectionIds[i] = selectionElement.id;
}
var _this = this;
axios({
method: "post",
url: "http://localhost:8080/login-register/brand/deleteByIds",
data: _this.selectionIds
}).then(function (resp) {
if (resp.data == "success") {
//删除成功
_this.selectAll();
_this.$message({
message: '恭喜你,删除成功',
type: 'success'
});
}
})
}).catch(() => {
this.$message({
type: 'info',
message: '已取消删除'
});
});
},
updateBrand(row) {
var _this = this;
_this.brand.id = row.id;
this.$confirm('此操作将修改该数据, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
axios({
method: "post",
url: "http://localhost:8080/login-register/brand/updateBrand",
data: _this.brand
}).then(function (resp) {
if (resp.data == "success") {
//删除成功
_this.centerVisible = false,
_this.selectAll();
_this.$message({
message: '恭喜你,修改成功',
type: 'success'
});
}
})
}).catch(() => {
this.$message({
type: 'info',
message: '已取消修改'
});
});
},
tableRowClassName({row, rowIndex}) {
if (rowIndex === 1) {
return 'warning-row';
} else if (rowIndex === 3) {
return 'success-row';
}
return '';
},
//复选框选中后执行的方法
handleSelectionChange(val) {
this.multipleSelection = val;
},
//分页
handleSizeChange(val) {
this.pageSize = val;
this.selectAll();
},
handleCurrentChange(val) {
this.currentPage = val;
this.selectAll();
}
}
})
</script>
</body>
</html>