通过模拟一个用户注册并上传头像的过程
sql语句 创建数据库
create table users
(userid char(20) primary key,
userpwd char(20) not null,
userimg char(30) not null);
.dao包中写上一个接口
public interface UserinfoDao {
//注册方法
public int UserRegsiter(Userinfo userinfo);
}
.domain中写上一个用户信息类
public class Userinfo {
private String userid;
private String userpwd;
private String userimg;
public Userinfo(){
super();
}
public Userinfo(String userid,String userpwd,String userimg){
this.userid = userid;
this.userpwd = userpwd;
this.userimg = userimg;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getUserpwd() {
return userpwd;
}
public void setUserpwd(String userpwd) {
this.userpwd = userpwd;
}
public String getUserimg() {
return userimg;
}
public void setUserimg(String userimg) {
this.userimg = userimg;
}
}
.util包中写上用于存放连接数据库的方法以及给上传文件重命名的方法
public class DBUTIL {
private final String DRIVER = "com.mysql.jdbc.Driver";
private final String URl = "jdbc:mysql://localhost:3306/test";
private final String SQLID = "root";
private final String SQLPWD = "123456";
private Connection connection = null;
//获取连接 的方法
public Connection getConn(){
try {
Class.forName(DRIVER);
connection = DriverManager.getConnection(URl, SQLID, SQLPWD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
//关闭连接的方法
public void close(){
try {
if (!connection.isClosed()) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//给上传文件重命名,是为了避免重复文件名覆盖之前的文件
public class fileNameUtil {
public static String createFileName(String oldfilename){
//获取文件后缀
String suffix = oldfilename.substring(oldfilename.lastIndexOf("."));
//根据当前时间给文件重命名
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
Calendar calendar = Calendar.getInstance();
return sdf.format(calendar.getTime())+suffix;
}
}
.impl包中实现业务的具体操作方法,实现注册的方法
public class UserinfoImpl extends DBUTIL implements UserinfoDao{
private Connection conn = null;
PreparedStatement pstm = null;
String sql = null;
ResultSet rs = null;
Userinfo Userinfo = null;
//注册方法
@Override
public int UserRegsiter(Userinfo userinfo) {
conn = getConn();
sql = "insert into users(userid,userpwd,userimg) values(?, ?, ?)";
try {
pstm = conn.prepareStatement(sql);
pstm.setString(1, userinfo.getUserid());
pstm.setString(2, userinfo.getUserpwd());
pstm.setString(3, userinfo.getUserimg());
return pstm.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally{
close();
}
return 0;
}
}
.controller包用于实现业务逻辑
@WebServlet("/UserRegister")
public class UserRegister extends HttpServlet {
private static final long serialVersionUID = 1L;
//定义数组存储得到的数据
private String[] userinfoList = new String[3];
private Userinfo userinfo = null;
private UserinfoDao userinfoDao = null;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//存储数据
save(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
public void save(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置缓冲区大小4k 4*1024
int sizeThreshold = 4096;
//获取服务器地址
String serverPath = request.getServletContext().getRealPath("/");
//设置缓冲区位置,服务器根目录
File repository = new File(serverPath);
//缓冲区设置,放入缓冲区位置及大小
DiskFileItemFactory dff = new DiskFileItemFactory(sizeThreshold, repository);
//实例化上传类 ServletFileUpload
ServletFileUpload fileUpload = new ServletFileUpload(dff);
try {
//获取用户端请求request中的数据,并存入fileItems
List<FileItem> fileItems = fileUpload.parseRequest(request);
//遍历获取的集合
for (int i = 0; i < 3; i++) {
FileItem item = fileItems.get(i);
//判断该表单项是否是普通类型
if (item.isFormField()) {
//是数据,直接存入数组
userinfoList[i] = item.getString();
} else {
//是file类型
// System.out.println(item.getContentType());
//判断文件是不是图片文件
if ((!item.getContentType().equals("image/png"))&&
(!item.getContentType().equals("image/jpg"))&&
(!item.getContentType().equals("image/eng"))&&
(!item.getContentType().equals("image/gif"))){
//不是图片文件,返回register.jsp注册页面,并提示用户
request.setAttribute("msg1", "注册失败!头像请上传图片文件...");
request.getRequestDispatcher("register.jsp").forward(request, response);
return;
}
//判断图片是否大于1M
if (item.getSize()>1024*1024) {
//图片大于1M,返回register.jsp注册页面,并提示用户
request.setAttribute("msg2", "注册失败!头像请上传小于1M的图片文件...");
request.getRequestDispatcher("register.jsp").forward(request, response);
return;
}
// item.getSize()
//item.getContentType()
//是小于1M的图片文件
//调用Upload方法上传文件到服务器目录下的upload文件夹下
//该方法返回相对于服务器根目录的文件地址
userinfoList[i] = Upload(item,serverPath);
}
}
//将读取的纯数据数组userinfoList存入数据库
//创建用户信息类
userinfo = new Userinfo();
//存入数组中存放的用户数据
userinfo.setUserid(userinfoList[0]);
userinfo.setUserpwd(userinfoList[1]);
userinfo.setUserimg(userinfoList[2]);
userinfoDao = new UserinfoImpl();
//调用写入数据库的注册方法
if (userinfoDao.UserRegsiter(userinfo)>0) {
//注册成功,创建浏览器session变量userinfo,存放注册用户的基本信息
HttpSession session = request.getSession();
session.setAttribute("userinfo", userinfo);
//并返回主页
response.sendRedirect("index.jsp");
return;
} else{
//注册失败,返回注册页面,并返回注册失败的提示信息
request.setAttribute("msg3", "注册失败!请重试...");
request.getRequestDispatcher("register.jsp").forward(request, response);
return;
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
//上传文件file到根目录filepath下的upload文件夹下,并返回存入文件的新名称及父级目录
public String Upload(FileItem item,String filepath){
//文件重命名
String fileNewName = fileNameUtil.createFileName(item.getName());
//判断upload存不存在,不存在就创建一个文件夹
String fileBinPath = filepath+"upload/";
File fileBin = new File(fileBinPath);
if (!fileBin.exists()) {
fileBin.mkdirs();
}
//写入磁盘
File file = new File(fileBinPath+fileNewName);
try {
item.write(file);
} catch (Exception e) {
e.printStackTrace();
}
return "upload/"+fileNewName;
};
}
注册界面register.jsp
// enctype="multipart/form-impldata" 表单数据以字节流上传
<form action="UserRegister" method="post" enctype="multipart/form-data">
请输入账号:<input type="text" name="userid"/><br/>
请输入密码:<input type="password" name="userpwd"/><br/>
上传个性图片<input type="file" name="userimg" value="选择图片"/><br/>
<input type="submit" value="注册"/><br/>
</form>
//接受当上传的头像不是图片文件的错误提示
${msg1 }
//接受当上传的头像大小大于1M的时候的错误提示
${msg2 }
//接受当注册失败的时候的错误提示
${msg3 }
index.jsp主页,写了一个a连接去个人中心,以及一些样式
<style>
a{
text-decoration: none;
font-size:20px;
cursor:pointer;
}
/*默认状态*/
a:link{
color: blue;
}
/*访问后得状态*/
a:visited{
color: #19242C;
}
/*鼠标悬浮状态*/
a:hover{
color: #FF0000;
}
/*点击状态*/
a:active{
color: aqua;
}
img{
height:40px;
width:40px;
}
</style>
//由于注册成功后创建了浏览器session变量userinfo,因此可以直接获取其中的用户信息
<a href="self.jsp">
<img src="${userinfo.getUserimg()}"/>
${userinfo.getUserid()},欢迎您登录本网站!
</a>
self.jsp个人主页,用于显示一些个人信息
<table>
<tr>
<td>账号</td>
<td>密码</td>
<td>头像</td>
</tr>
<tr>
//由于注册成功后创建了浏览器session变量userinfo,因此可以直接获取其中的用户信息
<td>${userinfo.getUserid()}</td>
<td>${userinfo.getUserpwd()}</td>
<td><img src="${userinfo.getUserimg()}"/></td>
</tr>
</table>
效果
1.注册
2.填入信息 12345 12345 ,随便选择一张图片
3.注册成功跳转到主页
4.点击链接进入个人中心
5.查看数据库sql,最后一行可以看到页面输入的注册信息
基本实现了页面注册的功能
以上一些后缀的说法可以查看我的另一篇博客mvc模式
以上是基于mvc开发模式写的一个基本的最简单的注册页面,其中最难的在于文件的上传比较复杂,不过基本都有注释,应该不难理解…