带头像的用户显示功能

作为一个javaweb的小白,也不知以前做了多少demo,但始终有一个遗憾,我的数据库的用户没有图像,只有姓名和id等等其他属性,今天想起来,觉得是一种遗憾,于是我决定研究一把,做一个完美的demo,让我数据库里面的用户,也能有一个美丽图像。

1.我首先帮我的表结构以图片,展示出来,表很容易

表其实特表简单,我就弄了几个简单字段,然后注意的就是我存用户图像存的是地址。



2.这个简单的demo,我用了一些小框架,我先说明一下 struts2 , mybatis ,然后一些前端技术 bootstrap ,jquery ,javacript ,我相信这些技术大家伙肯定很熟悉。

我用mybatis主要是和数据库交互的,这一方面,大家是可以随便换成 其他的技术 比如原初的:jdbc 等等,

 1).我先把我的用户修改页面展示出来,各位看官不要看代码或多,大部分都是样式, 这个页面就是模拟用户在修改自己的图像的时候,上传一张图片<s:form action="fileUpload" method="post" enctype="multipart/form-data">
<s:hidden name="user.id"></s:hidden>
      <input type="file" class="input-group" name="file"><br>
       <button type="submit" class="btn btn-primary">提交</button>
    </s:form>

我们这里上传的action路径是 fileUpload ,我们是form这个表单上传,关键熟悉就是enctype="multipart/form-data",指定了这个属性,我们就能上传一个file文件。然后我们在Struts2的配置文件(struts.xml)中设置只能上传只能上传png,gif,jpeg格式的图片

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width,inittal-scale=1" />
		<title>更改用户信息</title>
		<script src="<%=basePath%>/resource/js/jquery-3.1.1.js" type="text/javascript" charset="utf-8"></script>
		<link rel="stylesheet" href="<%=basePath%>/resource/css/bootstrap.css" />
		<script src="<%=basePath%>/resource/js/bootstrap.js" type="text/javascript" charset="utf-8"></script>
		<script src="<%=basePath%>/resource/js/setimgurl.js" type="text/javascript" charset="utf-8"></script>
		
	</head>
	<body>
		<center>
			<h1 style="color: orange;">用户信息修改</h1>
			
		<div class="img-circle" style="margin-top: 20px;margin-left: 7px;height: 100px;">
		<img src="<%=basePath%>/resource/img/userImg1.jpg" data-toggle="modal" data-target="#myModal" id="cuimg" style="width: 100px;height: 100px;"/><span style="font-size: 18px;color:#31B0D5;margin-left: 6px;">上之恋奶茶</span>
		<input type="image" src="<%=basePath%>/resource/img/update.png" style="width: 20px;height: 20px;margin-left: 6px;" />
		</div>
		<div style="margin-left:180px ;">
			<input type="class="form-control"" name="birth" placeholder="生日"/><br />
			<input type="class="form-control""  style="margin-top: 8px;" name="sex" placeholder="性别"/><br />
			<input type="class="form-control"" style="margin-top: 8px;" name="telphoe" placeholder="电话"/><br/>
			<button type="submit" style="margin-top: 8px;" class="btn-info">提交</button>
		</div>
		</center>
		
		<input type="hidden" id="myhide" value="${requestScope.image}">
		<!-- 模态框(Modal) -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" 
						aria-hidden="true">×
				</button>
				<h4 class="modal-title" id="myModalLabel">
					上传用户图片
				</h4>
			</div>
			<div class="modal-body">
				<span>只能上传png,gif,jpeg格式的图片</span>
				 <s:form action="fileUpload" method="post" enctype="multipart/form-data">
					<s:hidden name="user.id"></s:hidden>
			      	<input type="file" class="input-group" name="file"><br>
			        <button type="submit" class="btn btn-primary">提交</button>
			     </s:form>
			</div>
			
		</div>
	</div>
</div>
	</body>
</html>
2).这是我们struts,xml文件的配置,我们在action设置了我们请求的路径 fileUpload ,这就是我们form请求的路径,在param里面我们设置了我们只能上传的文件类型,这是不是很容易了
<action name="fileUpload" class="com.xuhang.action.UserAction" method="fileUpload">
			<result name="success">/index.jsp</result>
			 <interceptor-ref name="defaultStack">   
			    <!-- 配置允许上传的文件类型,多个用","分隔 -->   
			    <param name="fileUpload.allowedTypes">   
			       image/png,image/gif,image/jpeg    
			 </param>   
			</interceptor-ref> 
		</action>
