SpringMVC 03 - 小练习

目标:1、实现注册功能 - 注册提交头像文件,-表单校验 --(1.信息需要填充完整才可以提交。2.密码为6-12位字符。3.密码与确认密码一致。)2、实现文件下载功能 - 文件下载记录下载次数。

步骤:

一、创建相关数据库表

                                    

2、搭建相关环境

  导入相关jar包 -- 注意 需要额外导入     用于处理文件上传与下载。

// 数据库属性文件
jdbc.driver=com.mysql.jdbc.Driver // 驱动名称
jdbc.url = jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=UTF-8 
jdbc.username = root
jdbc.password = 密码
// web.xml 文件 配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee                       
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
	<!-- 上下文参数 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
	<!-- 监听器 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- 前端控制器 -->
	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springmvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	
	<!-- 过滤器 设置字符编码 -->
	<filter>
		<filter-name>filter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>utf-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>filter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>
// applicationContext.xml文件  spring
<?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:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd"
	default-autowire="byName">
	<!-- 扫描注解 -->
	<context:component-scan base-package="com.yyl.service.impl"></context:component-scan>
	<!-- 扫描属性 -->
	<context:property-placeholder location="classpath:db.properties" />
	<!-- 数据源 -->
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="${jdbc.url}"></property>
		<property name="username" value="${jdbc.username}"></property>
		<property name="password" value="${jdbc.password}"></property>
	</bean>
	<!-- factory -->
	<bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"></property>
		<property name="typeAliasesPackage" value="com.yyl.pojo"></property>
	</bean>
	<!-- mapper -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.yyl.mapper"></property>
		<property name="sqlSessionFactoryBeanName" value="factory"></property>
	</bean>
	<!-- 事务管理器 -->
	<bean id="TxManage"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
			<property name="dataSource" ref="dataSource"></property>
		</bean>
	<!-- 声明事务 -->
	<tx:advice id="mytx" transaction-manager="TxManage">
		<tx:attributes>
			<tx:method name="ins*" />
			<tx:method name="del*" />
			<tx:method name="upd*" />
			<tx:method name="*" read-only="true" />
		</tx:attributes>
	</tx:advice>
	<!-- 配置AOP -->
	<aop:config>
		<aop:pointcut expression="execution(* com.yyl.service.impl.*.*(..))"
			id="mypoint" />
		<aop:advisor advice-ref="mytx" pointcut-ref="mypoint" />
	</aop:config>
	<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
</beans>
// springmvc.xml 文件 springmvc 环境
<?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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
		http://www.springframework.org/schema/mvc/spring-mvc.xsd">
	<!-- 扫描注解 -->
	<context:component-scan base-package="com.yyl.controller"></context:component-scan>
	<!-- 注册驱动 -->
	<mvc:annotation-driven></mvc:annotation-driven>
	<!-- 静态资源 -->
	
	<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
	<mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
	<mvc:resources location="/images/" mapping="/images/**"></mvc:resources>
	// 处理文件上传
	<bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	
	</bean>
</beans>

2、创建实体类

             

3、创建mapper接口

package com.yyl.mapper;
import org.apache.ibatis.annotations.Insert;
import com.yyl.pojo.User;
    // userMapper 处理注册相关信息 
public interface UserMapper {
        // 将注册信息插入表中
	@Insert("INSERT INTO register values(default,#{name},#{password},#{photo})")
	public boolean insUser(User u);
	
}
package com.yyl.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.yyl.pojo.Files;
  // 处理文件下载相关数据库操作
public interface FilesMapper {
    // 查询所有文件信息
	@Select("select * from files")
	List<Files> selAll();
    // 更新文件下载次数
	@Update("update files SET counts = counts+1 where id = #{0}")
	int updCount(int id);
}

4、创建service类

package com.yyl.service.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.yyl.mapper.UserMapper;
import com.yyl.pojo.User;
import com.yyl.service.UserService;
    // 用户注册service 
@Service  // 自动注册spring容器
public class UserServiceImpl implements UserService{
	@Resource  // 依赖注入
	private UserMapper mapper;
     // 调用数据库查询
	 public boolean insService(User u) {
		return mapper.insUser(u);
	}
}
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.yyl.mapper.FilesMapper;
import com.yyl.pojo.Files;
import com.yyl.service.FilesService;
  // 文件下载service
@Service
public class FilesServiceImpl implements FilesService{
	@Resource
	private FilesMapper mapper;
    // 查询所有文件信息
	@Override
	public List<Files> selAllFile() {
		return mapper.selAll();
	}
    //更新文件下载次数
	@Override
	public int updCount(int id) {
		return mapper.updCount(id);
	}

}

