项目知识点记录

1.使用druid连接池 

使用properties配置文件:

driverClassName= com.mysql.cj.jdbc.Driver
url= jdbc:mysql://localhost:3306/book?useSSL=true&setUnicode=true&charsetEncoding=UTF-8&serverTimezone=GMT%2B8
username= root
password= 123456
#初始化链接数量
initialSize=5
#最大链接数
maxActive=10
#最大等待时间
maxWait=3000

工具类:

package com.util;import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;public class JDBCUtils {//定义成员变量private static DataSource ds = null;//定义静态代码块static {try {//加载配置文件Properties pro = new Properties();pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));//获取DataSourceds = DruidDataSourceFactory.createDataSource(pro);} catch (IOException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}}//获取链接public static Connection getConnection() throws SQLException{return ds.getConnection();}//释放资源public static void close(Statement stmt,Connection conn){if (stmt != null){try {stmt.close();} catch (SQLException throwables) {throwables.printStackTrace();}}if (conn != null){try {conn.close();} catch (SQLException throwables) {throwables.printStackTrace();}}}public static void close(ResultSet rs,Statement stmt,Connection conn){if (rs != null){try {rs.close();} catch (SQLException throwables) {throwables.printStackTrace();}}close(stmt,conn);}//获取链接池方法public static  DataSource getDataSource(){return ds;}
}

Dao接口: 

 dao实现类:

查询:

 //定义sqlString sql = "select * from user where username = ? and password = ?";
//执行sqlUser user1 = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), user.getUsername(), user.getPassword());

 增加:

 //定义sql
String sql ="insert into user values(null,?,?)";
//执行sql
int update = template.update(sql, user.getUsername(), user.getPassword());

删除:

 //定义sqlString sql = "delete from shopping where id = ?";//执行sqlint update = template.update(sql, id);

修改:

//定义sqlString sql ="update books set img = ? , name = ? , price = ? , classly = ? , detail = ? where id = ?";//执行sqlint update = template.update(sql, books.getImg(), books.getName(), books.getPrice(), books.getClassly(), books.getDetail(), books.getId());

package com.dao;import com.domain.Admin;
import com.domain.Books;
import com.domain.Shopping;
import com.domain.User;
import com.util.JDBCUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.TimeoutException;public class DaoImpl implements Dao {//使用JdbcTemplateprivate JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());//用户登录@Overridepublic User login(User user) {try {//定义sqlString sql = "select * from user where username = ? and password = ?";//执行sqlUser user1 = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), user.getUsername(), user.getPassword());//返回结果return user1;} catch (DataAccessException e) {e.printStackTrace();return null;}}//用户注册@Overridepublic int addUser(User user) {try {//定义sqlString sql ="insert into user values(null,?,?)";//执行sqlint update = template.update(sql, user.getUsername(), user.getPassword());return update;} catch (DataAccessException e) {e.printStackTrace();return 0;}}//遍历图书@Overridepublic List<Books> selectBooks(String classly) {//定义sqlString sql = "select * from books where classly = ?";//执行sqlList<Books> query = template.query(sql, new RowMapper<Books>() {@Overridepublic Books mapRow(ResultSet resultSet, int i) throws SQLException {Books b = new Books();b.setImg(resultSet.getString("img"));b.setName(resultSet.getString("name"));b.setPrice(resultSet.getInt("price"));b.setDetail(resultSet.getString("detail"));return b;}}, classly);return query;}//添加图书@Overridepublic int addBook(Books books) {try {//定义sqlString sql = "insert into books values(null,?,?,?,?,?)";//执行sqlint update = template.update(sql, books.getImg(),books.getName(), books.getPrice(),books.getClassly(), books.getDetail());//返回值return update;} catch (DataAccessException e) {e.printStackTrace();return 0;}}//查询图书详情@Overridepublic Books selectDetail(String name) {//定义sqlString sql ="select * from books where name = ?";//执行sqlBooks query = template.queryForObject(sql, new BeanPropertyRowMapper<Books>(Books.class), name);//返回return query;}//加入购物车@Overridepublic int addShopping(Shopping shopping) {try {//定义sqlString sql = "insert into shopping values(null,?,?,?,?,?)";int update = template.update(sql,shopping.getImg(), shopping.getUsername(), shopping.getName(), shopping.getNumber(), shopping.getPrice());//返回值return update;} catch (DataAccessException e) {e.printStackTrace();return 0;}}//遍历购物车@Overridepublic List<Shopping> selectShopping(String username) {//定义sqlString sql = "select * from shopping where username = ?";List<Shopping> query = template.query(sql, new RowMapper<Shopping>() {@Overridepublic Shopping mapRow(ResultSet resultSet, int i) throws SQLException {Shopping shopping = new Shopping();shopping.setId(resultSet.getInt("id"));shopping.setImg(resultSet.getString("img"));shopping.setName(resultSet.getString("name"));shopping.setNumber(resultSet.getInt("number"));shopping.setPrice(resultSet.getInt("price"));return shopping;}}, username);return query;}//删除购物车@Overridepublic int deleteShopping(int id) {//定义sqlString sql = "delete from shopping where id = ?";//执行sqlint update = template.update(sql, id);//返回执行结果return update;}//清空购物车@Overridepublic int deleteS(String username) {//定义sqlString sql = "delete from shopping where username = ?";//执行sqlint update = template.update(sql, username);//返回执行结果return update;}//管理员登录@Overridepublic Admin admin(Admin admin) {try {//定义sqlString sql = "select * from admin where username = ? and password = ?";//执行sqlAdmin admin1 = template.queryForObject(sql, new BeanPropertyRowMapper<Admin>(Admin.class), admin.getUsername(), admin.getPassword());return admin1;} catch (DataAccessException e) {e.printStackTrace();return null;}}//遍历图书@Overridepublic List<Books> BOOKS_LIST() {//定义sqlString sql ="select * from books";//执行sqlList<Books> query = template.query(sql, new RowMapper<Books>() {@Overridepublic Books mapRow(ResultSet resultSet, int i) throws SQLException {Books b = new Books();b.setId(resultSet.getInt("id"));b.setImg(resultSet.getString("img"));b.setName(resultSet.getString("name"));b.setPrice(resultSet.getInt("price"));b.setClassly(resultSet.getString("classly"));b.setDetail(resultSet.getString("detail"));return b;}});return query;}//删除图书@Overridepublic int deleteBooks(String name) {//定义sqlString sql = "delete from books where name = ?";//执行sqlint update = template.update(sql, name);//返回return update;}//修改图书@Overridepublic int modifyBook(Books books) {//定义sqlString sql ="update books set img = ? , name = ? , price = ? , classly = ? , detail = ? where id = ?";//执行sqlint update = template.update(sql, books.getImg(), books.getName(), books.getPrice(), books.getClassly(), books.getDetail(), books.getId());//返回return update;}//遍历用户@Overridepublic List<User> selectUser() {//定义sqlString sql ="select * from user";//执行sqlList<User> query = template.query(sql, new RowMapper<User>() {@Overridepublic User mapRow(ResultSet resultSet, int i) throws SQLException {User u = new User();u.setId(resultSet.getInt("id"));u.setUsername(resultSet.getString("username"));u.setPassword(resultSet.getString("password"));return u;}});return query;}//修改用户@Overridepublic int modifyUser(User user) {//定义sqlString sql = "update user set username = ? , password = ? where id = ?";//执行sqlint update = template.update(sql, user.getUsername(), user.getPassword(), user.getId());//返回return update;}@Overridepublic int deleteUser(int id) {//定义sqlString sql ="delete from user where id =?";//执行sqlint update = template.update(sql, id);return update;}
}

登录Servlet控制器:

package com.demo;import com.dao.Dao;
import com.dao.DaoImpl;
import com.domain.User;
import org.apache.commons.beanutils.BeanUtils;import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//设置编码格式request.setCharacterEncoding("utf-8");response.setContentType("text/html;charset=utf-8");//获取数据Map<String, String[]> map = request.getParameterMap();//封装数据User user = new User();try {BeanUtils.populate(user,map);} catch (IllegalAccessException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();}//调用daoDao dao = new DaoImpl();User login = dao.login(user);if (login != null){HttpSession session = request.getSession();session.setAttribute("username",user.getUsername());response.sendRedirect(request.getContextPath()+"/indexServlet?classly=1");}else {request.setAttribute("user","账号或密码错误");request.getRequestDispatcher("login.jsp").forward(request,response);}}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doPost(request, response);}
}

简单的过滤器实现:判断用户是否登录,登录就放行

package com.listener;import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;/*** 登录验证的过滤器*/
@WebFilter("/*")
public class LoginFilter implements Filter {public void destroy() {}public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {//强制转换HttpServletRequest request = (HttpServletRequest) req;//1.获取资源请求路径String uri = request.getRequestURI();//2.判断是否包含登录相关资源路径,要注意排除掉css/图片/js等资源if (uri.contains("/login.jsp") || uri.contains("/loginServlet")||uri.contains("/login2.jsp")||uri.contains("/login2Servlet") ||uri.contains("/css/") || uri.contains("/img/") ||uri.contains("adlogin.jsp") || uri.contains("/adLoginServlet")){//包含,用户就是想登录,放行chain.doFilter(req, resp);}else {//不包含,需要验证用户是否登录//3.从获取session中获取usernameObject username = request.getSession().getAttribute("username");if (username != null){//登录了,放行chain.doFilter(req,resp);}else {//没有登录,跳转登录页面request.setAttribute("user","您尚未登录,请登录");request.getRequestDispatcher("/login.jsp").forward(request,resp);}}//chain.doFilter(req, resp);}public void init(FilterConfig config) throws ServletException {}}

(2)项目Spring中用的aop事务的写法

 <!--加载事务管理器--><bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><!--加载数据源连接池--><property name="dataSource" ref="druidDataSource"/></bean><!--配置事务增强通知--><!--transaction-manager加载指定的事务管理器--><tx:advice id="txAdvice" transaction-manager="transactionManager"><!--事务规则列表--><tx:attributes><!--propagation定义动作的规则--><!--REQUIRED阻断操作--><!--NOT_SUPPORTED非阻断操作--><!--对新增数据操作的规则定义--><tx:method name="insert*" propagation="REQUIRED"/><tx:method name="add*" propagation="REQUIRED"/><!--对修改数据操作的规则定义--><tx:method name="update*" propagation="REQUIRED"/><tx:method name="edit*" propagation="REQUIRED"/><!--对删除数据操作的规则定义--><tx:method name="delete*" propagation="REQUIRED"/><!--对查询数据操作的规则定义--><tx:method name="get*" propagation="NOT_SUPPORTED"/><tx:method name="select*" propagation="NOT_SUPPORTED"/><tx:method name="query*" propagation="NOT_SUPPORTED"/></tx:attributes></tx:advice><!--托管通知工具类--><bean name="advice" class="com.example.meal_ordering_system.util.AdviceUtil"/><!--切面的配置--><aop:config><!--切面定义在Service层--><aop:pointcut id="pointCut" expression="execution(* com.example.meal_ordering_system.service..*(..))"/><!--将事务增强通知与切面进行绑定--><aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut"/><!--切面织入--><aop:aspect ref="advice"><aop:before method="before" pointcut-ref="pointCut"/><aop:after method="after" pointcut-ref="pointCut"/><aop:around method="around" pointcut-ref="pointCut"/><aop:after-throwing method="exception" pointcut-ref="pointCut"/></aop:aspect></aop:config>

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/66977.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

opencv实战项目 手势识别-手势音量控制(opencv)

本项目是使用了谷歌开源的框架mediapipe&#xff0c;里面有非常多的模型提供给我们使用&#xff0c;例如面部检测&#xff0c;身体检测&#xff0c;手部检测等。 手势识别系列文章 1.opencv实现手部追踪&#xff08;定位手部关键点&#xff09; 2.opencv实战项目 实现手势跟踪…

普通索引和唯一索引,应该怎么选择(已经那个changebuffer - 和你这个线程连接池)

普通索引和唯一索引是什么 普通索引和唯一索引都是数据库中常用的索引类型&#xff0c;它们的主要区别在于索引列的值是否允许重复 普通索引允许索引列的值重复&#xff0c;也就是说&#xff0c;如果多个记录在索引列中具有相同的值&#xff0c;那么这些记录仍然可以通过普通…

【12】Git工具 协同工作平台使用教程 Gitee使用指南 腾讯工蜂使用指南【Gitee】【腾讯工蜂】【Git】

tips&#xff1a;少量的git安装和使用教程&#xff0c;更多讲快速使用上手Gitee和工蜂平台 一、准备工作 1、下载git Git - Downloads (git-scm.com) 找到对应操作系统&#xff0c;对应版本&#xff0c;对应的位数 下载后根据需求自己安装&#xff0c;然后用git --version验…

uniapp 微信小程序 订阅消息

第一步&#xff0c;需要先去小程序官方挑选一下订阅模板拿到模板id 订阅按钮在头部导航上&#xff0c;所以 <u-navbar :bgColor"bgColor"><view class"u-nav-slot" slot"left" click"goSubscribe"><image :src"g…

74、75、76——tomcat项目实战

tomcat项目实战 tomcat 依赖 java运行环境,必须要有jre , 选择 jdk1.8 JvmPertest 千万不能用 kyj易捷支付 项目机器 选择 一台机器 ,安装jdk1.8的机器下载tomcat的包 上传到机器,解压tomcattomcat文件 bin文件夹: 启动文件 堆栈配置文件 catalina.sh JAVA_OPTS="-Xm…

【openwrt学习笔记】dnsmasq源码阅读

目录 一、DHCP(Dynamic Host Configuration Protocol)1.1 前置知识1.2 参考链接1.3 IP地址分配代码分析rfc2131.cdhcp-common.cdhcp.c 1.4 几个小问题1.4.1 连续IP模式&#xff08;sequential_ip&#xff09;1.4.2 重新连接使用IP地址1.4.3 续约租期1.4.4 不同的MAC地址分配到相…

深入浅出 栈和队列(附加循环队列、双端队列)

栈和队列 一、栈 概念与特性二、Stack 集合类及模拟实现1、Java集合中的 Stack2、Stack 模拟实现 三、栈、虚拟机栈、栈帧有什么区别&#xff1f;四、队列 概念与特性五、Queue集合类及模拟实现1、Queue的底层结构&#xff08;1&#xff09;顺序结构&#xff08;2&#xff09;链…

考公-判断推理-组合排列

例题 例题 例题 代入法 例题 排除法 例题

不同路径——力扣62

文章目录 题目描述解法一 动态规划题目描述 解法一 动态规划 int uniquePaths(int m, int n) {vector<vector

国企的大数据岗位方向的分析

现如今大数据已无所不在&#xff0c;并且正被越来越广泛的被应用到历史、政治、科学、经济、商业甚至渗透到我们生活的方方面面中&#xff0c;获取的渠道也越来越便利。 今天我们就来聊一聊“大屏应用”&#xff0c;说到大屏就一定要聊到数据可视化&#xff0c;现如今&#xf…

【Maven】常用命令、插件管理、私服nexus

【Maven】常用命令、插件管理、私服nexus 常用命令 插件管理 私服nexus Nexus3 配置私服 项目pom中的配置 发布时区分正式版、快照版 常用命令 Maven提供了一系列常用命令&#xff0c;用于构建、测试和管理项目。以下是一些常用的Maven命令示例&#xff1a; mvn clean:…

Redis_持久化(AOF、RDB)

6. Redis AOF 6.1 简介 目前&#xff0c;redis的持久化主要应用AOF&#xff08;Append Only File&#xff09;和RDF两大机制&#xff0c;AOF以日志的形式来记录每个写操作&#xff08;增量保存&#xff09;&#xff0c;将redis执行过的所有指令全部安全记录下来&#xff08;读…