JIANGzihao0222

导航

 

   转眼,就已经放假一个月了,回家也整整一周了,本周回家,没有在学校那么多的时间去投入到学习中,但也进行了学习,主要是vue与elment-ui的一些组件的学习,对此,将在以下给出学习成果:

1.后端 记住密码设置:

Cookie c_username = new Cookie("username", URLEncoder.encode(username, "UTF-8") );
                 Cookie c_password = new Cookie("password", URLEncoder.encode(username, "UTF-8") );
                 //设置存活时间
                 c_username.setMaxAge(60*60*24*7);
                 c_password.setMaxAge(60*60*24*7);
                 //发送
                 response.addCookie(c_username);
                 response.addCookie(c_password);

前端 接收:

 value="${cookie.username.value}"

2.验证码登录:

工具类:

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://checkCode.jpg");
        String checkCode = CheckCodeUtil.outputVerifyImage(100,50,fos,4);
        System.out.println(checkCode);
    }


    /**
     * 输出随机验证码图片流,并返回验证码值(一般传入输出流,响应response页面端,Web项目用的较多)
     *
     * @param w 宽度
     * @param h 高度
     * @param os 输出流
     * @param verifySize 字数大小
     * @return
     * @throws IOException
     */
    public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException {
        String verifyCode = generateVerifyCode(verifySize);
        outputImage(w, h, 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);
            }

        }

    }
}

前端的实现:

<p>
            <input
                    type="text"
                    name="checkCode"
                    placeholder="请输入验证码"
            />
            <img id="checkCodeImg" src="/finish/checkCodeServlet">
            <a href="#" id="changeImg">看不清?</a>
        </p>
<script>
    document.getElementById("changeImg").onclick = function ()
    {

        document.getElementById("checkCodeImg").src = "/finish/checkCodeServlet?"+new Date().getMilliseconds();
    }
</script>

后端的调用:

public class checkCodeServlet extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //生成验证码
        ServletOutputStream os = response.getOutputStream();
        String checkCode = CheckCodeUtil.outputVerifyImage(100,50,os,4);
        //存入session
        HttpSession session = request.getSession();
        session.setAttribute("checkCode",checkCode);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
后端的验证:
@WebServlet("/registerServlet")
public class registerServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                request.setCharacterEncoding("UTF-8");
         String checkCode=request.getParameter("checkCode");
     //获取session
        HttpSession session = request.getSession();
       String CheckCode = (String) session.getAttribute("checkCode");
    if(CheckCode.equals(checkCode))
    {
        System.out.println("验证成功");
     }

效果展示:

3. 分页展示:

前端准备:

<el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalCount">
    </el-pagination>
<script>
new Vue({
el:"#app",
data() {
return {
//每页显示条数
pageSize:5,
//当前页码
currentPage: 1,
tableData:[],
//中页码
totalCount:50,
}
},
mounted()
{
this.selectAll();
},
methods: {
//查询所有 空为所有,不空为条件
selectAll()
{
//页面加载完成后发送数据。发送异步请求,获取数据
axios({
method:"post",
url:"http://localhost:8080/brand_demo/brand/selectByPageAndCondition?currentPage="+this.currentPage+"&pageSize="+this.pageSize,
//前端传入界面的两个值,一个currentPag,一个pageSize
                    data:this.brand
}).then(resp=>{
this.tableData = resp.data.rows;
this.totalCount = resp.data.count;
})
},
//设置pageSize
            handleSizeChange(val) {
console.log(`每页 ${val} 条`);
this.pageSize = val;
this.selectAll();
},
//设置currentPag
handleCurrentChange(val) {
console.log(`当前页: ${val}`);
this.currentPage = val;
this.selectAll();
}
},
})
</script>

