需求:
通过html+Servlet+MyBatis,完成站点信息的添加功能。
以下是站点表的建表语句:
CREATE TABLE `websites` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` char(20) NOT NULL DEFAULT '' COMMENT '站点名称',
`url` varchar(255) NOT NULL DEFAULT '',
`alexa` int(11) NOT NULL DEFAULT '0' COMMENT 'Alexa 排名',
`country` char(10) NOT NULL DEFAULT '' COMMENT '国家',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
步骤:
RegisterServlet:
package com.ambow.controller;
import com.ambow.dao.UserDao;
import com.ambow.pojo.User;
import com.ambow.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/doRegister")
public class RegisterServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.修改编码
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//2.获取参数
String name = request.getParameter("name");
String url = request.getParameter("url");
Integer alexa = Integer.valueOf(request.getParameter("alexa"));
String country = request.getParameter("country");
//3.构建对象
User user = new User(name, url, alexa, country);
//4.获取代理对象
SqlSession sqlSession = MyBatisUtil.getSqlSession();
UserDao mapper = sqlSession.getMapper(UserDao.class);
//5.执行添加
PrintWriter out = response.getWriter();
int row = mapper.insertUser(user);
sqlSession.commit();
if (row != 0) {
out.println("<h1 align='center'>添加成功!!!</h1>");
} else {
out.println("<h1 align='center'>添加失败!!!</h1>");
}
}
}
UserDao:
package com.ambow.dao;
import com.ambow.pojo.User;
public interface UserDao {
int insertUser(User user);
}
User:
package com.ambow.pojo;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class User {
private int id;
private String name;
private String url;
private int alexa;
private String country;
public User(String name, String url, int alexa, String country) {
this.name = name;
this.url = url;
this.alexa = alexa;
this.country = country;
}
}
MyBatisUtil:
package com.ambow.util;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class MyBatisUtil {
//获取数据库链接
public static SqlSession getSqlSession(){
SqlSession sqlSession = null;
//读取主配置文件
String resource = "mybatis-config.xml";
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
//获取SqlSessionFactory - 工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//获取SqlSession - 连接对象
sqlSession = sqlSessionFactory.openSession();
} catch (IOException e) {
e.printStackTrace();
}
return sqlSession;
}
}
UserDao.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.ambow.dao.UserDao">
<insert id="insertUser">
insert into websites values(null,#{name},#{url},#{alexa},#{country})
</insert>
</mapper>
jdbc.properties:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://192.168.2.111:3306/db1
username=root
password=Mysql666!
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="jdbc.properties" />
<settings>
<!--开启数据库日志检测-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<typeAliases>
<!--<typeAlias type="com.ambow.pojo.User" alias="user"></typeAlias>-->
<package name="com.ambow.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.ambow.dao"/>
</mappers>
</configuration>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
</web-app>
register.html:
<!DOCTYPE html>
<html>
<head>
<title>站点信息</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.staticfile.org/twitter-bootstrap/5.1.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.staticfile.org/twitter-bootstrap/5.1.1/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<div class="container mt-2">
<h1><b>新增站点</b></h1>
<br>
<form action="doRegister" method="post">
<div class="mb-2 mt-2">
<label for="webname" class="form-label">站点名称:</label>
<input type="text" class="form-control" id="webname" placeholder="请输入站点名称" name="webname">
</div>
<br>
<div class="mb-2">
<label for="url" class="form-label">站点网址:</label>
<input type="text" class="form-control" id="url" placeholder="请输入站点网址" name="url">
</div>
<br>
<div class="mb-2 mt-2">
<label for="alexa" class="form-label">站点排名:</label>
<input type="text" class="form-control" id="alexa" placeholder="输入站点的名次" name="alexa">
</div>
<br>
<div class="mb-2 mt-2">
<label for="country" class="form-label">所在国家:</label>
<select class="form-select" id="country" name="country">
<option value="中国">中国</option>
<option value="美国">美国</option>
<option value="印度">印度</option>
<option value="日本">日本</option>
<option value="德国">德国</option>
</select>
</div>
<br>
<div class="mb-4 mt-4">
<label for="sign" class="form-label">简要介绍:</label>
<br/>
<textarea cols="40" rows="10" id="sign" name="sign"></textarea>
</div>
<button type="submit" class="btn btn-primary">添加</button>
</form>
</div>
</body>
</html>
RegTest:
package com.ambow.test;
import com.ambow.dao.UserDao;
import com.ambow.pojo.User;
import com.ambow.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
public class RegTest {
@Test
public void test01(){
SqlSession sqlSession = MyBatisUtil.getSqlSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
User user = new User();
user.setName("淘宝");
user.setUrl("http://taobao.com");
user.setAlexa(20);
user.setCountry("中国");
int i = userDao.insertUser(user);
sqlSession.commit();
System.out.println(i);
}
}
项目结构如下:
运行主程序:
点击网址跳转到浏览器:
填写信息如下:
点击提交按钮:
数据库中查看信息: