版权声明:未经本人同意,不得私自转载 https://blog.csdn.net/weixin_41866744/article/details/88122515
环境搭建:
web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <!-- 上下文参数 --> <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> <!-- SpringMVC前端控制器 --> <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>encoding</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> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
applicationContext.xml:
<?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.tao.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="${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> <!-- SqlSessionFactory --> <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="typeAliasesPackage" value="com.tao.pojo"></property> </bean> <!-- 扫描器 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.tao.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="txAdvice" 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.tao.service.impl.*.*(..))" id="mypoint"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="mypoint"/> </aop:config> </beans>
db.properties:
jdbc.driver=com.mysql.jdbc.Driver jdbc.url = jdbc:mysql://localhost:3306/ssm jdbc.username = root jdbc.password = root
log4j.properties:
log4j.rootCategory=ERROR, CONSOLE ,LOGFILE log4j.logger.com.tao.mapper=DEBUG log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%C %d{YYYY-MM-dd hh:mm:ss} %m %n log4j.appender.LOGFILE=org.apache.log4j.FileAppender log4j.appender.LOGFILE.File=MyBatis.log log4j.appender.LOGFILE.Append=true log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout log4j.appender.LOGFILE.layout.ConversionPattern=%C %m %L %n
springmvc.xml:
<?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.tao.controller"></context:component-scan> <!-- 注解驱动 --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 静态资源 --> <mvc:resources location="/js/" mapping="/js/**"></mvc:resources> <mvc:resources location="/images/" mapping="/images/**"></mvc:resources> <mvc:resources location="/files/" mapping="/files/**"></mvc:resources> <!-- Mutilpart解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean> </beans>
实体:
package com.tao.pojo; public class Files { private int id; private String name; private int count; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } }
package com.tao.pojo; public class Users { private int id; private String username; private String password; private String photo; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPhoto() { return photo; } public void setPhoto(String photo) { this.photo = photo; } }
package com.tao.pojo; public class Users { private int id; private String username; private String password; private String photo; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPhoto() { return photo; } public void setPhoto(String photo) { this.photo = photo; } }
数据层mapper:
package com.bjsxt.mapper; import java.util.List; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import com.bjsxt.pojo.Files; public interface FilesMapper { @Select("select * from files") List<Files> selAll(); @Update("update files set count=count+1 where id=#{0}") int updCountById(int id); }
package com.bjsxt.mapper; import org.apache.ibatis.annotations.Insert; import com.bjsxt.pojo.Users; public interface UsersMapper { @Insert("insert into users values (default,#{username},#{password},#{photo})") int insUsers(Users users); }
业务层及其实现类:
package com.tao.service; import java.util.List; import com.tao.pojo.Files; import com.tao.pojo.Users; public interface FilesService { /** * 显示全部 * @return */ List<Files> show(); /** * 根据id修改资料下载次数 * @param id * @return */ int updCount(int id,Users users,String name); }
package com.tao.service; import com.tao.pojo.Users; public interface UsersService { int insRegister(Users users); }
package com.tao.service.impl; import java.util.List; import javax.annotation.Resource; import org.apache.log4j.Logger; import org.springframework.stereotype.Service; import com.tao.mapper.FilesMapper; import com.tao.pojo.Files; import com.tao.pojo.Users; import com.tao.service.FilesService; @Service public class FilesServiceImpl implements FilesService { @Resource private FilesMapper filesMapper; @Override public List<Files> show() { return filesMapper.selAll(); } @Override public int updCount(int id, Users users, String name) { Logger logger = Logger.getLogger(FilesServiceImpl.class); logger.info(users.getUsername()+"下载了"+name); return filesMapper.updCountById(id); } }
package com.tao.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.tao.mapper.UsersMapper; import com.tao.pojo.Users; import com.tao.service.UsersService; @Service public class UsersServiceImpl implements UsersService{ @Resource private UsersMapper usersMapper; @Override public int insRegister(Users users) { return usersMapper.insUsers(users); } }
controller:
package com.tao.controller; import java.io.File; import java.io.IOException; 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.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.tao.pojo.Users; import com.tao.service.FilesService; @Controller public class FilesController { @Resource private FilesService filesServiceImpl; @RequestMapping("show") public String show(Model model){ model.addAttribute("list", filesServiceImpl.show()); return "/main.jsp"; } @RequestMapping("download") public void download(int id,String name,HttpServletResponse res,HttpServletRequest req) throws IOException{ filesServiceImpl.updCount(id,(Users)req.getSession().getAttribute("user"),name); res.setHeader("Content-Disposition", "attachment;filename="+name); ServletOutputStream os = res.getOutputStream(); File file = new File(req.getServletContext().getRealPath("files"),name); os.write(FileUtils.readFileToByteArray(file)); os.flush(); os.close(); } }
package com.tao.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.tao.pojo.Users; import com.tao.service.UsersService; @Controller public class UsersController { @Resource private UsersService usersServiceImpl; @RequestMapping("register") public String register(Users users,MultipartFile file,HttpServletRequest req){ String fileName = UUID.randomUUID().toString()+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); String path = req.getServletContext().getRealPath("images")+"/"+fileName; try { FileUtils.copyInputStreamToFile(file.getInputStream(), new File(path)); } catch (IOException e) { e.printStackTrace(); } //只能取到webapps文件夹内容 users.setPhoto(fileName); int index = usersServiceImpl.insRegister(users); if(index>0){ req.getSession().setAttribute("user", users); return "redirect:/show"; }else{ return "redirect:/register.jsp"; } } }
前台页面: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> <script type="text/javascript" src="js/jquery-1.7.2.js"></script> <script type="text/javascript"> $(function(){ var username = false; var password = false; var passwordSure = false; //用户名的验证 $(":text:eq(0)").blur(function(){ if($(this).val()==""){ $(this).next().css("color","red").html("X"); username = false; }else{ $(this).next().css("color","green").html("√"); username = true; } }); //确认密码 $(":password:eq(1)").blur(function(){ if($(this).val()==""||$(this).val()!=$(":password:eq(0)").val()){ $(this).next().css("color","red").html("X"); passwordSure = false; }else{ $(this).next().css("color","green").html("√"); passwordSure = true; } }); $(":submit").click(function(){ if(username==false||password==false||passwordSure==false||$(":file").val()==""){ alert("请添加完整信息"); return false; } }); }); </script> </head> <body> <form action="register" method="post" enctype="multipart/form-data"> 用户名:<input type="text" name="username"/><span></span><br/> 密码:<input type="password" name="password"/><span></span><br/> 确认密码:<input type="password" name="passwordSure"/><span></span><br/> 头像:<input type="file" name="file"/><br/> <input type="submit" value="注册"/> </form> </body> </html>
main.jsp:
<%@ 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(){ //parent() 父标签 //prev() 前一个兄弟标签 //jquery中规范,对象名以$开头 var $td =$(this).parent().prev(); //html()返回值字符串 $td.html(parseInt($td.html())+1); }); }) </script> </head> <body> <table border="1"> <tr> <td>资料名称</td> <td>下载次数</td> <td>操作</td> </tr> <c:forEach items="${list }" var="file"> <tr> <td>${file.name }</td> <td>${file.count }</td> <td><a href="download?id=${file.id }&name=${file.name}">下载</a></td> </tr> </c:forEach> </table> </body> </html>