一 创建项目并修改项目结构
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