3).接下来我们要在我们的action类里面处理我们的请求,这里设计到了一个简单的IO流操作
package com.xuhang.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.RequestAware;
import org.omg.CORBA.Request;

import com.opensymphony.xwork2.ActionSupport;
import com.xuhang.bean.User;
import com.xuhang.service.UserService;

public class UserAction extends ActionSupport implements RequestAware{
	
	private Map<String, Object> request;
	
	//对于三个属性的命名规则是是file+FileName,file+ContentType,评级而成,“+”后面的是包里面默认的属性名称,我们只能自己命名“+”前面的,我们要对这3个属性file,fileFileNamefileContentType
	//实现getter 和 setter方法,方便我们的IO流操作
	//页面提交过来的file文件
	private File file;
	    
    //提交过来的file的名字
    private String fileFileName;
    
    //提交过来的file的MIME类型
    private String fileContentType;
    
 
    private String image;
	
	public String getResult() {
		return result;
	}
	public void setResult(String result) {
		this.result = result;
	}
	
	public File getFile() {
		return file;
	}
	public void setFile(File file) {
		this.file = file;
	}
	public String getFileFileName() {
		return fileFileName;
	}
	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}
	public String getFileContentType() {
		return fileContentType;
	}
	public void setFileContentType(String fileContentType) {
		this.fileContentType = fileContentType;
	}
	
	
	//上传图片
	public String fileUpload() throws Exception {
		//获得上传的路径
		String root = ServletActionContext.getServletContext().getRealPath("/resource/img");
		InputStream is  = new FileInputStream(file);
		
		OutputStream os = new FileOutputStream(new File(root, fileFileName));
		System.out.println("fileFileName:"+fileFileName);
		byte[] buffer = new byte[500];
		
		int length = 0;
		while(-1!=(length=is.read(buffer, 0, buffer.length))){
			os.write(buffer);
		}
		os.close();
		is.close();
		image = "resource/img/"+fileFileName;
		User user = new User();
		user = new User();	
		Integer integer = new Integer(1);
		user.setId(integer);
		user.setImgurl(image);
		
		UserService userService = new UserService();
		userService.updateUserImgUrl(user);
		
		
		return SUCCESS;
	}
	
	//得到request对象以Map<String,Object>的形式
	public void setRequest(Map<String, Object> arg0) {
		this.request=arg0;
		
	}
	
	
}
3)接下来就是一些存到数据的过程,这些和大家平时的操作都是一样,我就直接copy代码了

package com.xuhang.service;

import com.xuhang.bean.User;
import com.xuhang.dao.UserDAO;

public class UserService {
	UserDAO userDAO = new UserDAO();
	public void updateUserImgUrl(User user){
		userDAO.userUpdate(user);
	}
	
}
package com.xuhang.dao;




import java.io.IOException;

import org.apache.ibatis.session.SqlSession;

import com.xuhang.bean.User;
import com.xuhang.util.DBUtil;



public class UserDAO {
	
	/**
	 * 上传图片到数据库
	 * @param file
	 * @return
	 */
	public void userUpdate(User user){
		
		DBUtil dbUtil = new DBUtil();
		SqlSession sqlSession = null;
		try {
			sqlSession = dbUtil.getSqlSession();
			System.out.println("自定义输出:"+user.getId()+"  "+user.getImgurl());
			
			sqlSession.update("MyUser.updateUser",user);
			sqlSession.commit();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(sqlSession != null){
				sqlSession.close();
			}
		}
		
	}
	
	
}

看一下mybatis配置文件就是一个更新语句

<?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="MyUser">

  <resultMap type="com.xuhang.bean.User" id="User">
    <id column="id" jdbcType="INTEGER" property="id"/>
    <result column="userName" jdbcType="VARCHAR" property="userName"/>
    <result column="userpwd" jdbcType="VARCHAR" property="userpwd"/>
    <result column="birth" jdbcType="VARCHAR" property="birth"/>
    <result column="sex" jdbcType="CHAR" property="sex"/>
    <result column="telphone" jdbcType="VARCHAR" property="telphone"/>
    <result column="imgurl" jdbcType="VARCHAR" property="imgurl"/>
  </resultMap>

      <update id="updateUser" parameterType="com.xuhang.bean.User" >
      		update userInfo
      		<set>
      			<if test="userName !=null">
      				userName = #{userName},
      			</if>
      			<if test="userpwd !=null">
      				userpwd = #{userpwd},
      			</if>
      			<if test="birth !=null">
      				birth = #{birth},
      			</if>
      			<if test="sex !=null">
      				sex = #{sex},
      			</if>
      			<if test="telphone !=null">
      				telphone = #{telphone},
      			</if>
      			<if test="imgurl !=null">
      				imgurl = #{imgurl}
      			</if>
      		</set>
      		where id = #{id}
      </update>
      
