JavaWeb小项目练习(基于三层架构实现登录,对表增,删,改,查的操作)

news2024/11/24 8:04:46

 一 创建项目并修改项目结构

File->New->Project新建一个名为javaweb01的工程

1

2

javaweb01->New->Module新建一个名为MyManage的模块

1

2

将MyManage模块设置为支持web项目

1

2

将web项目重命名并移动到main路径下

配置pom文件(文件依赖,打包方式,以及支持加载的文件)

<?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>
    <parent>
        <groupId>com.by</groupId>
        <artifactId>javaweb</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <artifactId>MyManage</artifactId>
<!--    项目打包方式-->
    <packaging>war</packaging>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
<!--        依赖Servlet-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>

<!--        依赖Mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
<!--        依赖mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
<!--        依赖log4j-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
<!--        依赖jsp-api-->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
        </dependency>
<!--       依赖jstl-->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>
    <build>
        <!-- 如果不添加此节点src/main/java目录下的所有配置文件都会被漏掉。 -->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <!--让idea识别resources目录-->
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
    </build>

</project>

二 使用三层架构和配置文件以及Tomcat服务器

创建三层架构的包(表现层)servlet,(业务逻辑层)service serviceimpl,(数据访问层)mapper

加载配置文件(数据库配置文件,日志文件,MyBatis配置文件)

数据库配置文件db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3305/servlet?characterEncoding=UTF-8
jdbc.username=root
jdbc.password=

日志文件log4j.properties

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

MyBatis配置文件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>
    <properties resource="db.properties"></properties>
    <typeAliases>
        <package name="com.by.pojo"/>
    </typeAliases>
    <!-- 数据库连接信息 -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 扫描映射文件 -->
    <mappers>
<!--        <mapper resource="com/by/dao/UserDao.xml"/>-->
        <package name="com.by.mapper"/>
    </mappers>
</configuration>

项目结构

Tomcat服务器

1

2

3

4

5

6

7

8

9

三 监听和过滤

监听器

SqlSession回话实例从始至终都使用,所以在将SqlSession装在ServletContext里边

新建com->by->listener->MyServletContxtListenerlei

public class MyServletContxtListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        try {
            //加载配置文件
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);

            //创建SessionFactory
            SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

            //使用数据的会话实例
            SqlSession sqlSession = sessionFactory.openSession();
            //把sqlSession对象撞到servletContext中
            ServletContext servletContext = servletContextEvent.getServletContext();
            servletContext.setAttribute("sqlSession", sqlSession);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}

web.xml

<!--配置监听器-->
    <listener>
        <listener-class>com.by.listener.MyServletContxtListener</listener-class>
    </listener>

过滤器

因为文件请求和响应需要防止字符编码格式不一样而导致乱码,所以我们采用过滤器技术过滤每一个servlet文件

新建com->by->filter->CharacterEncodingFilter

public class CharacterEncodingFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //请求中文乱码
        servletRequest.setCharacterEncoding("utf-8");
        //响应中文乱码
        servletResponse.setContentType("text/html;charset=utf-8");
        //放行filter
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}

pojo包下新建User类

package com.by.pojo;

public class User {
    private Integer id;
    private String username;
    private String password;
    private String sex;
    private String address;
    private Integer age;