后端代码:

 public void selectByPageAndCondition(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException
    {
        req.setCharacterEncoding("UTF-8");
        //接收参数  当前页码 每页展示条数
        String _currentPage = req.getParameter("currentPage");
        String _pageSize = req.getParameter("pageSize");
        int currentPage = Integer.parseInt(_currentPage);
        int pageSize = Integer.parseInt(_pageSize);
        //获取对象
        BufferedReader reader = req.getReader();
        String params = reader.readLine();
        //转为brand对象
        Brand brand = JSON.parseObject(params, Brand.class);
        System.out.println(brand);
        PageBean<Brand> pageBean = brandService.selectByPageAndCondition(currentPage, pageSize,brand);
        System.out.println(pageBean.getCount());
        //2. 将集合转换为JSON数据   序列化
        String jsonString = JSON.toJSONString(pageBean);
        System.out.println(jsonString);
        //3. 响应数据
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(jsonString);
    }

BrandService层:

 PageBean<Brand> selectByPageAndCondition(int currentPage,int pageSize,Brand brand);

BrandServiceimpl层:

 public PageBean<Brand> selectByPageAndCondition(int currentPage, int pageSize, Brand brand) {

        //调用BrandMapper.selectAll()
        //2. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //计算开始索引
        int begin = (currentPage - 1) * pageSize;
        int size = pageSize;
        //4. 调用方法
        //设置模糊查询
        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(currentPage,pageSize,brand);
        //查询总记录数
        int totalCount = mapper.selectTotalCountByCondition(brand);

        PageBean<Brand> pageBean = new PageBean<>();
        pageBean.setRows(rows);
        pageBean.setCount(totalCount);
        //释放资源
        sqlSession.close();

        return pageBean;



    }

BrandMapper层:

List<Brand> selectByPageAndCondition(@Param("begin") int begin, @Param("size") int size, @Param("brand") Brand brand);
    /*
    查询总条数
     */
    int selectTotalCountByCondition(Brand brand);

BrandMapper.xml

 <select id="selectByPageAndCondition" resultType="com.Jiang.Bean.Brand">
        select * from tb_brand
        <where>
            <if test="brand.brandName != null and brand.brandName !=''">
                and brand_name like #{brand.brandName}
            </if>

            <if test="brand.companyName != null and brand.companyName !=''">
                and company_name like #{brand.companyName}
            </if>

            <if test="brand.status != null">
                and status = #{brand.status}
            </if>
        </where>
        limit #{begin},#{size}
    </select>
    <select id="selectTotalCountByCondition" resultType="java.lang.Integer">
        select count(*) from tb_brand
        <where>
            <if test="brandName != null and brandName !=''">
                and brand_name like #{brandName}
            </if>

            <if test="companyName != null and companyName !=''">
                and company_name like #{companyName}
            </if>

            <if test="status != null">
                and status = #{status}
            </if>
        </where>
    </select>

4.批量删除和新增

前端:

<el-row>
        <el-button type="danger" plain @click="deleteByIds">批量删除</el-button>
        <el-button type="primary" plain @click="dialogVisible = true">新    增</el-button>
    </el-row>
<!--对话框表单-->
    <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-value="1"
                           inactive-value="0"
                ></el-switch>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="addBrand">提交</el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
            </el-form-item>
        </el-form>
    </el-dialog>
<!--表格--> <template> <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="50"> </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" align="center" label="当前状态"> </el-table-column> <el-table-column align="center" label="操作"> <el-row> <el-button type="primary">修改</el-button> <el-button type="danger">删除</el-button> </el-row> </el-table-column> </el-table> </template>
<script>
// import fa from "./element-ui/src/locale/lang/fa";
new Vue({
el:"#app",
data() {
return {
//绑定选中行的数据
multipleSelection:[],

brand: {
status: '',
brandName: '',
companyName:'',
id:'',
ordered:'',
description:''
},
//每页显示条数
pageSize:5,
//当前页码
currentPage: 1,
dialogVisible: false,
tableData:[],
//被选中的ids
selectIds:[],
totalCount:50,
}
},
mounted()
{
this.selectAll();
},
methods: {
//查询所有 空为所有,不空为条件
selectAll()
{
// var _this = this;
// //页面加载完成后发送数据。发送异步请求,获取数据
// axios({
// method:"get",
// url:"http://localhost:8080/brand_demo/brand/SelectAll",
// }).then(function (resp)
// {
// _this.tableData = resp.data;
// })

//页面加载完成后发送数据。发送异步请求,获取数据
axios({
method:"post",
url:"http://localhost:8080/brand_demo/brand/selectByPageAndCondition?currentPage="+this.currentPage+"&pageSize="+this.pageSize,
data:this.brand
}).then(resp=>{
this.tableData = resp.data.rows;
this.totalCount = resp.data.count;
})

// .then(function (resp)
// {
// _this.tableData = resp.data.rows;
// _this.totalCount = resp.data.count;
// })
},

addBrand(){
var _this = this;
console.log(this.brand);
axios({
method:"post",
url:"http://localhost:8080/brand_demo/brand/Add",
data:_this.brand
}).then(function (resp){
if(resp.data == "success")
{
//关闭窗口
_this.dialogVisible = false;
_this.selectAll();
//弹出消息提升
_this.$message({
message: '添加成功',
type: 'success'
});
}
})
},

// 批量删除
deleteByIds(){
//创建id数组
for (let i = 0 ; i < this.multipleSelection.length;i++)
{
//获取选择的行的数据
let selectElement = this.multipleSelection[i];
this.selectIds[i] = selectElement.id;
}
var _this = this;


//弹出确认提示框

this.$confirm('此操作将永久删除所选数据, 是否继续?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
//用户点击确认按钮

//发送请求
axios({
method:"post",
url:"http://localhost:8080/brand_demo/brand/deleteByids",
data:_this.selectIds
}).then(function (resp){
if(resp.data == "success")
{
//关闭窗口
_this.selectAll();
//弹出消息提升
_this.$message({
message: '删除成功',
type: 'success'
});
}
})

}).catch(() => {
this.$message({
type: 'info',
message: '已取消删除'
});
});
},

},
})
</script>

