Mvc+jsp+servlet实现从数据库图片的切换和添加
此次采用的是Mvc模式+jsp+servlet+C3p0来实现的,在实训中也算是唯一拿的出手的了,希望能对你有所帮助.,运行效果图如下:
点击图片就能切换背景图片,也可以进行添加.
思路:
1.新建一个数据表(imges表)用来存放图片的:
2.把所需的jar添加进去, c3p0配置好,在搭建Mvc框架模型,dao(层), domain(实体类),service(层),servlet(层),util(工具类)层, 拦截器(防止传参数时出现乱码)
3.搭建好后,先新键一个jsp运行下,运行成功则表时Tomcat没问题
4.在domain实体层中写imges表的实体类,实体类就略过了,
5.在写dao层之前先在工具类层中建一个DataSoureceUtils的类:
private static DataSource dataSource = new ComboPooledDataSource();
private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
public static DataSource getDataSource() {
return dataSource;
}
/**
* 当DBUtils需要手动控制事务时,调用该方法获得一个连接
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
Connection con = tl.get();
if (con == null) {
con = dataSource.getConnection();
tl.set(con);
}
return con;
}
/**
* 开启事务
* @throws SQLException
*/
public static void startTransaction() throws SQLException {
Connection con = getConnection();
if (con != null)
con.setAutoCommit(false);
}
/**
* 从ThreadLocal中释放并且关闭Connection,并结束事务
* @throws SQLException
*/
public static void releaseAndCloseConnection() throws SQLException {
Connection con = getConnection();
if (con != null) {
con.commit();
tl.remove();
con.close();
}
}
/**
* 事务回滚
* @throws SQLException
*/
public static void rollback() throws SQLException {
Connection con = getConnection();
if (con != null) {
con.rollback();
}
}
先在就可以安心的写dao层和serice层了:
在dao层新建一个类,方便从数据库中得到数据:
private QueryRunner runner = new QueryRunner(DataSoureceUtils.getDataSource());
//从数据库读取图片
public imgurl imgurls(int id)throws SQLException{
String sql = "select * from imges where id=?";
return runner.query(sql, new BeanHandler<imgurl>(imgurl.class),id);
}
//获取数据库图片的数量
public List<imgurl> Allimgurl() throws SQLException{
String sql ="select * from imges";
List list = (List) runner.query(sql, new BeanListHandler(imgurl.class));
return list;
}
//向数据库添加图片
public void addFileImg(imgurl img)throws SQLException{
String sql="insert into imges set url=?,verse=?";
System.out.println("dao"+img.getUrl()+" "+img.getVerse());
int num = runner.update(sql, new Object[]{img.getUrl(), img.getVerse()});
if(num > 0) {
System.out.println("Yes");
}else {
System.out.println("No");
}
}
接下来在service层中新键一个类,方便serlvet的调用:
private 你的dao层类名 dao = new 你的dao层类名();
//图片获取
public imgurl getImgUrl(int id) {
try {
return dao.imgurls(id);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
//获取所有图片方便统计图片总数
public List<imgurl> Allimages(){
try {
return dao.Allimgurl();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
//添加图片到数据库
public void AddImgUrl(imgurl img) {
try {
System.out.println(img.getUrl());
dao.addFileImg(img);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
6.写完service层后,就是写servlet层了
查询所有图片的servlet的servlet:,最后要运行的是这个servlet而不是jsp文件
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
你serice层的类 service = new 你serice层的类();
//从jsp中得到数据
List<imgurl> list = service.Allimages();
String strid = request.getParameter("id");
imgurl img = new imgurl();
HttpSession session = request.getSession();
//从jsp中传来得strid不为空的化,则图片不随机,选择指定图片为背景图片
if(strid != null) {
int id = Integer.parseInt(strid);
img = service.getImgUrl(id);
}else {
//如果strid为空,那么就随机抽取一张图片为背景图片
Random r = new Random();
//随机长度,在list的范围内
int id = r.nextInt(list.size());
System.out.println(id);
//list是从0开始所以要加1
img = service.getImgUrl(id+1);
//如果img为空拿么就是第一张图片
if(img == null) {
img = service.getImgUrl(1);
}
}
//利用session存值
session.setAttribute("img", img.getUrl());
session.setAttribute("verse", img.getVerse());
session.setAttribute("imgs", list);
//将数据传给jsp
request.getRequestDispatcher("jsp的路径").forward(request,response);
}
添加图片的servlet, 需注意的是要的到jsp中的值需要判断它不是文件组件才能得到:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
imgurl img = new imgurl();
OnlineService service = new OnlineService();
//文件上传过程
DiskFileItemFactory diff = new DiskFileItemFactory();
//设置文件上传的位置
diff.setRepository(new File(this.getServletContext().getRealPath("/temp")));
//设置文件缓存大小
diff.setSizeThreshold(1024*1024*10);
//创建一个上传组
ServletFileUpload upload = new ServletFileUpload(diff);
upload.setHeaderEncoding("utf-8");
List<FileItem> items = null;
try {
items=upload.parseRequest(request);
//遍历所有的FileItems
for(FileItem item:items) {
if(item.isFormField()) {
//得到jsp中传来的值
String fileName = item.getFieldName();
String value=item.getString("utf-8");
System.out.println(value);
img.setVerse(value);
}else {
//获取上传文件真实文件名
String fileName = item.getName();
String urls = "你保存图片的路径";
String imgurl_parent = "你图片存放的路径"+fileName;
img.setUrl(imgurl_parent);
IOUtils.copy(item.getInputStream(), new FileOutputStream(new File(urls)));
item.delete();
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
service.AddImgUrl(img);
response.sendRedirect("./getimgUrlServlet");
}
}
7.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta charset="UTF-8">
<title>用户登录</title>
<link href="${pageContext.request.contextPath}/client/css/Style.css" rel="stylesheet" type="text/css">
</head>
<script>
function openlogin() {
document.getElementById('logins').style.display='block';
}
/*超链接关闭登陆弹窗*/
function closelogin() {
document.getElementById('logins').style.display='none';
}
function openforget(){
document.getElementById("forget").style.display='block';
}
function closeforget() {
document.getElementById('forget').style.display='none';
}
function openfile(){
document.getElementById("fileUP").style.display='block';
}
function closefile() {
document.getElementById('fileUP').style.display='none';
}
</script>
<body>
<div id="box">
<img src="./${img}" class="img"/>
<div id="formlogin">
<form action="./loginServlet" method="post">
<h1>用户登录</h2>
<a class="zu">账号 :</a><input type="text" class="input" name="user" value="${name}"/> <br />
<br />
<a class="zu">密码 :</a><input type="password" class="input" name="pwd" /> <br /><br />
<a class="zu">验证 :</a><input type="text" class="verify" name="verify" />
<img src="./CheckServlet" class="verifycode" />
<br />
<br />
<input type="submit" class="login" value="登录">
<br />
<a class="ce" onclick="openlogin()">注册</a>
<br />
<a class="ce" onclick="openforget()">忘记密码</a>
</form>
</div>
<h2>${verse}</h2>
<div id="logins">
<form action="./EnrollServlet" method="post">
<h1>用户注册</h1>
<p>用户账号: <input type="text" class="input" name="user"></p>
<p>用户密码: <input type="password" class="input" name="pwd"></p>
<p>确认密码: <input type="password" class="input" name="pwd2"></p>
<p>你的邮箱: <input type="text" class="input" name="email" /></p>
<p>输入验证: <input type="text" class="ver" name="verify"/>
<img src="./CheckServlet" class="verifycode" /></p>
<p>你的身份: <select name="category" class="category">
<option value="" selected="selected">----</option>
<option value="1">学生</option>
<option value="2">老师</option>
</select></p>
<input type="submit" class="submit" value="登陆">
<input type="reset" class="reset" value="重置">
<a class="exit" href="javascript:closelogin()" onclick="closelogin()">X</a>
</form>
</div>
<div id="forget">
<form action="./forgetServlet" method="post">
<h1>找回密码</h1>
<p>用户账号: <input type="text" class="input" name="user"/></p>
<p>用户密码: <input type="password" class="input" name="pwd"/></p>
<p>确认密码: <input type="password" class="input" name="pwd1"/></p>
<p>输入验证: <input type="text" class="ver" name="verify"/>
<img src="./CheckServlet" class="verifycode"></p>
<input type="submit" class="submit" value="提交"/>
<input type="reset" class="reset" value="重置" />
<a class="exit" href="javascript:closeforget()" onclick="closeforget()">X</a>
</form>
</div>
<a class="jia" onclick="openfile()">+</a>
<a href="./getimgUrlServlet" class="qian" >换一张!!</a>
<div id="fileUP">
<form action="./FileUpServlet" method="post" enctype="multipart/form-data">
<h4>图片上传</h4>
<p> 描述: <input type="text" name="dess" />
图片: <input type="file" name="myfile">
<input type="submit" value="上传" />
</p>
</form>
<a class="exit" href="javascript:closefile()" onclick="closefile()">X</a>
<div id="der">
<c:forEach items="${imgs}" var="i">
<a href="./getimgUrlServlet?id=${i.id}" class="aver">
<img src="./${i.url}" class="allimg"/>
<p> ${i.verse }</p>
</a>
</c:forEach>
</div>
</div>
</div>
</body>
</html>
css
body{padding:0px; margin:0px;width:100%;position:relative;}
#box{
width:100%;
height:100%;
z-index:1;
}
#box .img{width:100%; height:100%;}
#box #formlogin{
width:400px;
height:100%;
top:0%;
background-color:rgba(0,0,0,0.7);
position:absolute;
}
#box #formlogin h1{
margin:100px 25%;
color:#ffffff;
font-style:italic;
font-size:40px;
}
#box #formlogin a.zu{
color:#ffffff;
margin-left:30px;
font-size:25px;
}
#box #formlogin .input{
border:none;
border-bottom:1px solid #ffffff;
background-color:rgba(0,0,0,0);
color:#ffffff;
height:32px;
width:240px;
font-size:20px;
font-weight:bold;
margin-left:10px;
outline:none;
text-indent:10px;
}
#box #formlogin .verify{
margin-left:10px;
border:none;
border-bottom:1px solid #ffffff;
background-color:rgba(0,0,0,0);
height:32px;
width:150px;
outline:none;
color:#ffffff;
text-indent:10px;
font-size:20px;
font-weight:bold;
}
#box #formlogin .login{
width:200px;
height:40px;
font-size:20px;
margin-left:22%;
}
#box #formlogin .login:hover{
background-color:yellow;
font-weight:bold;
color:red;
}
#box #formlogin a.ce{
margin-left:79%;
color:#ffffff;
text-decoration:none;
font-size:20px;
}
#box #formlogin a.ce:hover{
color:red;
font-weight:bold;
}
h2{
color:#ffffff;
font-size:15px;
top:0%;
left:445px;
font-style:italic;
position:absolute;
font-family:"微软雅黑";
}
h2:hover{
color:yellow;
font-weight:bold;
font-size:20px;
}
#box #logins{
z-index:3;
display:none;
font-size:20px;
position:absolute;
left:50%;
top:45%;
width:600px;
height:450px;
box-shadow:2px 2px 91px 6px #000;
margin-left:-300px;
margin-top:-225px;
border:1px solid #888;
background-color:#ffffff;
text-align:center;
}
.exit{
position:absolute;
top:1%;
left:96%;
text-decoration:none;
}
.exit:hover{
color:red;
transform:rotate(90deg);
}
h1{
font-style:italic;
}
.input{
height:30px;
width:255px;
font-size:22px;
}
.ver{
weight:120px;
height:30px;
}
.verifycode{
margin-bottom:-12px;
border-radius: 40%;
box-shadow:2px 2px 11px 1px #000;
}
.submit{
height:30px;
width:180px;
}
#box #forget{
z-index:3;
display:none;
font-size:20px;
position:absolute;
left:50%;
top:45%;
width:600px;
height:350px;
box-shadow:2px 2px 91px 6px #000;
margin-left:-300px;
margin-top:-175px;
border:1px solid #888;
background-color:#ffffff;
text-align:center;
}
.reset{
width:60px;
height:30px;
}
.jia{
position:absolute;
top:0px;
left:402px;
width: 40px;
height: 40px;
border-radius: 100px;
border: 1px steelblue solid;
text-align: center;
font-size: 27px;
color: steelblue;
}
.jia:hover{
color:white;border:2px white solid;
}
.qian{
position:absolute;
top:43px;
left:402px;
color:yellow;
font-size:16px;
}
.qian:hover{
color:red;
}
#fileUP{
z-index:3;
display:none;
font-size:20px;
position:absolute;
left:50%;
top:45%;
width:760px;
height:500px;
box-shadow:2px 2px 91px 6px #000;
margin-left:-300px;
margin-top:-175px;
border:1px solid #888;
background-color:#ffffff;
text-align:center;
}
#fileUP #der{
width:760px;
height:373px;
overflow:scroll;
}
#fileUP #der a.aver{
float:left;
width:160px;
height:160px;
padding-left:15px;
padding-bottom:40px;
}
#fileUP #der a.aver p{
padding-top:0;
font-size:13px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
#fileUP #der a .allimg:hover{
border:1px solid red;
}
#fileUP #der a .allimg{
width:100%;
height:100%;
}
然后就可以了
d