5、创建controller 类

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import com.yyl.pojo.User;
import com.yyl.service.UserService;
// 用户注册
@Controller
public class UserController {
	@Resource
	private UserService userServiceImpl;
	@RequestMapping("register")
	public String reg(String name, String password, MultipartFile file, HttpServletRequest req) {
		User u = new User();
		u.setName(name);
		u.setPassword(password);
		String filename = file.getOriginalFilename();
		String substring = filename.substring(filename.lastIndexOf("."));
		if (substring.equals(".png")) { // 文件必须为.png结尾的图像
			String uuid = UUID.randomUUID().toString(); //防止文件重名
			String path = req.getServletContext().getRealPath("images") + "/" + uuid + substring;
			try {
				FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path));
			} catch (IOException e) {
				e.printStackTrace();
			}
			u.setPhoto(path);
			boolean flag = userServiceImpl.insService(u);
			if (flag)
				return "redirect:/show";
			else
				return "error.jsp";
		} else {
			return "error.jsp";
		}
	}
}
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.yyl.pojo.Files;
import com.yyl.service.FilesService;
// 文件下载
@Controller
public class FileController {
	@Resource
	private FilesService filesServiceImpl;
	
	@RequestMapping("show")  // 显示所有文件
	public String showFile(HttpServletRequest req){
		List<Files> allFile = filesServiceImpl.selAllFile();
		//System.out.println(allFile);
		req.setAttribute("files", allFile);
		return "main.jsp";	
	}
	@RequestMapping("down") // 下载文件
	public void downFile(int id,HttpServletRequest req,String filename,HttpServletResponse resp) throws IOException{
		filesServiceImpl.updCount(id);
		resp.setHeader("Content-Disposition", "attachment;filename="+filename); // 必须设    
                                                               //置头文件格式,才会实现下载
		ServletOutputStream os = resp.getOutputStream();
		File file = new File(req.getServletContext().getRealPath("files"),filename);
		byte[] bs = FileUtils.readFileToByteArray(file);
		os.write(bs);
		os.flush();
		os.close();
	}
}

6、创建相关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>
<script type="text/javascript" src="js/jquery-1.7.2.js"></script>
<script type="text/javascript">
	$(function(){
		var name=false;
		var pwd=false;
		var epwd=false;
		// 验证用户名
		$(":text:eq(0)").blur(function(){
			if($(this).val()==""){
				$(this).next().css("color","red").html("×");
				name = false;
			}else{
				$(this).next().css("color","green").html("√");
				name = true;
			}	
		})
		// 验证密码
		$(":password:eq(0)").blur(function(){
			if(!$(this).val().match(/^\w{6,12}$/)){
				$(this).next().css("color","red").html("×");
				pwd = false;
			}else{
				$(this).next().css("color","green").html("√");
				pwd = true;
			}	
		})
		// 确认密码
		$(":password:eq(1)").blur(function(){
			if($(this).val()==""||$(this).val()!=$(":password:eq(0)").val()){
				$(this).next().css("color","red").html("×");
				epwd = false;
			}else{
				$(this).next().css("color","green").html("√");
				epwd = true;
			}	
		})
		// 所有信息不为空验证
		$(":submit").click(function(){
			if(!(name && pwd && epwd)){
				alert("请将信息完善!");
				return false;
			}
		})
		
	})
	

</script>
</head>
<body>
	<form action="register" method="post" enctype="multipart/form-data">
	用户名:<input type="text" name="name" /><span></span><br>
	     密码:<input type="password" name="password" /><span></span><br>
      确认密码:<input type="password" name="epassword" /><span></span><br>
	     头像:<input type="file" name="file" /><span></span><br>
	     <input type="submit" value="提交" />
	</form>
</body>
</html>
<%@ 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>
<script type="text/javascript" src="js/jquery-1.7.2.js"></script>
<script type="text/javascript">
	$(function() {
		$("a").click(function() {
			var $td = $(this).parent().prev();
			$td.html(parseInt($td.html()) + 1);
		});
	})
</script>
</head>
<body>
	<table border="1px">
		<tr>
			<td>编号</td>
			<td>文件名</td>
			<td>下载次数</td>
			<td>是否下载</td>
		</tr>
		<c:forEach items="${files}" var="file">
			<tr>
				<td>${file.id}</td>
				<td>${file.filename}</td>
				<td>${file.counts}</td>
				<td><a href="down?id=${file.id}&filename=${file.filename}">下载</a></td>
			</tr>
		</c:forEach>
	</table>
</body>
</html>

未解决: 在点击下载后,如果取消下载,文件下载次数任然会加一。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值