目录
16.SelectByIdServlet(实现回显--update中的模块)
19.UserMapper.xml(User映射文件,没有用到)
20.Mybatis-config.xml(Mybatis实现连接数据库)
26.index.html(主页面,显示brand.jsp的链接)
(算了,不想展示了,如果有哪位朋友愿意来看的话,给我留言我私信给你)


- package com.itheima.mapper;
-
- import com.itheima.pojo.Brand;
- import org.apache.ibatis.annotations.*;
-
- import java.util.List;
-
- public interface BrandMapper {
-
- /**
- * dao层查询所有的操作
- * @return
- */
- @Select("select * from tb_brand")
- @ResultMap("brandResultMap")
- List
selectAll(); -
- /**
- * dao层添加数据
- * @param brand
- */
- @Insert("insert into tb_brand values (null,#{brandName},#{companyName},#{ordered},#{description},#{status})")
- void add(Brand brand);
-
- /**
- * 更改数据前的回显数据,图像化根据id查询
- * @param id
- * @return
- */
- @Select("select * from tb_brand where id = #{id}")
- @ResultMap("brandResultMap")
- Brand selectById(int id);
-
- /**
- * 修改语句
- * @param brand
- */
- @Update("update tb_brand set brand_name=#{brandName},company_name=#{companyName},ordered=#{ordered},description=#{description},status=#{status} where id=#{id}")
- void update(Brand brand);
-
- @Delete("delete from tb_brand where id = #{id}")
- void delete(int id);
- }
- package com.itheima.mapper;
-
- import com.itheima.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.itheima.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 Brand(Integer id, String brandName, String companyName, Integer ordered, String description,
- Integer status) {
- super();
- this.id = id;
- this.brandName = brandName;
- this.companyName = companyName;
- this.ordered = ordered;
- this.description = description;
- this.status = status;
- }
- public Brand() {
- }
- @Override
- public String toString() {
- return "Brand [id=" + id + ", brandName=" + brandName + ", companyName=" + companyName + ", ordered=" + ordered
- + ", description=" + description + ", status=" + 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;
- }
- }
- package com.itheima.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.itheima.service;
-
- import com.itheima.Util.SqlSessionFactoryUtils;
- import com.itheima.mapper.BrandMapper;
- import com.itheima.pojo.Brand;
- import org.apache.ibatis.session.SqlSession;
- import org.apache.ibatis.session.SqlSessionFactory;
-
- import java.util.List;
-
- public class BrandService {
- SqlSessionFactory factory= SqlSessionFactoryUtils.getSqlSessionFactory();
-
- /**
- * service查询所有的功能
- * @return
- */
- public List
selectAll() { - //调用BrandMapper.selectAll()方法
-
-
- //获取SqlSession
- SqlSession sqlSession = factory.openSession();
-
- //获取BrandMapper
- BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
-
- //调用方法
- List
brands = mapper.selectAll(); -
- //关闭sqlSession
- sqlSession.close();
-
- //返回brands
- return brands;
- }
-
- /**
- * 添加数据库
- * @return
- */
- public void add(Brand brand) {
- //调用BrandMapper.selectAll()方法
-
-
- //获取SqlSession
- SqlSession sqlSession = factory.openSession(true);
-
- //获取BrandMapper
- BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
-
- //调用方法
- mapper.add(brand);
-
- //关闭sqlSession
- sqlSession.close();
-
- }
- /**
- * 根据id查询
- * @return
- */
- public Brand selectById(int id) {
- //调用BrandMapper.selectAll()方法
-
-
- //获取SqlSession
- SqlSession sqlSession = factory.openSession();
-
- //获取BrandMapper
- BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
-
- //调用方法
- Brand brand = mapper.selectById(id);
-
- //关闭sqlSession
- sqlSession.close();
-
- //返回brand
- return brand;
- }
-
- public void update(Brand brand) {
- //调用BrandMapper.selectAll()方法
-
-
- //获取SqlSession
- SqlSession sqlSession = factory.openSession(true);
-
- //获取BrandMapper
- BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
-
- //调用方法
- mapper.update(brand);
-
- //关闭sqlSession
- sqlSession.close();
-
- }
- public void delete(int id) {
- //调用BrandMapper.selectAll()方法
-
-
- //获取SqlSession
- SqlSession sqlSession = factory.openSession(true);
-
- //获取BrandMapper
- BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
-
- //调用方法
- mapper.delete(id);
-
- //关闭sqlSession
- sqlSession.close();
-
- }
- }
- package com.itheima.service;
-
- import com.itheima.Util.SqlSessionFactoryUtils;
- import com.itheima.mapper.UserMapper;
- import com.itheima.pojo.User;
- import org.apache.ibatis.session.SqlSession;
- import org.apache.ibatis.session.SqlSessionFactory;
-
- public class UserService {
- //获取util工具包的SqlSessionFactory
- SqlSessionFactory factory= SqlSessionFactoryUtils.getSqlSessionFactory();
- //调用UserMapper,构成方法,来让servlet进行下一步操作
-
- /**
- * 登录
- * @param username
- * @param password
- * @return
- */
- public User login(String username,String password){
-
- //获取SqlSession,查找不需要事务,所以选择不提交事务
- SqlSession sqlSession = factory.openSession();
-
- //获取UserMapper
- UserMapper mapper = sqlSession.getMapper(UserMapper.class);
-
- //调用方法
- User user = mapper.select(username, password);
-
- //关闭sqlSession
- sqlSession.close();
-
- //返回user
- return user;
- }
-
- public Boolean register(User user) {
-
- //获取SqlSession,查找不需要事务,所以选择不提交事务
- SqlSession sqlSession = factory.openSession();
-
- //获取UserMapper
- UserMapper mapper = sqlSession.getMapper(UserMapper.class);
-
- //判断用户名是否存在
- User u = mapper.selectByUsername(user.getUsername());
-
- if ( u == null ){
- //用户名不存在
- mapper.add(user);
- //提交事务
- sqlSession.commit();
- }
- //关闭sqlSession,释放资源
- sqlSession.close();
- return u == null;
- }
- }
- package com.itheima.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 {
- FileOutputStream fos = new FileOutputStream("D://152//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);
- }
-
- }
-
- }
- }
-
- package com.itheima.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;
-
- public class SqlSessionFactoryUtils {
-
- private static SqlSessionFactory sqlSessionFactory;
-
- //静态代码快会随着类的加载二自动执行,并且只执行一次
- static
- {
- String resource = "mybatis-config.xml";//现在在resource根目录下
- InputStream inputStream = null;
- try {
- inputStream = Resources.getResourceAsStream(resource);
- } catch (IOException e) {
- e.printStackTrace();
- }
- sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
- }
-
- public static SqlSessionFactory getSqlSessionFactory(){
- return sqlSessionFactory;
- }
- }
- package com.itheima.web;
-
- import com.itheima.pojo.Brand;
- import com.itheima.service.BrandService;
-
- import javax.servlet.*;
- import javax.servlet.http.*;
- import javax.servlet.annotation.*;
- import java.io.IOException;
-
- @WebServlet("/addServlet")
- public class AddServlet extends HttpServlet {
- private BrandService service = new BrandService();
-
- @Override
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
-
- //解决乱码问题
- request.setCharacterEncoding("UTF-8");
-
- //1.接受表单提交的数据,封装成一个brand对象的数据
- String brandName = request.getParameter("brandName");
- String companyName = request.getParameter("companyName");
- String ordered = request.getParameter("ordered");
- String description = request.getParameter("description");
- String status = request.getParameter("status");
-
- Brand brand = new Brand(null,brandName,companyName,Integer.parseInt(ordered),description,Integer.parseInt(status));
-
-
- //2.调用service添加数据
- service.add(brand);
-
- //3.转发到查询所有的servlet
- request.getRequestDispatcher("/selectAllServlet").forward(request,response);
-
- }
-
- @Override
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- this.doGet(request, response);
- }
- }
- package com.itheima.web;
-
- import com.itheima.Util.CheckCodeUtil;
-
- import javax.servlet.*;
- import javax.servlet.http.*;
- import javax.servlet.annotation.*;
- import java.io.FileOutputStream;
- import java.io.IOException;
-
- @WebServlet("/checkCodeServlet")
- public class CheckCodeServlet extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- //生成验证码
- ServletOutputStream outputStream = response.getOutputStream();
- String checkCode = CheckCodeUtil.outputVerifyImage(100, 50, outputStream, 4);
-
- //把生成的验证码存入到session对象
- HttpSession session = request.getSession();
- session.setAttribute("checkCodeGen",checkCode);
- }
-
- @Override
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- this.doGet(request, response);
- }
- }
- package com.itheima.web;
-
- import com.itheima.pojo.Brand;
- import com.itheima.service.BrandService;
-
- import javax.servlet.*;
- import javax.servlet.http.*;
- import javax.servlet.annotation.*;
- import java.io.IOException;
-
- @WebServlet("/deleteServlet")
- public class DeleteServlet extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
-
- //1.传入id
- String id = request.getParameter("id");
-
- //2.调用对象
- BrandService service = new BrandService();
- service.delete(Integer.parseInt(id));
-
- //3.把id传入到delete
- request.setAttribute("id",id);
-
- //3.强求转发到主界面
- request.getRequestDispatcher("/delete.jsp").forward(request,response);
- }
-
- @Override
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- this.doGet(request, response);
- }
- }
- package com.itheima.web;
-
- import com.itheima.pojo.User;
- import com.itheima.service.UserService;
-
- import javax.servlet.*;
- import javax.servlet.http.*;
- import javax.servlet.annotation.*;
- import java.io.IOException;
-
- @WebServlet("/loginServlet")
- public class LoginServlet extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
-
- //1.获取表单传递的参数(实际上和php很类似,接受的表单信息,其实就是input的name属性)
- String username = request.getParameter("username");
- String password = request.getParameter("password");
- //获取复选框数据
- String remember = request.getParameter("remember");
-
- //2.获取UserService的方法来去查询
- UserService service = new UserService();
- User user = service.login(username, password);
-
- //进行条件判断
- if(user != null ){
-
- //判断用户选中了remember,最好写成("1".equals(remember)),以免造成空指针异常
- if("1".equals(remember)){
- //确定数值等于1
-
- //1.创建cookie(可以把username当作一个cookie,把另外一个password当作另一个cookie)
- Cookie c_cookie = new Cookie("username",username);
- Cookie p_cookie = new Cookie("password",password);
-
- //1.1设置此cookie在浏览器存活的时间
- c_cookie.setMaxAge(60*60*24*7);
- p_cookie.setMaxAge(60*60*24*7);
-
- //2.发送cookie
- response.addCookie(c_cookie);
- response.addCookie(p_cookie);
- }
- //提前打开session
- HttpSession session = request.getSession();
- session.setAttribute("user",user);
-
- //登陆成功,跳转到查询所有的主页面(index.html),否则这个index.html将毫无意义(两个方法,请求转发(有参数),重定向)
- String contextPath = request.getContextPath();//动态获取地址
- response.sendRedirect(contextPath+"/index.html");
- }else{
- //登录失败,提供失败信息,跳转到login.jsp页面,引导客户进行注册
-
- //将错误信息存储到request里面,利用请求转发,来让register.jsp页面显示此错误信息
- request.setAttribute("login_msg","用户名或密码错误,请您重新登录");
- request.getRequestDispatcher("/login.jsp").forward(request,response);
- }
- }
-
- @Override
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- this.doGet(request, response);
- }
- }
- package com.itheima.web;
-
- import com.itheima.pojo.User;
- import com.itheima.service.UserService;
-
- import javax.servlet.*;
- import javax.servlet.http.*;
- import javax.servlet.annotation.*;
- import java.io.IOException;
-
- @WebServlet("/registerServlet")
- public class RegisterServlet extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
-
- //解决乱码问题
- request.setCharacterEncoding("UTF-8");
-
- //获取表单参数(与用户输入的验证码)
- String username = request.getParameter("username");
- String password = request.getParameter("password");
- String checkCode = request.getParameter("checkCode");
-
- //获取session,把从session获取的checkCodeGen这个值,强转为String,利于之后的比对
- HttpSession session = request.getSession();
- String checkCodeGen = (String)session.getAttribute("checkCodeGen");
-
- User user = new User();
- user.setUsername(username);
- user.setPassword(password);
-
- //验证码的比对(前提是这个checkCode(用户填写的不准为空))
- if(!checkCodeGen.equals(checkCode)){
- //不允许注册
- //如果验证码比对不正确,则就给出提示信息
- request.setAttribute("register_msg", "验证码错误");
- request.getRequestDispatcher("/register.jsp").forward(request, response);
- return;//如果执行到return后,就不会在向下继续执行到mysql了
- }
-
- //调取userService方法完成对数据的添加
- UserService service = new UserService();
- Boolean register = service.register(user);
-
- //判断注册成功与否
- if (username.length()!=0 && password .length()!=0) {
- if (register) {
- //register为true,则跳转到登录页面(因为还要显示注册成功,请登录的信息,所以使用请求转发比较稳妥)
- request.setAttribute("register_msg", "注册成功,请登录");
- request.getRequestDispatcher("/login.jsp").forward(request, response);
-
- } else {
- //register为false
- request.setAttribute("register_msg", "用户已经存在,请重新注册");
- request.getRequestDispatcher("/register.jsp").forward(request, response);
- }
- }else{
- //用户名和密码为空的情况下
- request.setAttribute("error_msg", "账号或密码为空,请重新注册");
- request.getRequestDispatcher("/register.jsp").forward(request, response);
- }
- }
- @Override
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- this.doGet(request, response);
- }
- }
- package com.itheima.web;
-
- import com.itheima.pojo.Brand;
- import com.itheima.service.BrandService;
-
- import javax.servlet.*;
- import javax.servlet.http.*;
- import javax.servlet.annotation.*;
- import java.io.IOException;
- import java.util.List;
-
- @WebServlet("/selectAllServlet")
- public class SelectAllServlet extends HttpServlet {
- private BrandService service = new BrandService();
-
- @Override
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
-
- //调用对应的BrandService完成查询
- List
brands = service.selectAll(); -
- //存入request域中
- //void setAttribute(String name,Object o)存储数据到request域中
- request.setAttribute("brands",brands);
-
- //请求转发
- request.getRequestDispatcher("/brand.jsp").forward(request,response);
- }
-
- @Override
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- this.doGet(request, response);
- }
- }
- package com.itheima.web;
-
- import com.itheima.pojo.Brand;
- import com.itheima.service.BrandService;
-
- import javax.servlet.*;
- import javax.servlet.http.*;
- import javax.servlet.annotation.*;
- import java.io.IOException;
-
-
- @WebServlet("/selectByIdServlet")
- public class SelectByIdServlet extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
-
- //1,在brand.jsp里面传输了一个id,之前在php里面学过,就不在赘述了(接收id)
- String id = request.getParameter("id");
-
- //id有了之后,把这个id传入到SelectById的形参里面去(调用对应的service进行查询)
- BrandService service = new BrandService();
- Brand brand = service.selectById(Integer.parseInt(id));
-
- //储存到request域中
- request.setAttribute("brand",brand);
-
- //转发到update.jsp中
- request.getRequestDispatcher("/update.jsp").forward(request,response);
-
- }
-
- @Override
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- this.doGet(request, response);
- }
- }
- package com.itheima.web;
-
- import com.itheima.pojo.Brand;
- import com.itheima.service.BrandService;
-
- import javax.servlet.*;
- import javax.servlet.http.*;
- import javax.servlet.annotation.*;
- import java.io.IOException;
-
- @WebServlet("/updateServlet")
- public class UpdateServlet extends HttpServlet {
- @Override
- protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
-
- //解决乱码问题
- request.setCharacterEncoding("UTF-8");
-
- //1.接受表单提交的数据,封装成一个brand对象的数据
- String id = request.getParameter("id");
- String brandName = request.getParameter("brandName");
- String companyName = request.getParameter("companyName");
- String ordered = request.getParameter("ordered");
- String description = request.getParameter("description");
- String status = request.getParameter("status");
-
- Brand brand = new Brand(Integer.parseInt(id),brandName,companyName,Integer.parseInt(ordered),description,Integer.parseInt(status));
-
- //调用service更改数据
- BrandService service = new BrandService();
- service.update(brand);
-
- //3.转发到查询所有的servlet
- request.getRequestDispatcher("/selectAllServlet").forward(request,response);
-
- }
-
- @Override
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- this.doGet(request, response);
- }
- }
- "1.0" encoding="UTF-8" ?>
- mapper
- PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="com.itheima.mapper.BrandMapper">
-
- <resultMap id="brandResultMap" type="brand">
- <result column="brand_name" property="brandName">result>
- <result column="company_name" property="companyName">result>
- resultMap>
-
-
-
- mapper>
- "1.0" encoding="UTF-8" ?>
- configuration
- PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-config.dtd">
- <configuration>
-
- <typeAliases>
- <package name="com.itheima.pojo"/>
- typeAliases>
-
- <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:///db1?useSSL=false&useServerPrepStmts=true"/>
- <property name="username" value="root"/>
- <property name="password" value="root"/>
- dataSource>
- environment>
- environments>
- <mappers>
-
- <package name="com.itheima.mapper"/>
- mappers>
- configuration>
- * {
- 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: red;
- }
-
- 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;
- }
- * {
- 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;
- }



- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
-
- <html>
-
- <head>
- <meta charset="UTF-8">
- <title>添加品牌title>
- head>
- <body>
- <h3>添加品牌h3>
- <form action="/brand_demo/addServlet" method="post">
- 品牌名称:<input type="text" name="brandName"><br>
- 企业名称:<input type="text" name="companyName"><br>
- 排序: <input type="text" name="ordered"><br>
- 描述信息:<textarea rows="5" cols="3" name="description">textarea><br>
- 状态:
- <input type="radio" name="status"value="0">禁用
- <input type="radio" name="status"value="1">启用<br>
-
- <input type="submit" value="提交">
- form>
- body>
- html>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
- <html>
- <script>
- function add(){
- let flag = window.confirm("您确定要添加数据吗?");
- if (flag==true){
- window.location="/brand_demo/addBrand.jsp";
- }else{
- window.location="/brand_demo/brand.jsp";
- }
- }
- function del(){
- let flag = window.confirm("您确定要删除数据吗?");
- if (flag==true){
- window.location="/brand_demo/brand.jsp";
- }else{
- return 0;
- }
- }
- script>
- <head>
- <title>Titletitle>
- head>
- <body>
- <center>
- <h1>欢迎${user.username}访问阿里云数据库h1>
- <input type="button" value="添加数据" onclick="add()">
- <hr>
- <table border="1" cellspacing="0" width="800">
- <tr>
- <th>序号th>
- <th>品牌名称th>
- <th>企业名称th>
- <th>排序th>
- <th>品牌介绍th>
- <th>状态th>
- <th>操作th>
-
- tr>
- <c:forEach items="${brands}" var="brand" varStatus="status">
- <tr align="center">
- <%-- <td>${brand.id}td>--%>
- <td>${status.count}td>
- <td>${brand.brandName}td>
- <td>${brand.companyName}td>
- <td>${brand.ordered}td>
- <td>${brand.description}td>
- <c:if test="${brand.status == 0 }">
- <td>禁用td>
- c:if>
- <c:if test="${brand.status == 1 }">
- <td>启用td>
- c:if>
- <td><a href="/brand_demo/selectByIdServlet?id=${brand.id}">修改a>/
- <a href="/brand_demo/deleteServlet?id=${brand.id}" onclick="del()">删除a>td>
- tr>
- c:forEach>
- table>
- center>
- body>
- html>
- <%--
- Created by IntelliJ IDEA.
- User: HP
- Date: 2022/8/21
- Time: 16:05
- To change this template use File | Settings | File Templates.
- --%>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <html>
- <script>
- function del(){
- let flag = window.confirm("您确定要返回主页面吗?");
- if (flag=true){
- window.location="/brand_demo/selectAllServlet";
- }
- }
- script>
- <head>
- <title>Deletetitle>
- head>
- <body>
- <center>
- <h1>提醒您!!<br>
- 已经删除了id为${id}的数据h1>
- <input type="button"value="返回主页面"onclick="del()">
- center>
- body>
- html>
- html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Titletitle>
- head>
- <body>
- <center>
- <h2>h2>
- <h1> 欢迎访问h1>
- <a href="/brand_demo/selectAllServlet" >点击查询所有数据库数据a>
- center>
- body>
- html>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- html>
- <html lang="en">
-
- <head>
- <meta charset="UTF-8">
- <title>logintitle>
- <link href="css/login.css" rel="stylesheet">
- head>
-
- <body>
- <div id="loginDiv" style="height: 350px">
- <%--action一般指向处理这个页面的servlet,当点击submit的时候,就会把表单里面面的变量,提交到对应的servlet里面去--%>
- <form action="/brand_demo/loginServlet" id="form">
- <h1 id="loginMsg">LOGIN INh1>
- <div id="errorMsg">${login_msg}${register_msg}div>
- <p>Username:<input id="username" name="username" type="text" value="${cookie.username.value}">p>
- <p>Password:<input id="password" name="password" type="password" value="${cookie.password.value}">p>
- <p>Remember:<input id="remember" value="1" 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.jsp">没有账号?a>
- div>
- form>
- div>
-
- body>
- html>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- 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="/brand_demo/registerServlet" method="post">
- <table>
- <tr>
- <td>用户名td>
- <td class="inputs">
- <input name="username" type="text" id="username">
- <br>
- <span id="username_err" class="err_msg" >${register_msg}${error_msg}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 id="CheckCodeImage" src="/brand_demo/checkCodeServlet" onclick="check()">
- <a href="#" id="changeImg" onclick="check()">看不清?a>
- td>
- tr>
- table>
- <div class="buttons">
- <input value="注 册" type="submit" id="reg_btn">
- div>
- <br class="clear">
- form>
-
- div>
- <script>
- function check(){
- // 利用时间来当作参数来获取图片
- let milliseconds = new Date().getMilliseconds();//获取当前时间的毫米值
- document.getElementById("CheckCodeImage").src = "/brand_demo/checkCodeServlet?"+milliseconds;
- }
- script>
- body>
- html>
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
- <html>
- <head>
- <title>修改数据title>
- head>
- <body>
- <h3>回显数据,修改数据h3>
- <h3>可以封装成一个brand的数据,然后利用el表达式来回显数据h3>
- <form action="/brand_demo/updateServlet" method="post">
- <%-- 隐藏域--%>
- <input type="hidden" name="id" value="${brand.id}">
- 品牌名称:<input type="text" name="brandName" value="${brand.brandName}"><br>
- 企业名称:<input type="text" name="companyName"value="${brand.companyName}"><br>
- 排序: <input type="text" name="ordered" value="${brand.ordered}"><br>
- 描述信息:<textarea rows="10" cols="3" name="description" >${brand.description}textarea><br>
- 状态:
- <c:if test="${brand.status == 0}">
- <input type="radio" name="status"value="0" checked >禁用
- <input type="radio" name="status"value="1">启用<br>
- c:if>
- <c:if test="${brand.status == 1}">
- <input type="radio" name="status"value="0" >禁用
- <input type="radio" name="status"value="1" checked>启用<br>
- c:if>
- <input type="submit" value="提交">
- form>
-
- body>
- html>
- "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.0modelVersion>
-
- <groupId>org.examplegroupId>
- <artifactId>brand_demoartifactId>
- <version>1.0-SNAPSHOTversion>
-
- <properties>
- <maven.compiler.source>18maven.compiler.source>
- <maven.compiler.target>18maven.compiler.target>
- properties>
-
- <packaging>warpackaging>
-
- <build>
- <plugins>
-
- <plugin>
- <groupId>org.apache.tomcat.mavengroupId>
- <artifactId>tomcat7-maven-pluginartifactId>
- <version>2.2version>
- plugin>
- <plugin>
- <groupId>org.apache.maven.pluginsgroupId>
- <artifactId>maven-compiler-pluginartifactId>
- <configuration>
- <source>17source>
- <target>17target>
- configuration>
- plugin>
- plugins>
- build>
-
- <dependencies>
- <dependency>
- <groupId>javax.servletgroupId>
- <artifactId>javax.servlet-apiartifactId>
- <version>3.1.0version>
- <scope>providedscope>
- dependency>
-
- <dependency>
- <groupId>commons-iogroupId>
- <artifactId>commons-ioartifactId>
- <version>2.6version>
- dependency>
-
- <dependency>
- <groupId>org.mybatisgroupId>
- <artifactId>mybatisartifactId>
- <version>3.5.5version>
- dependency>
-
- <dependency>
- <groupId>mysqlgroupId>
- <artifactId>mysql-connector-javaartifactId>
- <version>8.0.29version>
- dependency>
-
- <dependency>
- <groupId>junitgroupId>
- <artifactId>junitartifactId>
- <version>4.13.2version>
- <scope>Testscope>
- dependency>
-
- <dependency>
- <groupId>org.slf4jgroupId>
- <artifactId>slf4j-apiartifactId>
- <version>1.7.36version>
- dependency>
-
- <dependency>
- <groupId>ch.qos.logbackgroupId>
- <artifactId>logback-classicartifactId>
- <version>1.2.3version>
- dependency>
-
- <dependency>
- <groupId>ch.qos.logbackgroupId>
- <artifactId>logback-coreartifactId>
- <version>1.2.3version>
- dependency>
- <dependency>
- <groupId>jstlgroupId>
- <artifactId>jstlartifactId>
- <version>1.2version>
- dependency>
- <dependency>
- <groupId>taglibsgroupId>
- <artifactId>standardartifactId>
- <version>1.1.2version>
- dependency>
- dependencies>
- project>