利用Java+Html+Jsp实现简单的MVC分层项目->实现表的增删改查

graph TD View-->Service Service-->Controller Service-->View Controller-->Service

准备工作:

无骨架创建一个maven项目,配置文件目录【增加webapp目录,在webapp下面一级添加web.xml文件】,配置pom.xml文件【导入需要的依赖】:

<?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.exmple</groupId>
    <artifactId>table-demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <packaging>war</packaging>
<dependencies>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</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.2</version>
    </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>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.24</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.10</version>
        <scope>compile</scope>
    </dependency>
</dependencies>
</project>

配置资源文件mybatis-config.xml文件:数据库的url需修改成需要使用的数据库

<?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.demo1.pojo"></package>
    </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:///study_db?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--加载sql映射文件-->
        <mapper resource="com/demo1/mapper/UserInfoMapper.xml"/>
    </mappers>
</configuration>

创建表对应的实体类【xxMapper.java】,在资源目录下面创建目录【com/xx/mapper】,在此目录配置sql映射文件【xxmapper.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.demo1.mapper.UserInfoMapper">
</mapper>

创建实体类【xx】:

@ToString
@NoArgsConstructor
@AllArgsConstructor
@Setter
@Getter
public class UserInfo {
    private Integer id;
    private String userName;
    private String userPwd;

}

mybatis-config.xml中的package name需要修改成对应的存放实体类的包,mapper的映射文件路径需要修改到对应的mapper接口路径【上面已经修改】,【xxmapper.xml】中的命名空间需要修改成对应的mapper接口存放的包,返回类型需要修改为接收的实体类【上面也修改好了】创建service层【service层其实应该是接口和他的实现类,但我这里写了类,懒得改了】和对应的类,发现代码重复很多,创建工具类获取SqlSessionFactory对象:

