一、准备环境
1.引入坐标
<?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>BrandTest</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
</plugin>
</plugins>
</build>
<dependencies>
<!--mysql driver-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.16</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
</dependencies>
</project>
2.创建三层架构的包结构
com.jkj.web
com.jkj.service
com.jkj.mapper
com.jkj.pojo
com.jkj.util
注意:在resources创建com/jkj/mapper,用来放xxxMapper.xml文件。
3.数据库表 tb_brand和tb_login(数据库名:mybatis)
自己往表里添加数据。
4.实体类 Brand
package com.jkj.pojo;
public class Brand {
private Integer id;
private String brandName;
private String companyName;
private Integer ordered;
private String description;
private Integer status;
public Brand() {
}
public Brand(Integer id, String brandName, String companyName, Integer ordered, String description, Integer status) {
this.id = id;
this.brandName = brandName;
this.companyName = companyName;
this.ordered = ordered;
this.description = description;
this.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;
}
@Override
public String toString() {
return "Brand{" +
"id=" + id +
", brandName='" + brandName + '\'' +
", companyName='" + companyName + '\'' +
", ordered=" + ordered +
", description='" + description + '\'' +
", status=" + status +
'}';
}
}
5.实体类 User
package com.jkj.pojo;
public class User {
private Integer id;
private String username;
private String password;
public User() {
}
public User(Integer id, String username, String password) {
this.id = id;
this.username = username;
this.password = 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 + '\'' +
'}';
}
}
6.mybatis-config.xml
<?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>
<typeAliases>
<package name="com.jkj.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://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.jkj.mapper"/>
</mappers>
</configuration>
7.BrandMapper.xml
package com.jkj.mapper;
import com.jkj.pojo.Brand;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface BrandMapper {
}
8.BrandMapper接口
<?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">
<mapper namespace="com.jkj.mapper.BrandMapper">
</mapper>
9.UserMapper.xml
<?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">
<mapper namespace="com.jkj.mapper.UserMapper">
</mapper>
10.UserMapper接口
package com.jkj.mapper;
import com.jkj.pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
public interface UserMapper {
}
11.SessionFactory工具类
可参照:SessionFactory工具类 进行学习。
package com.jkj.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";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
e.printStackTrace();
}
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
public static SqlSessionFactory getSqlSessionFactory(){
return sqlSessionFactory;
}
}
二、登录
1.用户登录及记住用户
1.编写UserMapper
public interface UserMapper {
//根据用户名和密码查询用户对象
@Select("select * from tb_login where username=#{username} and password=#{password}")
User select(@Param("username") String userName,@Param("password") String password);
//根据用户名查找对象
@Select("select * from tb_login where username=#{username}")
User selectByUserName(String username);
}
2.编写UserService.java
public class UserService {
//登录方法
public User login(String username,String password){
SqlSessionFactory sqlSessionFactory= SqlSessionFactoryUtils.getSqlSessionFactory();
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.select(username, password);
sqlSession.close();
return user;
}
}
3.编写login.jsp
<%@ 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="/BrandTest/loginServlet" method="post" id="form">
<h1 id="loginMsg">用户登录</h1>
<div id="errorMsg">${login_msg}${register_msg}</div>
<p>用 户 名:<input id="username" name="username" value="${cookie.username.value}" type="text"></p>
<p>密 码:<input id="password" name="password" value="${cookie.password.value}" type="password"></p>
<p>记住密码:<input id="remember" name="remember" value="1" type="checkbox"></p>
<div id="subDiv">
<input type="submit" class="button" value="登录">
<input type="reset" class="button" value="取消">
<a href="register.jsp">注册</a>
</div>
</form>
</div>
</body>
</html>
4.login.css
* {
margin: 0;
padding: 0;
}
html {
height: 100%;
width: 100%;
overflow: hidden;
margin: 0;
padding: 0;
background-color: rgba(48, 190, 216, 0.5);
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(48, 190, 216, 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;
}
5.编写loginServlet.java
package com.jkj.web;
import com.jkj.pojo.User;
import com.jkj.service.UserService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//接收参数
String username = req.getParameter("username");
String password = req.getParameter("password");
String remember = req.getParameter("remember");
//调用service
UserService service = new UserService();
//调用方法
User user = service.login(username, password);
//判断
if (user !=null){
//判断用户是否勾选了
if ("1".equals("remember")){
//创建cookie
Cookie u = new Cookie("username",username);
Cookie p = new Cookie("password", password);
//存活时间
u.setMaxAge(60);
p.setMaxAge(60);
//发送
resp.addCookie(u);
resp.addCookie(p);
}
//将user存储到session中
HttpSession session = req.getSession();
session.setAttribute("user",user);
String contextPath = req.getContextPath();
resp.sendRedirect(contextPath+"/selectAllServlet");
}else {
req.setAttribute("login_msg","用户名或密码错误!");
req.getRequestDispatcher("/login.jsp").forward(req,resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
6.编写brand.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body bgcolor="#00ced1">
<h1 align="center">欢迎!${user.username},登录成功!</h1>
<div align="center">
<input type="button" value="新增" id="add"><br>
</div>
<table border="1" bgcolor="#00ced1" cellpadding="0" width="800" align="center">
<tr>
<td>序号</td>
<td>品牌名称</td>
<td>企业名称</td>
<td>排序</td>
<td>品牌介绍</td>
<td>状态</td>
<td>操作</td>
</tr>
<c:forEach items="${brands}" var="brand" varStatus="status">
<tr align="center">
<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 ==1}">
<td>启用</td>
</c:if>
<c:if test="${brand.status !=1}">
<td>禁用</td>
</c:if>
<td><a href="/BrandTest/selectByIdServlet?id=${brand.id}">修改</a> <a href="/BrandTest/deleteByIdServlet?idd=${brand.id}">删除</a> </td>
</tr>
</c:forEach>
</table>
<script>
document.getElementById("add").onclick=function () {
location.href="/BrandTest/addBrand.jsp";
}
</script>
</body>
</html>
7.测试
登录数据库已有的用户名和密码:
用户名或密码错误的运行结果及提示错误信息:
登录成功,跳转到主页面,brand.jsp页面:
三、注册
1.用户注册和验证码
1.编写UserMapper
package com.jkj.mapper;
import com.jkj.pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
public interface UserMapper {
//根据用户名和密码查询用户对象
@Select("select * from tb_login where username=#{username} and password=#{password}")
User select(@Param("username") String userName,@Param("password") String password);
//根据用户名查找对象
@Select("select * from tb_login where username=#{username}")
User selectByUserName(String username);
//添加用户
@Insert("insert into tb_login values (null,#{username},#{password})")
void addUser(User user);
}
2.编写UserService.java
package com.jkj.service;
import com.jkj.mapper.UserMapper;
import com.jkj.pojo.User;
import com.jkj.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
public class UserService {
//登录方法
public User login(String username,String password){
SqlSessionFactory sqlSessionFactory= SqlSessionFactoryUtils.getSqlSessionFactory();
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.select(username, password);
sqlSession.close();
return user;
}
//注册方法
public boolean register(User user) {
SqlSessionFactory sqlSessionFactory= SqlSessionFactoryUtils.getSqlSessionFactory();
// 获取SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
// 获取UserMapper
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
// 调用方法
User u = mapper.selectByUserName(user.getUsername());
// 对用户是否存在判定
if (u == null) {
// 用户不存在进行注册操作
mapper.addUser(user);
sqlSession.commit();
}
// 关闭资源
sqlSession.close();
return u == null;
}
}
3.编写register.jsp
<%@ page import="java.util.Date" %>
<%@ 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="/BrandTest/registerServlet" method="get">
<table>
<tr>
<td>用 户 名</td>
<td class="inputs">
<input name="username" type="text" id="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">
<br>
<span id="password_err" class="err_msg"></span>
</td>
</tr>
<tr>
<td>验 证 码</td>
<td class="inputs">
<%--<input name="checkCode" type="text" id="checkCode">
<img src="/BrandTest/code">
<a href="#" id="changeImg" >看不清?</a>--%>
<input type="text" name="verifycode" class="form-control col-sm-6" id="verifycode" placeholder="Please Check" style="width: 120px;"/>
<a href="javascript:refreshCode()" onclick="refreshCode()" class="col-sm-4">
<img src="/BrandTest/checkCodeServlet" title="刷新" id="vcode"/>
</a>
</td>
</tr>
</table>
<div class="buttons">
<input value="注册" type="submit" id="reg_btn">
</div>
<br class="clear">
</form>
</div>
<script>
//切换验证码
function refreshCode() {
//1、获取验证码图片对象
var vcode = document.getElementById("vcode");
//2、设置其src属性,加时间戳
vcode.src="/BrandTest/checkCodeServlet?time="+new Date().getTime();
}
</script>
</body>
</html>
4.编写register.css
* {
margin: 0;
padding: 0;
list-style-type: none;
}
.reg-content{
padding: 30px;
margin: 3px;
}
a, img {
border: 0;
}
body {
background-color: rgba(48, 190, 216, 0.5);
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: center;
}
.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;
}
5.编写registerServlet.java
package com.jkj.web;
import com.jkj.pojo.User;
import com.jkj.service.UserService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@WebServlet("/registerServlet")
public class registerServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1. 获取用户名和密码数据
String username = req.getParameter("username");
String password = req.getParameter("password");
// 避免用户名存在中文导致乱码
username = new String(username.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
// 2. 封装成User对象
User user = new User();
user.setUsername(username);
user.setPassword(password);
// 3. 调用service中的注册方法
UserService service = new UserService();
boolean register = service.register(user);
String verifycode1 = req.getParameter("verifycode");//用户输入的验证码
String checkcode_server = (String) req.getSession().getAttribute("CHECKCODE_SERVER");//生成的验证码
if(verifycode1.equals("")||!checkcode_server.equalsIgnoreCase(verifycode1))//不输入verifycode为空字符串,不是null
{
req.setAttribute("register_msg", "验证码错误");
req.getRequestDispatcher("register.jsp").forward(req, resp);
return;
}
// 4. 判断是否注册成功
if (register) {
// 注册成功
req.setAttribute("register_msg", "新用户注册成功");
req.getRequestDispatcher("login.jsp").forward(req, resp);
} else {
// 注册失败
req.setAttribute("register_msg", "该用户名已存在");
req.getRequestDispatcher("register.jsp").forward(req, resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
6.运行测试
1.先注册一个数据库有的数据
2.注册个新用户,验证码要填写正确(首页就变成欢迎,cat了)
四、完成品牌数据的增删改查
2.查询所有
1.编写接口方法
操作数据比较简单建议使用注解的形式。
public interface BrandMapper {
//查询所有
@Select("select * from tb_brand")
@ResultMap("brandResultMap")
List<Brand> selectAll();
}
2.编写BrandMapper.xml
<?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">
<mapper namespace="com.jkj.mapper.BrandMapper">
<resultMap id="brandResultMap" type="brand">
<result column="brand_name" property="brandName"></result>
<result column="company_name" property="companyName"></result>
</resultMap>
</mapper>
3.编写service
新建BrandService.java
public class BrandService {
SqlSessionFactory sqlSessionFactory=SqlSessionFactoryUtils.getSqlSessionFactory();
//查询全部
public List<Brand> selectAll(){
//调用BrandMapper.selectAll()
//获取 SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//调用方法
List<Brand> brands = mapper.selectAll();
//释放资源
sqlSession.close();
return brands;
}
}
4.编写Servlet
创建selectAllServlet.java
package com.jkj.web;
import com.jkj.pojo.Brand;
import com.jkj.service.BrandService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet("/selectAllServlet")
public class selectAllServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//调用BrandService,完成查询
BrandService service = new BrandService();
List<Brand> brands = service.selectAll();
//存入request域中
req.setAttribute("brands",brands);
//转发到brand.jsp
req.getRequestDispatcher("/brand.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
5.编写brand.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body bgcolor="#00ced1">
<h1 align="center">欢迎!${user.username},登录成功!</h1>
<div align="center">
<input type="button" value="新增" id="add"><br>
</div>
<table border="1" bgcolor="#00ced1" cellpadding="0" width="800" align="center">
<tr>
<td>序号</td>
<td>品牌名称</td>
<td>企业名称</td>
<td>排序</td>
<td>品牌介绍</td>
<td>状态</td>
<td>操作</td>
</tr>
<c:forEach items="${brands}" var="brand" varStatus="status">
<tr align="center">
<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 ==1}">
<td>启用</td>
</c:if>
<c:if test="${brand.status !=1}">
<td>禁用</td>
</c:if>
<td><a href="#">修改</a> <a href="#">删除</a> </td>
</tr>
</c:forEach>
</table>
</script>
</body>
</html>
7.测试
3.添加
1.编写BrandMapper接口
public interface BrandMapper {
//查询所有
@Select("select * from tb_brand")
@ResultMap("brandResultMap")
List<Brand> selectAll();
//添加数据
@Insert("insert into tb_brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status})")
void add(Brand brand);
}
2.编写BrandService.java
public class BrandService {
SqlSessionFactory sqlSessionFactory=SqlSessionFactoryUtils.getSqlSessionFactory();
//查询全部
public List<Brand> selectAll(){
//调用BrandMapper.selectAll()
//获取 SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//调用方法
List<Brand> brands = mapper.selectAll();
//释放资源
sqlSession.close();
return brands;
}
//添加数据
public void add(Brand brand){
//获取 SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//调用方法
mapper.add(brand);
sqlSession.commit();
sqlSession.close();
}
}
3.编写brand.jsp
点击“新增”,转到addBrand.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body bgcolor="#00ced1">
<h1 align="center">欢迎!${user.username},登录成功!</h1>
<div align="center">
<input type="button" value="新增" id="add"><br>
</div>
<table border="1" bgcolor="#00ced1" cellpadding="0" width="800" align="center">
<tr>
<td>序号</td>
<td>品牌名称</td>
<td>企业名称</td>
<td>排序</td>
<td>品牌介绍</td>
<td>状态</td>
<td>操作</td>
</tr>
<c:forEach items="${brands}" var="brand" varStatus="status">
<tr align="center">
<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 ==1}">
<td>启用</td>
</c:if>
<c:if test="${brand.status !=1}">
<td>禁用</td>
</c:if>
<td><a href="#">修改</a> <a href="#">删除</a> </td>
</tr>
</c:forEach>
</table>
<script>
document.getElementById("add").onclick=function () {
location.href="/BrandTest/addBrand.jsp";
}
</script>
</body>
</html>
4.编写addBrand.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body bgcolor="#00ced1">
<div align="center">
<h3>添加品牌</h3>
<form action="/BrandTest/addServlet" method="post">
品牌名称:<input name="brandName"><br>
企业名称:<input name="companyName"><br>
排 序:<input name="ordered"><br>
描述信息:<textarea rows="5" cols="20" name="description"></textarea><br>
状 态:
<input type="radio" name="status" value="0">禁用
<input type="radio" name="status" value="1">启用<br>
<input type="submit" value="提交">
</form>
</div>
</body>
</html>
5.编写AddServlet
package com.jkj.web;
import com.jkj.pojo.Brand;
import com.jkj.service.BrandService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/addServlet")
public class addServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
BrandService service = new BrandService();
//post乱码
req.setCharacterEncoding("utf-8");
//接收参数
String brandName = req.getParameter("brandName");
String companyName = req.getParameter("companyName");
String ordered = req.getParameter("ordered");
String description = req.getParameter("description");
String status = req.getParameter("status");
//封装对象
Brand brand=new Brand();
brand.setBrandName(brandName);
brand.setCompanyName(companyName);
brand.setOrdered(Integer.parseInt(ordered));
brand.setDescription(description);
brand.setStatus(Integer.parseInt(status));
//调用service
service.add(brand);
//转发到查询所有数据
req.getRequestDispatcher("/selectAllServlet").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
6.测试运行
在brand.jsp页面中,点击“新增”跳转到addBrand.jsp页面,然后填写信息,点击提交
点击提交后又跳转到brand.jsp页面
4.修改-回显数据
在修改页面,显示当前的数据,你可以选择修改部分数据,或者全部修改。
1.编写BrandMapper.java
public interface BrandMapper {
//查询所有
@Select("select * from tb_brand")
@ResultMap("brandResultMap")
List<Brand> selectAll();
//添加数据
@Insert("insert into tb_brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status})")
void add(Brand brand);
//根据id查询数据
@Select("select * from tb_brand where id=#{id}")
@ResultMap("brandResultMap")
Brand selectById(int id);
}
2.编写BrandService.java
public class BrandService {
SqlSessionFactory sqlSessionFactory=SqlSessionFactoryUtils.getSqlSessionFactory();
//查询全部
public List<Brand> selectAll(){
//调用BrandMapper.selectAll()
//获取 SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//调用方法
List<Brand> brands = mapper.selectAll();
//释放资源
sqlSession.close();
return brands;
}
//添加数据
public void add(Brand brand){
//获取 SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//调用方法
mapper.add(brand);
sqlSession.commit();
sqlSession.close();
}
//通过id查找数据
public Brand selectById(int id){
//获取 SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//调用方法
Brand brand = mapper.selectById(id);
return brand;
}
}
3.编写brand.jsp
连接selectByIdServlet.java获取id
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body bgcolor="#00ced1">
<h1 align="center">欢迎!${user.username},登录成功!</h1>
<div align="center">
<input type="button" value="新增" id="add"><br>
</div>
<table border="1" bgcolor="#00ced1" cellpadding="0" width="800" align="center">
<tr>
<td>序号</td>
<td>品牌名称</td>
<td>企业名称</td>
<td>排序</td>
<td>品牌介绍</td>
<td>状态</td>
<td>操作</td>
</tr>
<c:forEach items="${brands}" var="brand" varStatus="status">
<tr align="center">
<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 ==1}">
<td>启用</td>
</c:if>
<c:if test="${brand.status !=1}">
<td>禁用</td>
</c:if>
<td><a href="/BrandTest/selectByIdServlet?id=${brand.id}">修改</a> <a href="#">删除</a> </td>
</tr>
</c:forEach>
</table>
<script>
document.getElementById("add").onclick=function () {
location.href="/BrandTest/addBrand.jsp";
}
</script>
</body>
</html>
4.编写SelectByIdServlet.java
package com.jkj.web;
import com.jkj.pojo.Brand;
import com.jkj.service.BrandService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/deleteByIdServlet")
public class deleteByIdServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//接收参数
String id = req.getParameter("idd");
//调用BrandService,完成查询
BrandService service = new BrandService();
service.deleteById(Integer.parseInt(id));
//转发到update.jsp
req.getRequestDispatcher("/selectAllServlet").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
5.编写update.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body bgcolor="#00ced1">
<div align="center">
<h3>修改品牌</h3>
<form action="/BrandTest/updateServlet" method="post">
<!--
隐藏域:获取id
-->
<input type="hidden" name="id" value="${brand.id}">
品牌名称:<input name="brandName" value="${brand.brandName}"><br>
企业名称:<input name="companyName" value="${brand.companyName}"><br>
排 序:<input name="ordered" value="${brand.ordered}"><br>
描述信息:<textarea rows="5" cols="20" 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>
</div>
</body>
</html>
6.运行测试
5.修改数据
1.编写BrandMapper.java
public interface BrandMapper {
//查询所有
@Select("select * from tb_brand")
@ResultMap("brandResultMap")
List<Brand> selectAll();
//添加数据
@Insert("insert into tb_brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status})")
void add(Brand brand);
//根据id查询数据
@Select("select * from tb_brand where id=#{id}")
@ResultMap("brandResultMap")
Brand selectById(int id);
//修改数据
@Update("update tb_brand set brand_name=#{brandName},company_name=#{companyName},ordered=#{ordered},description=#{description},status=#{status} where id=#{id} ")
@ResultMap("brandResultMap")
void update(Brand brand);
}
2.编写BrandService
public class BrandService {
SqlSessionFactory sqlSessionFactory=SqlSessionFactoryUtils.getSqlSessionFactory();
//查询全部
public List<Brand> selectAll(){
//调用BrandMapper.selectAll()
//获取 SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//调用方法
List<Brand> brands = mapper.selectAll();
//释放资源
sqlSession.close();
return brands;
}
//添加数据
public void add(Brand brand){
//获取 SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//调用方法
mapper.add(brand);
sqlSession.commit();
sqlSession.close();
}
//通过id查找数据
public Brand selectById(int id){
//获取 SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//调用方法
Brand brand = mapper.selectById(id);
return brand;
}
//修改数据
public void update(Brand brand){
//获取 SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//调用方法
mapper.update(brand);
sqlSession.commit();
sqlSession.close();
}
}
3.修改update.jsp
修改update.jsp数据传输到servlet,注意要传入id到servlet,注意id不要显示在update.jsp页面中(隐藏域),type = hidden
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body bgcolor="#00ced1">
<div align="center">
<h3>修改品牌</h3>
<form action="/BrandTest/updateServlet" method="post">
<!--
隐藏域:获取id
-->
<input type="hidden" name="id" value="${brand.id}">
品牌名称:<input name="brandName" value="${brand.brandName}"><br>
企业名称:<input name="companyName" value="${brand.companyName}"><br>
排 序:<input name="ordered" value="${brand.ordered}"><br>
描述信息:<textarea rows="5" cols="20" 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>
</div>
</body>
</html>
4.编写updateServlet.java
package com.jkj.web;
import com.jkj.pojo.Brand;
import com.jkj.service.BrandService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/updateServlet")
public class updateServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
BrandService service = new BrandService();
//post乱码
req.setCharacterEncoding("utf-8");
//接收参数
String id = req.getParameter("id");
String brandName = req.getParameter("brandName");
String companyName = req.getParameter("companyName");
String ordered = req.getParameter("ordered");
String description = req.getParameter("description");
String status = req.getParameter("status");
//封装对象
Brand brand=new Brand();
brand.setId(Integer.parseInt(id));
brand.setBrandName(brandName);
brand.setCompanyName(companyName);
brand.setOrdered(Integer.parseInt(ordered));
brand.setDescription(description);
brand.setStatus(Integer.parseInt(status));
//调用service
service.update(brand);
//转发到查询所有数据
req.getRequestDispatcher("/selectAllServlet").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
5.测试运行
在update.jsp页面点击提交,跳转到brand.jsp页面,显示修改的内容。
6.删除
1.编写BrandMapper.java
package com.jkj.mapper;
import com.jkj.pojo.Brand;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface BrandMapper {
//查询所有
@Select("select * from tb_brand")
@ResultMap("brandResultMap")
List<Brand> selectAll();
//添加数据
@Insert("insert into tb_brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status})")
void add(Brand brand);
//根据id查询数据
@Select("select * from tb_brand where id=#{id}")
@ResultMap("brandResultMap")
Brand selectById(int id);
//修改数据
@Update("update tb_brand set brand_name=#{brandName},company_name=#{companyName},ordered=#{ordered},description=#{description},status=#{status} where id=#{id} ")
@ResultMap("brandResultMap")
void update(Brand brand);
//删除数据
@Delete("delete from tb_brand where id=#{id}")
void deleteById(int id);
}
2.编写BrandService.java
package com.jkj.service;
import com.jkj.mapper.BrandMapper;
import com.jkj.pojo.Brand;
import com.jkj.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import java.util.List;
public class BrandService {
SqlSessionFactory sqlSessionFactory=SqlSessionFactoryUtils.getSqlSessionFactory();
//查询全部
public List<Brand> selectAll(){
//调用BrandMapper.selectAll()
//获取 SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//调用方法
List<Brand> brands = mapper.selectAll();
//释放资源
sqlSession.close();
return brands;
}
//添加数据
public void add(Brand brand){
//获取 SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//调用方法
mapper.add(brand);
sqlSession.commit();
sqlSession.close();
}
//通过id查找数据
public Brand selectById(int id){
//获取 SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//调用方法
Brand brand = mapper.selectById(id);
return brand;
}
//修改数据
public void update(Brand brand){
//获取 SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//调用方法
mapper.update(brand);
sqlSession.commit();
sqlSession.close();
}
//删除数据
public void deleteById(int id){
//获取 SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
//获取BrandMapper
BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//调用方法
mapper.deleteById(id);
sqlSession.commit();
sqlSession.close();
}
}
3.编写deleteByIdServlet
package com.jkj.web;
import com.jkj.pojo.Brand;
import com.jkj.service.BrandService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/deleteByIdServlet")
public class deleteByIdServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//接收参数
String id = req.getParameter("idd");
//调用BrandService,完成查询
BrandService service = new BrandService();
service.deleteById(Integer.parseInt(id));
//转发到update.jsp
req.getRequestDispatcher("/selectAllServlet").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
4编写brand.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body bgcolor="#00ced1">
<h1 align="center">欢迎!${user.username},登录成功!</h1>
<div align="center">
<input type="button" value="新增" id="add"><br>
</div>
<table border="1" bgcolor="#00ced1" cellpadding="0" width="800" align="center">
<tr>
<td>序号</td>
<td>品牌名称</td>
<td>企业名称</td>
<td>排序</td>
<td>品牌介绍</td>
<td>状态</td>
<td>操作</td>
</tr>
<c:forEach items="${brands}" var="brand" varStatus="status">
<tr align="center">
<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 ==1}">
<td>启用</td>
</c:if>
<c:if test="${brand.status !=1}">
<td>禁用</td>
</c:if>
<td><a href="/BrandTest/selectByIdServlet?id=${brand.id}">修改</a> <a href="/BrandTest/deleteByIdServlet?idd=${brand.id}">删除</a> </td>
</tr>
</c:forEach>
</table>
<script>
document.getElementById("add").onclick=function () {
location.href="/BrandTest/addBrand.jsp";
}
</script>
</body>
</html>
5.运行测试
点击删除按钮,跳转到brand.jsp,数据已删除。
)