后端实现

BrandServlet:

 public void Add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        request.setCharacterEncoding("UTF-8");
        //获取请求体
        BufferedReader reader = request.getReader();
        String params = reader.readLine();
        Brand brand = JSON.parseObject(params,Brand.class);
        System.out.println(brand);
        brandService.Add(brand);
        response.getWriter().write("success");
    }
    /*
    批量删除
     */
    public void deleteByids(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        request.setCharacterEncoding("UTF-8");
        //获取请求体
        BufferedReader reader = request.getReader();
        String params = reader.readLine();

        int[] ids = JSON.parseObject(params, int[].class);
        System.out.println(ids);
        brandService.deleteByIds(ids);
        response.getWriter().write("success");
    }

BrandService层:

 void Add(Brand brand);
 void deleteByIds(int []ids);

BrandServiceimpl层:

public PageBean<Brand> selectByPageAndCondition(int currentPage, int pageSize, Brand brand) {

        //调用BrandMapper.selectAll()
        //2. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
        //3. 获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //计算开始索引
        int begin = (currentPage - 1) * pageSize;
        int size = pageSize;
        //4. 调用方法
        //设置模糊查询
        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(currentPage,pageSize,brand);
        //查询总记录数
        int totalCount = mapper.selectTotalCountByCondition(brand);

        PageBean<Brand> pageBean = new PageBean<>();
        pageBean.setRows(rows);
        pageBean.setCount(totalCount);
        //释放资源
        sqlSession.close();

        return pageBean;



    }

BrandMapper层

 void add(Brand brand);
    /*
    批量删除
     */
    void deleteByIds(@Param("ids") int []ids);

BrandMapper.xml层:

 <insert id="add">
        insert into tb_brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status})
    </insert>
    <delete id="deleteByIds">
        delete from tb_brand where id in
        <foreach collection="ids" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>