public class SqlSF {
    private static SqlSessionFactory sqlSessionFactory;
    private SqlSF() {

    }
    public static SqlSessionFactory getSSF() {
        try {
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactory build = new SqlSessionFactoryBuilder().build(inputStream);
            return build;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

在mapper接口中创建对应的增删改查方法:

public interface UserInfoMapper {
    /**
     * 查看所有用户
     * @return
     */
    List<UserInfo> selectAll();

    /**
     * 根据id查找用户
     * @param id
     * @return
     */
    UserInfo select(int id);

    /**
     * 添加用户
     * @param userInfo
     * @return
     */
    int add(UserInfo userInfo);

    /**
     * 删除用户
     * @param id
     * @return
     */
    int delete(int id);

    /**
     * 修改用户信息
     * @param userInfo
     * @return
     */
    int update(UserInfo userInfo);
}

在sql映射文件中,添加对应的映射方法【标签的id和接口中的方法名要一致】:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace:名称空间-->
<mapper namespace="com.demo1.mapper.UserInfoMapper">
    <resultMap id="userRs" type="UserInfo">
        <result column="user_name" property="userName"></result>
        <result column="user_pwd" property="userPwd"></result>
    </resultMap>
    <insert id="add">
        insert into login_user values (null,#{userName},#{userPwd});
    </insert>
    <update id="update">
        update login_user
        <set>
            <if test="userName!= null">user_name=#{userName},</if>
            <if test="userPwd!= null">user_pwd=#{userPwd},</if>
        </set>
        where id=#{id}
    </update>
    <delete id="delete">
        delete from login_user where id=#{id}
    </delete>
    <select id="selectAll" resultMap="userRs">
        select * from login_user;
    </select>
    <select id="select" resultMap="userRs">
        select * from login_user where id=#{id}
    </select>
</mapper>

在service层创建方法:

public class UserService {
    SqlSessionFactory ssf = SqlSF.getSSF();
    public List<UserInfo> selectAll() {
        SqlSession sqlSession = ssf.openSession();
        UserInfoMapper mapper = sqlSession.getMapper(UserInfoMapper.class);
        return mapper.selectAll();
    }
    public void add(UserInfo userInfo) {
        SqlSession sqlSession = ssf.openSession();
        UserInfoMapper mapper = sqlSession.getMapper(UserInfoMapper.class);
        mapper.add(userInfo);
        sqlSession.commit();
    }
    public void delete(int id) {
        SqlSession sqlSession = ssf.openSession();
        UserInfoMapper mapper = sqlSession.getMapper(UserInfoMapper.class);
        mapper.delete(id);
        sqlSession.commit();
    }
    public void update(UserInfo userInfo) {
        SqlSession sqlSession = ssf.openSession();
        UserInfoMapper mapper = sqlSession.getMapper(UserInfoMapper.class);
        int update = mapper.update(userInfo);
        System.out.println(update);
        sqlSession.commit();
    }
    public UserInfo select(int id) {
        SqlSession sqlSession = ssf.openSession();
        UserInfoMapper mapper = sqlSession.getMapper(UserInfoMapper.class);
       return mapper.select(id);
    }
}

填写对应的web页面【直接在resources目录下面创建文件】:

默认页面index.html:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>主页</title>
</head>
<body>
<button onclick="show()">显示全部用户</button>
<button onclick="add()">新增用户</button>
<script>
    function show() {
        location.href="/selectAllServlet"
    }
    function add() {
        location.href="/add.html"
    }
</script>
</body>
</html>

显示用户信息页面showAllUser.jsp:

<%@page language="java" pageEncoding="UTF-8" %>
<%@taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<%@page isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
    <meta charset="UTF-8">
</head>
<body>
<div align="center" style="text-align: center">
    <form method="post">
    <table border="1px" cellspacing="0px" align="center">
        <tr>
            <th>用户名</th>
            <th>密码</th>
            <th>编号</th>
            <th>操作</th>
        </tr>
        <c:forEach items="${AllUser}" var="user">
            <tr align="center">
                <td>${user.userName}</td>
                <td>${user.userPwd}</td>
                <td>${user.id}</td>
                <td>
                   <a href="/deleteServlet?delete_id=${user.id}">删除</a>
                   <a href="/showServlet?update_id=${user.id}">修改</a>
                </td>
            </tr>
        </c:forEach>
    </table>
    </form>
</div>
</body>
</html>

新增用户页面add.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>注册</title>
</head>
<body>
<form action="/addServlet" method="post">
用户名<input type="text" name="username"/><br/>
密码 <input type="password" name="password"><br/>
<input type="submit">
</form>
</body>
</html>

修改信息的页面showInfo.jsp:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>修改信息页面</title>
</head>
<body>
<form action="/updateServlet" method="post">
    <table>
        <tr>
            <td>编号</td>
            <td><input type="text" value="${user.id}" name="id"/></td>
        </tr>
        <tr>
            <td>用户名</td>
            <td><input type="text" value="${user.userName}" name="username"/></td>
        </tr>
        <tr>
            <td>密码</td>
            <td><input type="text" value="${user.userPwd}" name="password"/></td>
        </tr>
        <tr>
            <td colspan="2">
                <button>修改</button>
            </td>
        </tr>
    </table>
</form>
</body>
</html>

创建对应的servlet类【建议写完一个页面创建一个servlet,实现好一个功能之后再去实现另一个功能】:

新增用户:

@WebServlet(urlPatterns = "/addServlet")
public class AddServlet extends HttpServlet {
    private  UserService userService = new UserService();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName(username);
        userInfo.setUserPwd(password);
        userService.add(userInfo);
        request.getRequestDispatcher("/selectAllServlet").forward(request,response);
    }
}

删除用户:

@WebServlet(urlPatterns = "/deleteServlet")
public class DeleteServlet extends HttpServlet {
    private  UserService userService = new UserService();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String deleteBtn = request.getParameter("delete_id");
        userService.delete(Integer.parseInt(deleteBtn));
        request.getRequestDispatcher("/selectAllServlet").forward(request,response);
    }
}

修改用户:修改用户信息需要根据用户的id查到用户原有的信息再去修改:

展示用户原有信息:

@WebServlet(urlPatterns = "/showServlet")
public class ShowServlet extends HttpServlet {
    private UserService userService=new UserService();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String updateId = request.getParameter("update_id");
        UserInfo select = userService.select(Integer.parseInt(updateId));
        request.setAttribute("user",select);
        request.getRequestDispatcher("/showInfo.jsp").forward(request,response);
    }
}

修改:

@WebServlet(urlPatterns = "/updateServlet")
public class UpdateServlet extends HttpServlet {
    private UserService userService=new UserService();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String id = request.getParameter("id");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        userService.update(new UserInfo(Integer.parseInt(id),username,password));
        request.getRequestDispatcher("/selectAllServlet").forward(request,response);
    }
}

查询所有用户信息:

@WebServlet(urlPatterns = "/selectAllServlet")
public class SelectAllServlet extends HttpServlet {
    private  UserService userService = new UserService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<UserInfo> userInfos = userService.selectAll();
        request.setAttribute("AllUser", userInfos);
        request.getRequestDispatcher("/showAllUser.jsp").forward(request, response);
    }
}
posted @ 2023-01-11 22:05  Liku007  阅读(175)  评论(0编辑  收藏  举报