    public User(Integer id, String username, String password, String sex, Integer age, String address) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.sex = sex;
        this.address = address;
        this.age = age;
    }

    public User(String username, String password, String sex, Integer age, String address) {
        this.username = username;
        this.password = password;
        this.sex = sex;
        this.address = address;
        this.age = age;
    }

    public User() {
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    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;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

web.xml

<!--    过滤器-->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>com.by.filter.CharacterEncodingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <!--*代表任意请求-->
        <url-pattern>/*</url-pattern>
    </filter-mapping>

三 登录验证并查询数据表内容

login.jsp

<%--
  Created by IntelliJ IDEA.
  User: 21309
  Date: 2023-12-27
  Time: 16:05
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <h1>用户管理系统</h1>
  <form action="login" method="post">
    账号:<input type="text" name="username"><br>
    密码:<input type="text" name="password"><br>
    <input type="submit" value="登录">
  </form>
  </body>
</html>

web.xml

<!--设置欢迎页为Login.jsp-->
    <welcome-file-list>
        <welcome-file>login.jsp</welcome-file>
    </welcome-file-list>

在servlet包下新建LoginServlet

//表现层
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //根据input标签的name属性获取前端提交的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //调用service
        UserService userService = new UserServiceImpl(this);
        //将获得的username,password传递给User
        User user=userService.login(username,password);
        //登录判断
        if (user!=null){
        //如果登录成功,则跳转到select_user.jsp
        resp.sendRedirect("selectUserServlet");
        }else {
        //如果登录失败,则跳转到login.jsp
        req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    }
}

web.xml

<!--login页-->
    <servlet>
        <servlet-name>login</servlet-name>
        <servlet-class>com.by.servlet.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>login</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>

以下内容可在servlet类中Alt+Enter快捷键出来(先把Servlet类写完整)

在service包下的UserService接口

public interface UserService {
    User login(String username, String password);
}

UserServiceImpl类

public class UserServiceImpl implements UserService {
    private SqlSession sqlSession;
    private UserMapper userMapper;
    //加载UserMapper类
    public UserServiceImpl(HttpServlet httpServlet) {
        ServletContext servletContext = httpServlet.getServletContext();
        sqlSession = (SqlSession) servletContext.getAttribute("sqlSession");
        userMapper = sqlSession.getMapper(UserMapper.class);
    }
@Override
    public User login(String username, String password) {
        //调用dao
        return userMapper.login(username,password);
    }
}

mapper包下的UserMapper接口

public interface UserMapper {
     User login(@Param("username") String username, @Param("password") String password);
}

mapper包下的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.by.mapper.UserMapper">
    <select id="login" resultType="com.by.pojo.User">
        SELECT * FROM user WHERE username=#{username} AND password=#{password}
    </select>
    <select id="selectUser" resultType="com.by.pojo.User">
        SELECT * FROM user
    </select>
</mapper>

登陆页面要要跳到select_user.jsp页面

在servlet包下新建SelectUserServlet

public class SelectUserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //调用UserService查询List<User>
        UserService userService = new UserServiceImpl(this);
        List<User> userList = userService.selectUser();

        //把List<User>送到select_user.jsp
        req.setAttribute("userList", userList);
        req.getRequestDispatcher("select_user.jsp").forward(req, resp);
    }
}

web.xml

<!--    selectUserServlet-->
    <servlet>
        <servlet-name>selectUserServlet</servlet-name>
        <servlet-class>com.by.servlet.SelectUserServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>selectUserServlet</servlet-name>
        <url-pattern>/selectUserServlet</url-pattern>
    </servlet-mapping>

以下内容可在servlet类中Alt+Enter快捷键出来(先把Servlet类写完整)

在service包下的UserService接口

public interface UserService {

    User login(String username, String password);

    List<User> selectUser();
}

UserServiceImpl类

public class UserServiceImpl implements UserService {
    private SqlSession sqlSession;
    private UserMapper userMapper;
    //加载UserMapper类
    public UserServiceImpl(HttpServlet httpServlet) {
        ServletContext servletContext = httpServlet.getServletContext();
        sqlSession = (SqlSession) servletContext.getAttribute("sqlSession");
        userMapper = sqlSession.getMapper(UserMapper.class);
    }

    @Override
    public User login(String username, String password) {
        //调用dao
        return userMapper.login(username,password);
    }

    @Override
    public List<User> selectUser() {
        return userMapper.selectUser();
    }
}

mapper包下的UserMapper接口

public interface UserMapper {
    User login(@Param("username") String username, @Param("password") String password);

    List<User> selectUser();
}

mapper包下的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.by.mapper.UserMapper">
    <select id="login" resultType="com.by.pojo.User">
        SELECT * FROM user WHERE username=#{username} AND password=#{password}
    </select>
    <select id="selectUser" resultType="com.by.pojo.User">
        SELECT * FROM user
    </select>
</mapper>

测试结果

1

2

四 新增数据

在select_user.jsp添加新增链接

新建add_user.jsp

<%--
  Created by IntelliJ IDEA.
  User: Hero
  Date: 2023/12/29
  Time: 11:01
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>新增</h1>
<form action="addUser" method="post">
    账号:<input type="text" name="username"><br>
    密码:<input type="text" name="password"><br>
    性别:<input type="text" name="sex"><br>
    年龄:<input type="text" name="age"><br>
    地址:<input type="text" name="address"><br>
    <input type="submit" value=" 新  增 ">
</form>
</body>
</html>

在servlet包下新建addUser

public class addUser extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、接收参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String sex = req.getParameter("sex");
        Integer age = Integer.valueOf(req.getParameter("age"));
        String address = req.getParameter("address");
        User user = new User(username, password, sex, age, address);

        //2、调用service,把user保存到数据库
        UserService userService = new UserServiceImpl(this);
        userService.addUser(user);

        //3、重定向到SelectUserServlet
        resp.sendRedirect("selectUserServlet");
    }
}

web.xml

<!--    addUser-->
    <servlet>
        <servlet-name>addUser</servlet-name>
        <servlet-class>com.by.servlet.addUser</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>addUser</servlet-name>
        <url-pattern>/addUser</url-pattern>
    </servlet-mapping>

以下内容可在servlet类中Alt+Enter快捷键出来(先把Servlet类写完整)

在service包下的UserService接口

public interface UserService {

    User login(String username, String password);

    List<User> selectUser();

    void addUser(User user);
}

UserServiceImpl类

public class UserServiceImpl implements UserService {
    private SqlSession sqlSession;
    private UserMapper userMapper;
    //加载UserMapper类
    public UserServiceImpl(HttpServlet httpServlet) {
        ServletContext servletContext = httpServlet.getServletContext();
        sqlSession = (SqlSession) servletContext.getAttribute("sqlSession");
        userMapper = sqlSession.getMapper(UserMapper.class);
    }

    @Override
    public User login(String username, String password) {
        //调用dao
        return userMapper.login(username,password);
    }

    @Override
    public List<User> selectUser() {
        return userMapper.selectUser();
    }

    @Override
    public void addUser(User user) {
        userMapper.addUser(user);
        sqlSession.commit();
    }
}

mapper包下的UserMapper接口

public interface UserMapper {
    User login(@Param("username") String username, @Param("password") String password);

    List<User> selectUser();

    void addUser(User user);
}

mapper包下的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.by.mapper.UserMapper">
    <select id="login" resultType="com.by.pojo.User">
        SELECT * FROM user WHERE username=#{username} AND password=#{password}
    </select>
    <select id="selectUser" resultType="com.by.pojo.User">
        SELECT * FROM user
    </select>
<!--   insert-->
    <insert id="addUser" parameterType="com.by.pojo.User">
        INSERT INTO user
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="username!=null and username!=''">
                username,
            </if>
            <if test="password!=null and password!=''">
                password,
            </if>
            <if test="sex!=null and sex!=''">
                sex,
            </if>
            <if test="age!=null">
                age,
            </if>
            <if test="address!=null and address!=''">
                address,
            </if>
        </trim>
        VALUES
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="username!=null and username!=''">
                #{username},
            </if>
            <if test="password!=null and password!=''">
                #{password},
            </if>
            <if test="sex!=null and sex!=''">
                #{sex},
            </if>
            <if test="age!=null">
                #{age},
            </if>
            <if test="address!=null and address!=''">
                #{address},
            </if>
        </trim>
    </insert>
</mapper>

测试结果

1

2

五 删除数据

在select_user.jsp添加删除链接

在servlet包下新建DeleteUserServlet

public class UpdateUserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、接收参数
        Integer id = Integer.valueOf(req.getParameter("id"));
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String sex = req.getParameter("sex");
        Integer age = Integer.valueOf(req.getParameter("age"));
        String address = req.getParameter("address");
        User user = new User(id, username, password, sex, age, address);

        //2、调用service,修改user
        UserService userService = new UserServiceImpl(this);
        userService.updateUserById(user);

        //3、重定向到SelectUserServlet
        resp.sendRedirect("selectUserServlet");
    }
}

web.xml

 <!--    delete-->
    <servlet>
        <servlet-name>deleteUser</servlet-name>
        <servlet-class>com.by.servlet.DeleteUserServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>deleteUser</servlet-name>
        <url-pattern>/deleteUser</url-pattern>
    </servlet-mapping>

以下内容可在servlet类中Alt+Enter快捷键出来(先把Servlet类写完整)

在service包下的UserService接口

public interface UserService {

    User login(String username, String password);

    List<User> selectUser();

    void addUser(User user);

    void deleteUser(Integer id);
}

UserServiceImpl类

public class UserServiceImpl implements UserService {
    private SqlSession sqlSession;
    private UserMapper userMapper;
    //加载UserMapper类
    public UserServiceImpl(HttpServlet httpServlet) {
        ServletContext servletContext = httpServlet.getServletContext();
        sqlSession = (SqlSession) servletContext.getAttribute("sqlSession");
        userMapper = sqlSession.getMapper(UserMapper.class);
    }

    @Override
    public User login(String username, String password) {
        //调用dao
        return userMapper.login(username,password);
    }

    @Override
    public List<User> selectUser() {
        return userMapper.selectUser();
    }

    @Override
    public void addUser(User user) {
        userMapper.addUser(user);
        sqlSession.commit();
    }

    @Override
    public void deleteUser(Integer id) {
        userMapper.deleteUser(id);
        sqlSession.commit();
    }
}

mapper包下的UserMapper接口

public interface UserMapper {
    User login(@Param("username") String username, @Param("password") String password);

    List<User> selectUser();

    void addUser(User user);

    void deleteUser(Integer id);
}

mapper包下的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.by.mapper.UserMapper">
    <select id="login" resultType="com.by.pojo.User">
        SELECT * FROM user WHERE username=#{username} AND password=#{password}
    </select>
    <select id="selectUser" resultType="com.by.pojo.User">
        SELECT * FROM user
    </select>
<!--   insert-->
    <insert id="addUser" parameterType="com.by.pojo.User">
        INSERT INTO user
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="username!=null and username!=''">
                username,
            </if>
            <if test="password!=null and password!=''">
                password,
            </if>
            <if test="sex!=null and sex!=''">
                sex,
            </if>
            <if test="age!=null">
                age,
            </if>
            <if test="address!=null and address!=''">
                address,
            </if>
        </trim>
        VALUES
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="username!=null and username!=''">
                #{username},
            </if>
            <if test="password!=null and password!=''">
                #{password},
            </if>
            <if test="sex!=null and sex!=''">
                #{sex},
            </if>
            <if test="age!=null">
                #{age},
            </if>
            <if test="address!=null and address!=''">
                #{address},
            </if>
        </trim>
    </insert>
<!--    delete-->
    <delete id="deleteUser" parameterType="int">
        DELETE FROM user WHERE id=#{id}
    </delete>
</mapper>

测试结果

六 更新数据

在select_user.jsp增加修改链接

修改数据首先要获取被修改的数据

获取被修改的数据

在servlet包下新建GetUserServlet

public class GetUserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、接收参数
        Integer id = Integer.valueOf(req.getParameter("id"));
        //2、调用service,根据id查询user
        UserService userService = new UserServiceImpl(this);
        User user = userService.getUserById(id);

        //3、user送到update_user.jsp
        req.setAttribute("user", user);
        req.getRequestDispatcher("update_user.jsp").forward(req, resp);
    }
}

web.xml

 <!--    GetUserServlet-->
    <servlet>
        <servlet-name>getUserServlet</servlet-name>
        <servlet-class>com.by.servlet.GetUserServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>getUserServlet</servlet-name>
        <url-pattern>/getUserById</url-pattern>
    </servlet-mapping>

以下内容可在servlet类中Alt+Enter快捷键出来(先把Servlet类写完整)

在service包下的UserService接口

public interface UserService {

    User login(String username, String password);

    List<User> selectUser();

    void addUser(User user);

    void deleteUser(Integer id);

    User getUserById(Integer id);
}

UserServiceImpl类

public class UserServiceImpl implements UserService {
    private SqlSession sqlSession;
    private UserMapper userMapper;
    //加载UserMapper类
    public UserServiceImpl(HttpServlet httpServlet) {
        ServletContext servletContext = httpServlet.getServletContext();
        sqlSession = (SqlSession) servletContext.getAttribute("sqlSession");
        userMapper = sqlSession.getMapper(UserMapper.class);
    }

    @Override
    public User login(String username, String password) {
        //调用dao
        return userMapper.login(username,password);
    }

    @Override
    public List<User> selectUser() {
        return userMapper.selectUser();
    }

    @Override
    public void addUser(User user) {
        userMapper.addUser(user);
        sqlSession.commit();
    }

    @Override
    public void deleteUser(Integer id) {
        userMapper.deleteUser(id);
        sqlSession.commit();
    }

    @Override
    public User getUserById(Integer id) {
        return userMapper.getUserById(id);
    }
}

mapper包下的UserMapper接口

public interface UserMapper {
    User login(@Param("username") String username, @Param("password") String password);

    List<User> selectUser();

    void addUser(User user);

    void deleteUser(Integer id);

    User getUserById(Integer id);
}

mapper包下的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.by.mapper.UserMapper">
    <select id="login" resultType="com.by.pojo.User">
        SELECT * FROM user WHERE username=#{username} AND password=#{password}
    </select>
    <select id="selectUser" resultType="com.by.pojo.User">
        SELECT * FROM user
    </select>
<!--   insert-->
    <insert id="addUser" parameterType="com.by.pojo.User">
        INSERT INTO user
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="username!=null and username!=''">
                username,
            </if>
            <if test="password!=null and password!=''">
                password,
            </if>
            <if test="sex!=null and sex!=''">
                sex,
            </if>
            <if test="age!=null">
                age,
            </if>
            <if test="address!=null and address!=''">
                address,
            </if>
        </trim>
        VALUES
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="username!=null and username!=''">
                #{username},
            </if>
            <if test="password!=null and password!=''">
                #{password},
            </if>
            <if test="sex!=null and sex!=''">
                #{sex},
            </if>
            <if test="age!=null">
                #{age},
            </if>
            <if test="address!=null and address!=''">
                #{address},
            </if>
        </trim>
    </insert>
<!--    delete-->
    <delete id="deleteUser" parameterType="int">
        DELETE FROM user WHERE id=#{id}
    </delete>
<!--getdata-->
    <select id="getUserById" parameterType="int" resultType="com.by.pojo.User">
        SELECT * FROM user WHERE id=#{id}
    </select>
</mapper>

测试结果

修改数据

在servlet包下新建UpdateUserServlet

public class UpdateUserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、接收参数
        Integer id = Integer.valueOf(req.getParameter("id"));
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String sex = req.getParameter("sex");
        Integer age = Integer.valueOf(req.getParameter("age"));
        String address = req.getParameter("address");
        User user = new User(id, username, password, sex, age, address);

        //2、调用service,修改user
        UserService userService = new UserServiceImpl(this);
        userService.updateUserById(user);

        //3、重定向到SelectUserServlet
        resp.sendRedirect("selectUserServlet");
    }
}

web.xml

<!--    UpdateUserServlet-->
    <servlet>
        <servlet-name>updateUserById</servlet-name>
        <servlet-class>com.by.servlet.UpdateUserServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>updateUserById</servlet-name>
        <url-pattern>/updateUserById</url-pattern>
    </servlet-mapping>

以下内容可在servlet类中Alt+Enter快捷键出来(先把Servlet类写完整)

在service包下的UserService接口

public interface UserService {

    User login(String username, String password);

    List<User> selectUser();

    void addUser(User user);

    void deleteUser(Integer id);

    User getUserById(Integer id);

    void updateUserById(User user);
}

UserServiceImpl类

public class UserServiceImpl implements UserService {
    private SqlSession sqlSession;
    private UserMapper userMapper;
    //加载UserMapper类
    public UserServiceImpl(HttpServlet httpServlet) {
        ServletContext servletContext = httpServlet.getServletContext();
        sqlSession = (SqlSession) servletContext.getAttribute("sqlSession");
        userMapper = sqlSession.getMapper(UserMapper.class);
    }

    @Override
    public User login(String username, String password) {
        //调用dao
        return userMapper.login(username,password);
    }

    @Override
    public List<User> selectUser() {
        return userMapper.selectUser();
    }

    @Override
    public void addUser(User user) {
        userMapper.addUser(user);
        sqlSession.commit();
    }

    @Override
    public void deleteUser(Integer id) {
        userMapper.deleteUser(id);
        sqlSession.commit();
    }

    @Override
    public User getUserById(Integer id) {
        return userMapper.getUserById(id);
    }

    @Override
    public void updateUserById(User user) {
        userMapper.updateUserById(user);
        sqlSession.commit();
    }
}

mapper包下的UserMapper接口

public interface UserMapper {
    User login(@Param("username") String username, @Param("password") String password);

    List<User> selectUser();

    void addUser(User user);

    void deleteUser(Integer id);

    User getUserById(Integer id);

    void updateUserById(User user);
}

mapper包下的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.by.mapper.UserMapper">
    <select id="login" resultType="com.by.pojo.User">
        SELECT * FROM user WHERE username=#{username} AND password=#{password}
    </select>
    <select id="selectUser" resultType="com.by.pojo.User">
        SELECT * FROM user
    </select>
<!--   insert-->
    <insert id="addUser" parameterType="com.by.pojo.User">
        INSERT INTO user
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="username!=null and username!=''">
                username,
            </if>
            <if test="password!=null and password!=''">
                password,
            </if>
            <if test="sex!=null and sex!=''">
                sex,
            </if>
            <if test="age!=null">
                age,
            </if>
            <if test="address!=null and address!=''">
                address,
            </if>
        </trim>
        VALUES
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="username!=null and username!=''">
                #{username},
            </if>
            <if test="password!=null and password!=''">
                #{password},
            </if>
            <if test="sex!=null and sex!=''">
                #{sex},
            </if>
            <if test="age!=null">
                #{age},
            </if>
            <if test="address!=null and address!=''">
                #{address},
            </if>
        </trim>
    </insert>
<!--    delete-->
    <delete id="deleteUser" parameterType="int">
        DELETE FROM user WHERE id=#{id}
    </delete>
<!--getdata-->
    <select id="getUserById" parameterType="int" resultType="com.by.pojo.User">
        SELECT * FROM user WHERE id=#{id}
    </select>
<!--    updata-->
    <update id="updateUserById" parameterType="com.by.pojo.User">
        UPDATE user
        <set>
            <if test="username!=null and username!=''">
                username=#{username},
            </if>
            <if test="password!=null and password!=''">
                password=#{password},
            </if>
            <if test="sex!=null and sex!=''">
                sex=#{sex},
            </if>
            <if test="age!=null">
                age=#{age},
            </if>
            <if test="address!=null and address!=''">
                address=#{address},
            </if>
        </set>
        WHERE id=#{id}
    </update>
</mapper>

测试结果

1

2

七 最终项目结构

1

2

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1350534.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

24年上半年想考软考,小白如何备考?

软考科目的考试时间&#xff1a; 软考考试时间&#xff1a; 软考高级有三科&#xff08;机考&#xff09;&#xff1a;《综合知识》、《案例分析》、《论文》 软考中级、初级&#xff08;机考&#xff09;&#xff1a; 《基础知识》、《应用技术》 考试报名官网&#xff1a;中…

SpringBoot集成 Websocket 实现服务与客户端进行消息发送和接收

介绍 WebSocket是一种在单个TCP连接上进行全双工通信的协议。WebSocket使得客户端和服务器之间的数据交换变得更加简单&#xff0c;允许服务端主动向客户端推送数据。 效果 客户端效果 服务端日志 pom依赖 <!-- websocket --> <dependency><groupId>org.…

【Matlab】LSTM长短期记忆神经网络时序预测算法(附代码)

资源下载&#xff1a; https://download.csdn.net/download/vvoennvv/88688439 一&#xff0c;概述 LSTM&#xff08;Long Short-Term Memory&#xff09;是一种常用的循环神经网络&#xff08;Recurrent Neural Network&#xff0c;RNN&#xff09;结构&#xff0c;由于其对于…

1207. 大臣的旅费(dfs求树的直径/图论)

题目&#xff1a; 1207. 大臣的旅费 - AcWing题库 思路&#xff1a; dfs求树的直径。 代码&#xff1a; #include<iostream> #include<cstdio> #include<vector> using namespace std; const int N100100; struct Edge//边的id以及长度 {int id,w; };ve…

Mysql 下载与安装教程(详细介绍与总结)

一&#xff1a;版本介绍 首先&#xff0c;我们需要先进入官网进行下载&#xff0c;在官网中有好几个版本&#xff0c;那么这里我分别简述一下MySQL各个版本区别&#xff1a; 1&#xff1a;企业版&#xff0c;MySQL Enterprise Edition 需要付费的&#xff0c;可以免费试用30天…

redis的搭建及应用(五)-布隆过滤器插件

redis布隆过滤器 可以把布隆过滤器理解为bitmap结构&#xff0c;判断某个对象是否存在时&#xff0c;它可能会误判。但是布隆过滤器也不是特别不精确&#xff0c;只要参数设置得合理&#xff0c;它的精确度也可以控制得相对足够精确&#xff0c;只会有小小的误判概率。 总得来说…

从 0 到 1 实现 ReentrantLock

虽然本文的标题是从 0 到 1 实现 ReentrantLock &#xff0c;但是为了方便理解&#xff0c;我们先从一个问题出发&#xff1a;既然系统已经有 synchronized 关键字了&#xff0c;那么为什么还会出现 ReentrantLock 这种代码层面的锁? 这就要先回顾一下历史了&#xff1a;在 J…

微服务整合:构建高效灵活的分布式系统

随着软件开发的不断演进和业务的复杂性增加&#xff0c;微服务架构已经成为一种流行的解决方案。然而&#xff0c;当涉及到多个微服务之间的整合时&#xff0c;我们需要谨慎考虑如何实现高效、灵活的分布式系统。 微服务架构的流行使得软件开发变得更加灵活和可扩展。然而&…

layuiadmin新建tabs标签页,点击保存,打开新的标签页并刷新

用的layuiamin前端框架 需求&#xff1a;新增的页面为一个标签页&#xff0c;保存后&#xff0c;需要刷新列表 1、新建customMethod.js文件&#xff0c;自定义自己的方法 layui.define(function (exports) {var $ layui.$var customMethod {// 表单点击保存后&#xff0c;…

【ROS2】MOMO的鱼香ROS2(四)ROS2入门篇——ROS2节点通信之话题与服务

ROS2节点通信之话题与服务点 引言1 理解从通信开始1.1 TCP&#xff08;传输控制协议&#xff09;1.2 UDP&#xff08;用户数据报协议&#xff09;1.3 基于共享内存的IPC方式 2 ROS2话题2.1 ROS2话题指令2.2 话题之RCLPY实现2.2.1 编写发布者2.2 2 编写订阅者2.2.3 运行测试 3 R…

【Unity美术】Unity工程师对3D模型需要达到的了解【二】

&#x1f468;‍&#x1f4bb;个人主页&#xff1a;元宇宙-秩沅 &#x1f468;‍&#x1f4bb; hallo 欢迎 点赞&#x1f44d; 收藏⭐ 留言&#x1f4dd; 加关注✅! &#x1f468;‍&#x1f4bb; 本文由 秩沅 原创 &#x1f468;‍&#x1f4bb; 收录于专栏&#xff1a;Uni…

基于ThinkPHP的云盘系统Cloudreve本地搭建并实现远程访问

文章目录 1、前言2、本地网站搭建2.1 环境使用2.2 支持组件选择2.3 网页安装2.4 测试和使用2.5 问题解决 3、本地网页发布3.1 cpolar云端设置3.2 cpolar本地设置 4、公网访问测试5、结语 1、前言 自云存储概念兴起已经有段时间了&#xff0c;各互联网大厂也纷纷加入战局&#…

扫码看图时,多图如何用轮播排列展示?

在扫描二维码看图时&#xff0c;一般图片大多会通过上下排列的方式来展示&#xff0c;如果图片的数量太多&#xff0c;就需要在手机上不断地下滑才能看到所有内容&#xff0c;这种方式会导致在查看图片时感觉疲劳或者眼花的情况。那么想要解决这个问题&#xff0c;我们可以在生…

flutter接入扫码枪的扫描结果,其实就是监听键盘输入,从测试到页面显示出来

检测设备是否正常 首先一定要测试一下你的硬件设备是否正常&#xff0c;虽然有的设备看着插入usb后指示灯什么都亮了&#xff0c;但是不一定就说明设备没问题&#xff0c;这就需要先验证一下&#xff0c;比如打开记事本或者doc文档&#xff0c;然后扫描一下条形码&#xff0c;…

electron 主进程对预加载脚本和渲染进程通信

知识整理 主进程main.js node环境可以使用node的方法预加载脚本可以使用部分node方法,可以理解为是主进程和渲染进程之间的一个桥梁渲染进程属于浏览器环境,不可以使用node方法,可以操作dom等js方法 主进程对渲染进程通信 上一篇文章实现了自定义菜单栏功能,上上篇实现了预加…

程序员30而立的北京之路

作为一名程序员&#xff0c;职业规划和心灵成长是我工作和生活中不可或缺的部分。30岁是一个人生中的重要节点&#xff0c;也是所谓的“而立之年”&#xff0c;在这个阶段&#xff0c;我开始更加关注自己的职业发展和内心成长。在这篇文章中&#xff0c;我将分享我在北京这座城…

YOLOv8改进 | 细节创新篇 | iAFF迭代注意力特征融合助力多目标细节涨点

一、本文介绍 本文给大家带来的改进机制是iAFF&#xff08;迭代注意力特征融合&#xff09;&#xff0c;其主要思想是通过改善特征融合过程来提高检测精度。传统的特征融合方法如加法或串联简单&#xff0c;未考虑到特定对象的融合适用性。iAFF通过引入多尺度通道注意力模块(我…

花几分钟整点jmeter花活,轻松超越90%软件测试

jmeter 可以做性能测试&#xff0c;这个很多人都知道&#xff0c;那你知道&#xff0c;jmeter 可以在启动运行时&#xff0c;指定线程数和运行时间&#xff0c;自定义性能场景吗&#xff1f; 前言 jmeter 性能测试&#xff0c;动态设定性能场景 平时&#xff0c;我们使用 jmet…

使用.Net nanoFramework 驱动ESP32的OLED显示屏

本文介绍如何使用.Net nanoFramework 驱动ESP32的OLED显示屏。我们将会从最基础的部分开始&#xff0c;逐步深入&#xff0c;让你能够理解并实现整个过程。无论你是初学者还是有一定经验的开发者&#xff0c;这篇文章都会对你有所帮助。 1. 硬件准备 1.1 ESP32开发板 这里我们…