使用添加用户
创建UserDao 接口
package com.bdqn.dao;
import com.bdqn.pojo.User;
public interface UserDao {
//添加
int addUser(User user);
}
创建UserDaoimpl 实现类
package com.bdqn.dao;
import com.bdqn.pojo.User;
import com.bdqn.utli.BaseDao;
import org.springframework.stereotype.Repository;
//注解到UserDao
@Repository(value = "userDao")
public class UserDaoimpl extends BaseDao implements UserDao {
//添加的方法
@Override
public int addUser(User user) {
String sql="INSERT INTO user (name,password) VALUES(?,?)";
Object[]objects={user.getName(),user.getPassword()};
return this.executeUpdate(sql,objects);
}
}
创建实体类User
package com.bdqn.pojo;
import com.sun.istack.internal.NotNull;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotEmpty;
public class User {
private int id;
@NotEmpty(message = "用户名不能为空")
private String name;
@Length(min = 6,max = 10 ,message = "密码长度必须为6-10位")
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
}
创建UserService接口
package com.bdqn.service;
import com.bdqn.pojo.User;
public interface UserService {
//添加
boolean addUser(User user);
}
创建UserServiceimpl接口
package com.bdqn.service;
import com.bdqn.dao.UserDao;
import com.bdqn.pojo.User;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
//注解
@Service
public class UserServiceimpl implements UserService {
//创建UserDao
@Resource
private UserDao userDao;
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
//添加的方法
@Override
public boolean addUser(User user) {
if (userDao.addUser(user)>0){
return true;
}else {
return false;
}
}
}
创建BasDao
package com.bdqn.utli;
import java.sql.*;
public class BaseDao {
private String url = "jdbc:mysql://localhost:3306/text?serverTimezone=GMT-8&characterEncoding=utf8";//连接字符串
private String user = "root";//用户
private String password = "123.com";//密码
public Connection conn = null;//连接对象
public PreparedStatement ps = null;//创建执行者
public ResultSet rs = null;
//获取连接对象的方法啊
public Connection getConn(){
try {
//如果连接对象为空,则获取连接对象
if(conn==null){
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, user, password);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
//关闭所有资源的方法
public void CloseAll(Connection conn,PreparedStatement ps,ResultSet rs){
//如果连接对象不为空,则关闭连接
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//如果执行者不为空,则释放资源
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//如果ResultSet不为空,则释放资源
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//增删改的通用方法 返回int类型
public int executeUpdate(String sql,Object [] obj){
int rows = 0;
conn = this.getConn();
try {
ps = conn.prepareStatement(sql);
if(obj!=null){
for (int i = 0; i < obj.length; i++) {
ps.setObject(i+1,obj[i]);
}
}
rows = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return rows;
}
//查询的通用方法,返回ResultSet类型
public ResultSet executeQuery(String sql,Object [] obj){
conn = this.getConn();
try {
ps = conn.prepareStatement(sql);
if(obj!=null){
for (int i = 0; i < obj.length; i++) {
ps.setObject(i+1,obj[i]);
}
}
rs = ps.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
}
配置applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--对dao层和service、controller扫包-->
<context:component-scan base-package="com.bdqn.dao"/>
<context:component-scan base-package="com.bdqn.service"/>
<mvc:annotation-driven/>
<context:component-scan base-package="com.bdqn.controller"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!--配置静态资源-->
<mvc:resources mapping="/statics/**" location="/statics/"/>
</beans>
创建addjsp
<%@ taglib prefix="fm" uri="http://www.springframework.org/tags/form" %>
<%--
Created by IntelliJ IDEA.
User: 89800
Date: 2022/8/30
Time: 14:42
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>
<fm:form method="post" modelAttribute="user">
<p>
姓名:<fm:input path="name"/> <span><fm:errors path="name"/> </span>
</p>
<p>
密码:<fm:password path="password"/> <span><fm:errors path="password"/> </span>
</p>
<p>
<input type="submit" value="提交"/>
</p>
</fm:form>
</body>
</html>
创建success.jsp
<%--
Created by IntelliJ IDEA.
User: 89800
Date: 2022/8/30
Time: 14:42
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>
</body>
</html>
创建error.jsp
<%--
Created by IntelliJ IDEA.
User: 89800
Date: 2022/8/30
Time: 14:42
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>
</body>
</html>
创建UserController 类
package com.bdqn.controller;
import com.bdqn.pojo.User;
import com.bdqn.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
//注解
@Controller
//定义前缀
@RequestMapping(value = "/record")
public class UserController {
//定义UserService接口
@Resource
private UserService userService;
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
/*去往添加页面*/
@GetMapping("/add")
public String toAdd(@ModelAttribute("user") User user){
return "user/add";
}
/*添加用户*/
@PostMapping("/add")
public String addUser(@Valid User user,BindingResult bindingResult, Model model, HttpSession session){
//定义属性到页面 并循环读取
model.addAttribute("user",user);
if (bindingResult.hasErrors()){
return "user/add";
}
//如果添加成功跳转成功页面,否则跳转失败页面
if (userService.addUser(user)){
return "user/success";
}else{
return "user/error";
}
}
}
进行测试
我们前面在User实体类里面定义了非空判断,我们输入密码,下雨6位让他出发非空判断
我们输入正确的不触发非空判断 ,大家可以看见成功了符合我们非空判断的要求,所以数据库添加成功