//json格式数据
@RequestMapping("/save3")
@ResponseBody
public String save3() throws IOException {
role role=new role();
role.setRoleName("zhanglaosan");//中文的话会有乱码需要处理一下
role.setId(22);
role.setRoleDesc("hehehehe");
//使用json工具 记得导包!!!
ObjectMapper objectMapper=new ObjectMapper();
String json = objectMapper.writeValueAsString(role);
return json;
}
//json格式数据
@RequestMapping("/save4")
@ResponseBody
public String save4() throws IOException {
role role=new role();
role.setRoleName("zhanglaosan");//中文的话会有乱码需要处理一下
//@RequestMapping(value = "/select",produces = "text/html;charset=UTF-8")处理响应给页面的乱码处理
role.setId(22);
role.setRoleDesc("hehehehe");
return role;
}
//spring-mvc的xml文件配置
<!--处理器映射器 返回json格式给页面-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</list>
</property>
</bean>
//手动配置比较繁琐可直接配置
<!--配置mvc的注解驱动 可以自动转json格式 回写数据给页面-->
<mvc:annotation-driven></mvc:annotation-driven>
1.页面的跳转
2.回写数据
直接返回字符串
返回对象or集合还有json格式的数据
//http://localhost:8080/ssm6/role/save5_1?name=lisi&&age=45
@RequestMapping("/save5_1")
@ResponseBody
//对应的参数要和url地址一样 不一样要加注解 @RequestParam
public void save5_1(String name,int age) {
System.out.println(name+"====="+age);
}
@RequestMapping("/save5")
@ResponseBody
public void save5(role role) throws IOException {
System.out.println(role);
}
//jsp页面 通过ajax发送请求给后台
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>ajax请求</title>
<script src="${pageContext.request.contextPath}/js/jquery.min.js"></script>
<script >
var usersList =new Array();
usersList.push({id:12,roleName:"lisi"});
usersList.push({id:12,roleName:"lisi2"})
$.ajax({
type:"POST",
url:"${pageContext.request.contextPath}/role/save6",
data:JSON.stringify(usersList),
contentType:"application/json;charset=utf-8"
});
</script>
</head>
<body>
</body>
</html>
//后台(注意url地址写的是页面的地址!!!通过页面发送ajax请求)
@RequestMapping("/save6")
@ResponseBody
public void save6(@RequestBody List<role> list) throws IOException {
System.out.println(list);
}
//upload.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>文件上传</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/role/save7" method="post" enctype="multipart/form-data">
名称:<input type="text" name="roleName"><br>
文件1:<input type="file" name="file"><br>
文件2:<input type="file" name="file"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
//后台代码(单个文件上传)
@RequestMapping("/save7")
@ResponseBody //参数必须和from表单里面的name取的名字一致
public void save7(String roleName, MultipartFile file) {
//MultipartFile是SpringMVC提供简化上传操作的工具类。
System.out.println(roleName);
System.out.println(file);
//获取上传文件的名称
String originalFilename = file.getOriginalFilename();
//把文件存放到C盘下
file.transferTo(new File("C:\\upload\\"+originalFilename));
}
$\textcolor{red}{注:要导包!!!!!} $
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
//upload.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>文件上传</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/role/save8" method="post" enctype="multipart/form-data">
名称:<input type="text" name="roleName"><br>
文件1:<input type="file" name="file"><br>
文件2:<input type="file" name="file"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
//后台代码(多文件上传)
@RequestMapping("/save8")
@ResponseBody
public void save8(String roleName, MultipartFile[] file) throws IOException {
System.out.println(roleName);
System.out.println(file[0]);
System.out.println(file[1]);
for (MultipartFile multipartFile : file) {
//获取上传文件的名称
String originalFilename = multipartFile.getOriginalFilename();
//把文件存放到C盘下
multipartFile.transferTo(new File("C:\\upload\\"+originalFilename));
}
}
@RequestParam(这个注解 如果url地址的名字 和controller接受的不同 把这个注解放在参数的前面)
public List<role> selectall3() throws IOException { InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(resourceAsStream); SqlSession sqlSession = sqlSessionFactory.openSession(); roleDao mapper = sqlSession.getMapper(roleDao.class); List<role> list = mapper.selectall3(); sqlSession.close(); }
//配置文件中(自动创建sqlsession,并且自动创建mapper实现类到spring容器 //这样在serviceimpl中直接就可以注入mapper的实现从而调用方法) <!--加载properties文件--> <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder> <!--配置数据源--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!--配置sqlsession factory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <!--加载mybatis的核心文件--> <property name="configLocation" value="classpath:sqlMapConfig-spring.xml"></property> <!--融合mybatis 不需要mapper的映射文件--> <property name="mapperLocations" value="classpath:com.demo.entity/*Mapper.xml"></property> </bean> <!--扫描mapper的包 创建mapper实现类--> <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--扫包 创建mapper的实现--> <property name="basePackage" value="com.demo.dao"></property> </bean> @Override public List<role> selectall3() throws IOException { /* InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml"); SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(resourceAsStream); SqlSession sqlSession = sqlSessionFactory.openSession(); roleDao mapper = sqlSession.getMapper(roleDao.class); List<role> list = mapper.selectall3(); sqlSession.close();*/ return roleDao.selectall3(); }
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>ssm6</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <!--spring相关的--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.7</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.0.2.RELEASE</version> </dependency> <!--事物相关的--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>5.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>5.0.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.0.5.RELEASE</version> </dependency> <!--servlet 和jsp相关的--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--mybatis相关的--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.5</version> </dependency> <!--整合mybatis和spring的--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--json的包--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.8</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.8</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.9.8</version> </dependency> </dependencies><build> <plugins> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <server>tomcat9</server> <update>true</update> </configuration> </plugin> </plugins></build> <properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> </properties></project>
<?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_2_5.xsd" id="WebApp_ID" version="2.5"> <!--初始化参数 防止加载是application的配置文件名字不同 定义一个全局变量--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!--spring的监听器 (在加载项目时 spring帮我们创建了application上下文对象)--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--springmvc 的前端控制器 servlet的公共部分 spring帮我们创建完成 之后只需要写 特殊部分的pojo--> <servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--乱码过滤器--> <filter> <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping></web-app>
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--组件扫描 扫描service和mapper--> <context:component-scan base-package="com.demo"> <!--排除扫描controller--> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller "/> </context:component-scan> <import resource="spring-dao.xml"></import></beans>
jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/testjdbc.username=rootjdbc.password=root
log4j.rootLogger=DEBUG, stdout, logfilelog4j.category.org.springframework=ERRORlog4j.category.org.apache=INFOlog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%nlog4j.appender.logfile=org.apache.log4j.RollingFileAppenderlog4j.appender.logfile.File=${myweb.root}/WEB-INF/log/myweb.loglog4j.appender.logfile.MaxFileSize=512KBlog4j.appender.logfile.MaxBackupIndex=5log4j.appender.logfile.layout=org.apache.log4j.PatternLayoutlog4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--组件扫描 controller--> <context:component-scan base-package="com.demo.controller"></context:component-scan> <!--配置mvc的注解驱动--> <mvc:annotation-driven></mvc:annotation-driven> <!--内部资源解析器--> <bean id="resourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"></property> <property name="suffix" value=".jsp"></property> </bean> <!--静态资源访问权限--> <mvc:default-servlet-handler></mvc:default-servlet-handler></beans>
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--加载properties文件--> <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder> <!--配置数据源--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${jdbc.driver}"/> <property name="jdbcUrl" value="${jdbc.url}"/> <property name="user" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!--配置sqlsession factory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <!--加载mybatis的核心文件--> <property name="configLocation" value="classpath:sqlMapConfig-spring.xml"></property> <!--融合mybatis 不需要mapper的映射文件--> <property name="mapperLocations" value="classpath:com.demo.entity/*Mapper.xml"></property> </bean> <!--扫描mapper的包 创建mapper实现类--> <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--扫包 创建mapper的实现--> <property name="basePackage" value="com.demo.mapper"></property> </bean></beans>
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration> <!-- 配置映射类的别名 --> <typeAliases> <package name="com.demo.entity"/> </typeAliases> <!--映射 配置文件中可以自动添加 映射地址--> <!--<mappers> <mapper resource="com.demo.entity/RoleMapper.xml"></mapper> <!– <package name="com.demo.entity"/>–> </mappers>--></configuration>
<?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="com.demo.mapper.roleDao"> <select id="selectall3" resultType="com.demo.entity.role"> select * from sys_role </select></mapper>
<!-- 添加分布插件的包pagehelper --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.8</version> </dependency>
<!--配置sqlsession factory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <!--加载mybatis的核心文件--> <property name="configLocation" value="classpath:sqlMapConfig-spring.xml"></property> <!--融合mybatis 不需要mapper的映射文件--> <property name="mapperLocations" value="classpath:com.demo.entity/*Mapper.xml"></property> <!--分页插件--> <property name="plugins"> <array> <bean class="com.github.pagehelper.PageInterceptor"> <property name="properties"> <!--使用下面的方式配置参数,一行配置一个 --> <value> offsetAsPageNum=true rowBoundsWithCount=true pageSizeZero=true reasonable=true </value> </property> </bean> </array> </property> </bean>
<select id="selectpage" resultType="users" parameterType="Integer"> select * from users</select>
@RequestMapping("/selectallpage2") public String selectallpage2(users users, Model model, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize){ PageHelper.startPage(2,10);//startPage是告诉拦截器说我要开始分页了。分页参数是这两个。 List<users> page = us.selectpage(users, pageNum, pageSize); PageInfo<users> pageInfo = new PageInfo<>(page);//对普通的page查询到的进行增强 model.addAttribute("pageInfo",pageInfo); for (users users1 : pageInfo.getList()) { System.out.println(users1.getId()+"===="+users1.getUname()); } System.out.println("总行数="+pageInfo.getTotal()); System.out.println("当前页="+pageInfo.getPageNum()); System.out.println("每页行数="+pageInfo.getPageSize()); System.out.println("总页数="+pageInfo.getPages()); System.out.println("起始行数="+pageInfo.getStartRow()); System.out.println("是第一页="+pageInfo.isIsFirstPage()); System.out.println("是最后一页="+pageInfo.isIsLastPage()); System.out.println("还有下一页="+pageInfo.isHasNextPage()); System.out.println("还有上一页="+pageInfo.isHasPreviousPage()); System.out.println("页码列表="+ Arrays.toString(pageInfo.getNavigatepageNums())); return "select"; }
<%@ page contentType="text/html;charset=UTF-8" language="java" %><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><html><head> <title></title></head><body><h1>查询全部</h1><table> <thead> <tr> <td>编号</td> <td>姓名</td> <td>密码</td> </tr> </thead> <c:forEach var="list" items="#{pageInfo.list}"> <tbody> <tr> <td>${list.id}</td> <td>${list.uname}</td> <td>${list.pwd}</td> </tr> </tbody> </c:forEach></table></body></html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><html><head> <title>select</title> <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src="/js/jquery.min.js"></script> <script> var pages=${pageInfo.pages};//页面的总数 //下一页的按钮 function next(pageNum) { // alert(pageNum); if(pages>=pageNum){ $("#pageNum").val(pageNum); $("#cx").submit(); }else{ alert("到头啦!!!"); } } //中间数字部分 function current(i) { //alert(i); if (i!=0){ $("#pageNum").val(i); $("#cx").submit(); } } //上一页的按钮 function prep(pageNum) { // alert(pageNum); if(pageNum>=1){ $("#pageNum").val(pageNum); $("#cx").submit(); }else{ alert("已经是第一页啦!!!"); } } </script></head><body><h1>查询全部</h1><form action="/users/selectallpage2" method="post" id="cx"> <input type="hidden" name="pageNum" value="${pageInfo.pageNum}" id="pageNum"> <table> <thead> <tr> <td>编号</td> <td>姓名</td> <td>密码</td> </tr> </thead> <c:forEach var="list" items="#{pageInfo.list}"> <tbody> <tr> <td>${list.id}</td> <td>${list.uname}</td> <td>${list.pwd}</td> </tr> </tbody> </c:forEach> </table></form><ul class="pagination" id="xq"> <li><a href="javascript:prep(${pageInfo.pageNum-1});">«</a></li> <c:forEach var="i" items="${pageInfo.navigatepageNums}"> <li name="pageNum"><a href="javascript:current(${i});">${i}</a></li> </c:forEach> <li id="next"><a href="javascript:next(${pageInfo.pageNum+1});">»</a></li></ul></body></html>
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-N8n5FGuw-1646100987833)(C:\Users\weiwanyi\AppData\Roaming\Typora\typora-user-images\image-20211122132532101.png)]
server: # 服务器的HTTP端口,默认为8080 port: 8080 servlet: # 应用的访问路径 context-path: / tomcat: # tomcat的URI编码 uri-encoding: UTF-8 # tomcat最大线程数,默认为200 max-threads: 800 # Tomcat启动初始化的线程数,默认值25 min-spare-threads: 30spring: datasource: driverClassName: com.mysql.jdbc.Driver url: jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8 username: root password: rootmybatis: # 搜索指定包别名 typeAliasesPackage: com.demo.**.entity # 配置mapper的扫描,找到所有的mapper.xml映射文件 mapperLocations: classpath*:mybatis/*Mapper.xml
spring.datasource.username=rootspring.datasource.password=rootspring.datasource.url= jdbc:mysql://localhost:3306/accountspring.datasource.driver-class-name=com.mysql.jdbc.Driver#整合#mybatis.type-aliases-package=com.demo.entity#mybatis.mapper-locations=classpath:mybatis/mapper/*.xml#mybatis日志mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl#可以把 POST 请求转为 DELETE 或 POST 请求spring.mvc.hiddenmethod.filter.enabled=true
// _ooOoo_ o8888888o 88" . "88 (| ^_^ |) O\ = /O ____/`---'\____ .' \\| |// `. / \\||| : |||// \ / _||||| -:- |||||- \ | | \\\ - /// | | | \_| ''\---/'' | | \ .-\__ `-` ___/-. / ___`. .' /--.--\ `. . ___ ."" '< `.___\_<|>_/___.' >'"". | | : `- \`.;`\ _ /`;.`/ - ` : | | \ \ `-. \_ __\ /__ _/ .-` / / ========`-.____`-.___\_____/___.-`____.-'======== `=---=' ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 佛祖保佑 永不宕机 永无BUG //
<!--springboot整合mybatis 用了这个包 就不需要用mybatis的包了--><dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.0.5</version></dependency><!--连接驱动的包 注意自己的版本号 我的mysql是5 所以使用的版本要改成5.XX.XX--><dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.10</version></dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency>
这个是不需要自己写配置文件 和sql代码的里面
package com.demo.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;import com.demo.entity.users;import org.apache.ibatis.annotations.Mapper;import org.springframework.stereotype.Repository;@Mapper//这个是扫包的 or@MapperScan("com.demo.mapper")加到启动类上面@Repositorypublic interface usersMapper extends BaseMapper<users> {}
<!--导入html模板引擎--><dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId></dependency><dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-java8time</artifactId></dependency>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
注意!!!html页面需要放在templates目录下才可以被访问到
@RequestMapping("/queryall")public String queryall(){ List<users> queryall = usersService.queryall(); System.out.println(queryall); return "hehe";}
@Configurationpublic class myMVCconfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/hehe.html").setViewName("hehe"); registry.addViewController("/login.html").setViewName("login"); registry.addViewController("/").setViewName("login"); registry.addViewController("/index.html").setViewName("index"); registry.addViewController("/moduleSetting.html").setViewName("moduleSetting"); registry.addViewController("/user.html").setViewName("user"); }}
@Test //条件是否相同 通过名字查询column:列的字段 val:值void test2() { QueryWrapper<users> wrapper=new QueryWrapper<>(); wrapper.eq("uname","lisi"); users users = usersMapper.selectOne(wrapper); System.out.println(users);}
@Test //查询id在10-20之间的用户void test3() { QueryWrapper<users> wrapper=new QueryWrapper<>(); wrapper.between("id","10","20"); List<users> list = usersMapper.selectList(wrapper); System.out.println(list);}
@Test //模糊查询void test4() { QueryWrapper<users> wrapper=new QueryWrapper<>(); wrapper.notLike("uname","tes").like("uname","i"); List<Map<String, Object>> maps = usersMapper.selectMaps(wrapper); System.out.println(maps);}
package com.demo.config;import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;import org.mybatis.spring.annotation.MapperScan;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configuration/*@MapperScan("com.demo.mapper.*")*/public class MybatisPlusConfig { // 旧版 @Bean public PaginationInterceptor paginationInterceptor() { PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); return paginationInterceptor; }}
@RequestMapping("/fy") @ResponseBody public String fy(){ Page<users> page=new Page<>(1,10); IPage<users> fy = usersService.fy(page); System.out.println(page.getTotal()+"======"); //page里面有很多 属性值 当前页 总页等等 System.out.println(fy); return "hehe"; }
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-DnK5oiQA-1646100987834)(C:\Users\weiwanyi\AppData\Roaming\Typora\typora-user-images\image-20211122182710339.png)]
//servicepublic IPage<users> fy(Page page);//serviceimpl @Override public IPage<users> fy(Page page) { return usersMapper.selectPage(page,null); }
@Mapper@Repositorypublic interface usersMapper extends BaseMapper<users> {}
package com.demo.config;import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;import org.mybatis.spring.annotation.MapperScan;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configuration/*@MapperScan("com.demo.mapper.*")*/public class MybatisPlusConfig { // 旧版 @Bean public PaginationInterceptor paginationInterceptor() { PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); return paginationInterceptor; }}
@RequestMapping("/fy") public String fy(Model model, @RequestParam(value = "pageNum", defaultValue = "1") int pageNum, @RequestParam(value = "pageSize", defaultValue = "5") int pageSize){ Page<users> page=new Page<>(pageNum,pageSize); IPage<users> fy = usersService.fy(page); model.addAttribute("pagelist",page); System.out.println(page.getRecords()+"====123"); return "user"; }//getRecords是list里面的数据
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fRJFWOxo-1646100987835)(C:\Users\weiwanyi\AppData\Roaming\Typora\typora-user-images\image-20211122182710339.png)]
//servicepublic IPage<users> fy(Page page);//serviceimpl @Override public IPage<users> fy(Page page) { return usersMapper.selectPage(page,null); }
@Mapper@Repositorypublic interface usersMapper extends BaseMapper<users> {}
<table id="tbRecord"> <thead> <tr> <th>ID</th> <th>姓名</th> <th>用户名</th> <th>邮箱</th> <th>电话 </th> <th>编辑</th> <th>删除</th> </tr> </thead> <tbody th:each="users:${pagelist.getRecords()}"> <td hidden id="uid" th:text="${users.getId()}"></td> <td th:text="${users.getId()}">0</td> <td th:text="${users.getUname()}">张三11</td> <td th:text="${users.getAccountname()}"></td> <td th:text="${users.getEmail()}">354545454@qq.com</td> <td th:text="${users.getPhone()}">182333443434</td> <td class="td_column_edit" id="td_column_edit_1" align="center" style="cursor:pointer;"> <button class="btn btn-primary" th:onclick="'javascript:update_users('+${users.getId()}+')'"><i class="icon-edit" style="margin-right:3px"></i>编辑</button></td> <td class="td_column_delete" id="td_column_delete_1" align="center" style="cursor:pointer;"> <button class="btn btn-danger" th:onclick="'javascript:delete_users('+${users.getId()}+')'"><i class="icon-trash" style="margin-right:3px"></i>删除</button></td> </tr> </tbody><!--//页脚的页面--><div id="usersfy"> <ul class="pagination" > <!--上一页--> <li th:if="${pagelist.getCurrent()>=1}"> <a th:href="'/users/fy?pageNum='+${pagelist.getCurrent()-1}">«</a> </li> <!--中间的部分 i :${#numbers.sequence(1, pagelist.getPages())}这个表达式就是循环i的--> <li th:each="i :${#numbers.sequence(1, pagelist.getPages())}"> <a th:href="'/users/fy?pageNum='+${i}"><span th:text="${i}"></span></a> </li> <!--下一页--> <li th:if="${pagelist.getCurrent()<=pagelist.getPages()}" > <a th:href="'/users/fy?pageNum='+${pagelist.getCurrent()+1}">»</a> </li> </ul></div></table>
原文:https://blog.csdn.net/weixin_38117760/article/details/103251403
1.导入依赖
<!--导入html依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
2.添加此模板(thymeleaf的依赖)。会从templates中去找相对于的页面。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Ph368Zis-1646100987836)(C:\Users\weiwanyi\AppData\Roaming\Typora\typora-user-images\image-20211123210937485.png)]
@RequestMapping("/queryall") public String queryall(){ List<users> queryall = usersService.queryall(); System.out.println(queryall); return "hehe"; }