</mapper>
2.上面这些操作就是把这张的图片的地址存到数据库,很容易吧!别小看这些,因为默认的用户图片地址是没有的,所以我们先上传了一张图片地址到数据库,方便待会我们使用这张地址。做完这些,我们回归到正题中

1).带图像的用户显示页面,这是页面,我们按照逻辑是,通过一个actino先到数据库中查到我们刚才的插入图片的用户,我们查出来,把这些,返回到用户信息显示页面。这也是模拟实际项目中用户信息是从数据库得到道理

我们先看一下我们的页面:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width,inittal-scale=1" />
		<title>用户信息</title>
		<script src="<%=basePath%>/resource/js/jquery-3.1.1.js" type="text/javascript" charset="utf-8"></script>
		<link rel="stylesheet" href="<%=basePath%>/resource/css/bootstrap.css" />
		<script src="<%=basePath%>/resource/js/bootstrap.js" type="text/javascript" charset="utf-8"></script>
	</head>
	<body>
		<div align="center" style="margin-top: 30px">
			<img src="<%=basePath%>${user.imgurl}" style="width: 50px;height: 50px;"/>
			<h1 style="color: #245269;">${user.userName}</h1>
			<h2 style="color: #245269;">${user.birth}</h2>
			<h2 style="color: #245269;">${user.sex}</h2>
			<h2 style="color: #245269;">${user.telphone}</h2>
		</div>
	</body>
</html>
页面很容易,这些属性的值是我们访问action得到的一个user对象中取出来的,看一下我们的action,通过给设置user的getter和setter的方法,我们就可以在页面值栈中取出来,所以我们页面是"${user.}"的格式的原因

package com.xuhang.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.RequestAware;
import org.omg.CORBA.Request;

import com.opensymphony.xwork2.ActionSupport;
import com.xuhang.bean.User;
import com.xuhang.service.UserService;

public class UserAction extends ActionSupport{
	
	
    
    private User user;
   
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	
	
	//得到用户的信息
	public String meInfo() throws Exception {
		UserService userService = new UserService();
		user = userService.getmeInfo();
		return SUCCESS;
	}
}

2)剩下的就是从数据中查出来了,我就简单把代码copy下来了,这些后面查找操作,结构和插入一张图片到数据库操作,本质是类似的

package com.xuhang.service;

import com.xuhang.bean.User;
import com.xuhang.dao.UserDAO;

public class UserService {
	UserDAO userDAO = new UserDAO();
	
	public User getmeInfo(){
		return userDAO.getmeInfo();
		
	}
}
package com.xuhang.dao;




import java.io.IOException;

import org.apache.ibatis.session.SqlSession;

import com.xuhang.bean.User;
import com.xuhang.util.DBUtil;



public class UserDAO {
	
	
	public User getmeInfo(){
		DBUtil dbUtil = new DBUtil();
		SqlSession sqlSession = null;
		User user = new User();
		try {
			sqlSession =dbUtil.getSqlSession();
			user = sqlSession.selectOne("MyUser.meInfo");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(sqlSession != null){
				sqlSession.close();
			}
		}
		return user;		
	}
	
}
<?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="MyUser">

  <resultMap type="com.xuhang.bean.User" id="User">
    <id column="id" jdbcType="INTEGER" property="id"/>
    <result column="userName" jdbcType="VARCHAR" property="userName"/>
    <result column="userpwd" jdbcType="VARCHAR" property="userpwd"/>
    <result column="birth" jdbcType="VARCHAR" property="birth"/>
    <result column="sex" jdbcType="CHAR" property="sex"/>
    <result column="telphone" jdbcType="VARCHAR" property="telphone"/>
    <result column="imgurl" jdbcType="VARCHAR" property="imgurl"/>
  </resultMap>

   
      <select id="meInfo" parameterType="com.xuhang.bean.User" resultMap="User">
      	select * from userInfo
      </select>
</mapper>
3.到这里我们大工就完成了,是不是很容易了,其实就是这么简单,看一下效果图







虽然鄙人,是简单完成了这个功能,但在下还是比较感觉我还是做的不够好,所以我也很希望各位大佬多多批评我,在这里我也想到了一些问题村路径到数据库里面是不是好备份等其他问题,在这里我衷心的希望大家多批评我,谢谢!



  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值