1.创建数据库及表
注意:
MySQL :cms密码123;数据库port:3307
打开cmd输入mysql -u root -p后系统响应,再输入口令就行了,即可进入到Mysql
数据库操作:
1.登录root用户:mysql -uroot -p;123
2.创建一个数据库
create database bos;
3.创建新用户:root是最高级别的用户,权限太大,不仅可以操作当前的数据库,还可以操作别的数据库。
create user xiaoli identified by '123';
方法二:create user 'cms'@'localhost' identified by '123';
4.对创建的用户授权才能操作。all指对*的增删改查权限。
grant all on bos.* to xiaoli;
5.登录数据库;
mysql -uxiaoli -p123;我的电脑直接输这个指令进不去,要先输入mysql -uxiaoli -p,再在enter password里输123;
localhost是登录数据库时的mysql host address ,bos是创建的数据库名,3307是端口号port
jdbcUrl =jdbc:mysql://localhost:3307/bos
2 .开发web应用
a、搭建开发环境:
1)添加jar包
2)根据MVC开发模式,创建包的目录树。
b、根据数据库的USER表创建实现---set和get方法(javaBean)
实体类名字可以与表名一致致。(domain包下)
c、创建DAO接口及其实现类----数据访问层(操作数据库的表,进行数据的增删改查)
1)先连接数据库数据:
DBUtil.java:
package com.itheima.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
public class DBUtils {
private static String driverClass;
private static String url;
private static String username;
private static String password;
static{
//�˶��������ڼ���properties�ļ���ݵ�
ResourceBundle rb = ResourceBundle.getBundle("dbinfo");
driverClass = rb.getString("driverClass");
url = rb.getString("url");
username = rb.getString("username");
password = rb.getString("password");
try {
Class.forName(driverClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//得到连接的方法
public static Connection getConnection() throws Exception{
return DriverManager.getConnection(url, username, password);
}
//关闭数据
public static void closeAll(ResultSet rs,Statement stmt,Connection conn){
//�ر���Դ
if(rs!=null){
try {
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
rs = null;
}
if(stmt!=null){
try {
stmt.close();
} catch (Exception e) {
e.printStackTrace();
}
stmt = null;
}
if(conn!=null){
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
conn = null;
}
}
}
配置文件info.properties:
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3307/test1
username=xiaoli1
password=123
2)UserDao.java:
package com.cms.dao;
import com.cms.domain.User;
public interface UserDao {
/**
* 添加用户信息的接口
* @param user
* @throws Exception
*/
public void addUser(User user) throws Exception;
}
UserDaoImpl:
package com.cms.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import com.cms.dao.UserDao;
import com.cms.domain.User;
import com.cms.utils.DBUtils;
public class UserDaoImpl implements UserDao {
@Override
public void addUser(User user) throws Exception {
Connection conn = null;
PreparedStatement ps=null;
// TODO Auto-generated method stub
try {
conn = DBUtils.getConnection();
ps = conn.prepareStatement("INSERT INTO users(username,PASSWORD,email,birthday) VALUES(?,?,?,?)");
ps.setString(1, user.getUsername());
ps.setString(2, user.getPassword());
ps.setString(3, user.getEmail());
//转换日期类型
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(user.getBirthday());
ps.setString(4,date );
//执行SQL语句
int i = ps.executeUpdate();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException("添加失败!");
}finally{
DBUtils.closeAll(null, ps, conn);
}
}
}
d、创建Service接口并实现该接口。(业务层)
UserService.java(接口):
package com.cms.service;
import com.cms.domain.User;
public interface UserService {
/**
* 添加用户信息
*/
public void register(User user) throws Exception;
}
UserServiceImplement.java:
package com.cms.service.impl;
import com.cms.dao.UserDao;
import com.cms.dao.impl.UserDaoImpl;
import com.cms.domain.User;
import com.cms.service.UserService;
public class UserServiceImpl implements UserService {
UserDao userDao = new UserDaoImpl();
@Override
public void register(User user) throws Exception {
// TODO Auto-generated method stub
userDao.addUser(user);
}
}
e、servlet-----要封装表单数据
login.jsp:
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href=“”>登录</a>
<a href="register.jsp">注册</a>
</body>
</html>
register.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/registerServlet" method="post">
用户名:<input type="text" name="username" value="${uf.username }"/>${uf.msg.username }${error }<br/>
密码:<input type="password" name="password" />${uf.msg.password }<br/>
确认密码:<input type="password" name="repassword"/>${uf.msg.repassword }<br/>
邮箱:<input type="text" name="email" value="${uf.email }"/>${uf.msg.email }<br/>
生日:<input type="text" name="birthday" value="${uf.birthday }"/>${uf.msg.birthday }<br/>
<input type="submit" value="注册"/><br/>
</form>
</body>
</html>
RegisterServlet.java:
package com.cms.web.servlet;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.beanutils.locale.converters.DateLocaleConverter;
import com.cms.domain.User;
import com.cms.service.UserService;
import com.cms.service.impl.UserServiceImpl;
/**
* Servlet implementation class RegisterServlet2
*/
@WebServlet("/RegisterServlet2")
public class RegisterServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
// 获取表单数据
User user = new User();
try {
/*ConvertUtils.register(new Converter() {//注册一个日期转换器
@Override
public Object convert(Class type, Object value) {
Date date1 = null;
if(value instanceof String){
String date = (String)value;
// TODO Auto-generated method stub
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
date1 = sdf.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return date1;
}
}, Date.class);*/
ConvertUtils.register(new DateLocaleConverter(), Date.class);
BeanUtils.populate(user, request.getParameterMap());//不支持日期类型,数据库无法插入数据,ConvertUtils封装好了;
//调用业务逻辑
UserService us = new UserServiceImpl();
us.register(user);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//分发转向
response.getWriter().write("注册成功!1秒后跳到首页,请等待............................");
response.setHeader("refresh", "1;url="+request.getContextPath()+"/index.jsp");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
结果:用户注册数据库刷新已插入该用户数据。