5.service优化

旨在通过设定一个接口,用类基础这个接口,这样就可以方便更改类,若有需要改变的代码,就把web中接口类进行更改即可

 6.servlet进行优化:

先是进行一个基本类的编写

 BaseServlet
public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求路径
        String uri = req.getRequestURI();
        //获取方法名
        int index = uri.lastIndexOf('/');
        String methodName = uri.substring(index + 1);
        //执行方法
        //获取Servlet对象
        Class<? extends BaseServlet> aClass = this.getClass();
        //获取Method对象
        try {
            Method method = aClass.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //执行方法
            try {
                method.invoke(this,req,resp);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }
}

 后进行继承即可:

BrandServlet
@WebServlet("/brand/*")
public class BrandServlet extends BaseServlet{
    private BrandService brandService = new BrandServiceimpl();
    public void SelectAll(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException
    {
        List<Brand> brands = brandService.SelectAll();

        //2. 将集合转换为JSON数据   序列化
        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
    {
        request.setCharacterEncoding("UTF-8");
        //获取请求体
        BufferedReader reader = request.getReader();
        String params = reader.readLine();
        Brand brand = JSON.parseObject(params,Brand.class);
        System.out.println(brand);
        brandService.Add(brand);
        response.getWriter().write("success");
    }
    /*
    批量删除
     */
    public void deleteByids(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        request.setCharacterEncoding("UTF-8");
        //获取请求体
        BufferedReader reader = request.getReader();
        String params = reader.readLine();

        int[] ids = JSON.parseObject(params, int[].class);
        System.out.println(ids);
        brandService.deleteByIds(ids);
        response.getWriter().write("success");
    }

    public void selectByPage(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException
    {
        req.setCharacterEncoding("UTF-8");
        //接收参数  当前页码 每页展示条数
        String _currentPage = req.getParameter("currentPage");
        String _pageSize = req.getParameter("pageSize");
        int currentPage = Integer.parseInt(_currentPage);
        int pageSize = Integer.parseInt(_pageSize);
        PageBean<Brand> pageBean = brandService.selectByPage(currentPage, pageSize);
        System.out.println(pageBean.getCount());
        //2. 将集合转换为JSON数据   序列化
        String jsonString = JSON.toJSONString(pageBean);
        System.out.println(jsonString);
        //3. 响应数据
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(jsonString);
    }


//    条件查询
    public void selectByPageAndCondition(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException
    {
        req.setCharacterEncoding("UTF-8");
        //接收参数  当前页码 每页展示条数
        String _currentPage = req.getParameter("currentPage");
        String _pageSize = req.getParameter("pageSize");
        int currentPage = Integer.parseInt(_currentPage);
        int pageSize = Integer.parseInt(_pageSize);
        //获取对象
        BufferedReader reader = req.getReader();
        String params = reader.readLine();
        //转为brand对象
        Brand brand = JSON.parseObject(params, Brand.class);
        System.out.println(brand);
        PageBean<Brand> pageBean = brandService.selectByPageAndCondition(currentPage, pageSize,brand);
        System.out.println(pageBean.getCount());
        //2. 将集合转换为JSON数据   序列化
        String jsonString = JSON.toJSONString(pageBean);
        System.out.println(jsonString);
        //3. 响应数据
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(jsonString);
    }
}

这样写的好处将对同一个类的servlet的书写放到一个servlet,所注意的仅是@WebServlet("/brand/*"),这里的/brand + /方法名即可,写入前端url即可调用该方法。

7.VMware的安装,乌班图系统的安装。

完成了VMware的安装,乌班图系统的安装,

然后,本周将黑马程序员的web剩余课程进行复习,又学习了大数据的相关内容,安装了VMware,后进行hadoop的安装。

  

posted on 2023-07-16 20:41  实名吓我一跳  阅读(21)  评论(0)    收藏  举报