上一章的springmvc回顾内容:
1. springmvc框架: 主要作用:处理客户的请求,并处理数据,以及响应客户。
2. springmvc搭建流程:
[1]引入springmvc依赖。 spring-webmvc
[2]编写springmvc配置文件。
1.包扫描<context:component-scan basepackage=""/>
2.开启注解驱动:<mvc:annotation-driven> 导入的是mvc
3.静态资源放行:<mvc:default-servlet-handler/>
4.配置视图解析器。解析controller层返回的字符串。
[3]注册servlet:---DispatherServlet
[4]编写controller类的方法。
3. springmvc接受参数:
1.少量参数---直接方法的参数名和传递的参数名一致。
2.大量的参数--封装一个实体类属性要和传递的参数名一致。
4. 设置编码过滤器
一、跳转不经过视图解析器
返回的字符串经过视图解析器后,按照解析器的配置跳转。 如果不想经过视图解析器,可以使用redirect和forward关键 告诉springmvc我无需经过视图解析器。
两种方式:
forward:转发跳转
redirect:重定向跳转
二、controller如何保存数据给页面
servlet保存数据,pageContext,request, session, application,前端jsp通过EL表达式获取。
(在 Servlet 或控制器中,你可以将数据保存到不同的作用域(如 PageContext、Request、Session、Application),然后在 JSP 页面中通过 EL 表达式根据这些作用域来获取并显示数据。)
在 Java Web 应用中,不同作用域(scope)的对象如何保存数据以及前端 JSP 页面如何通过 EL(Expression Language)表达式获取这些数据。下面分点解释:
1. Servlet 保存数据
在 Servlet 或控制器中,可以通过以下几种方式将数据保存到不同的作用域对象中:
PageContext:仅限于当前页面,通常不常用。
Request:当前请求范围内有效,适用于一次请求响应周期。
Session:会话范围内有效,适用于多个请求之间共享数据。
Application(ServletContext):整个应用程序范围内有效,适用于全局共享数据。
2. 保存数据的方式
在你的 UserController 中,已经展示了如何将数据保存到不同的作用域:// 保存到 request
request.setAttribute("list1", list);// 保存到 model (等同于 request)
model.addAttribute("list2", list);// 保存到 session
session.setAttribute("list3", list);// 保存到 model (由于 @SessionAttributes, 也会保存到 session)
model.addAttribute("list4", list);3. 前端 JSP 通过 EL 表达式获取数据
在 JSP 页面中,可以使用 EL 表达式来访问这些保存在不同作用域中的数据。EL 表达式的语法是 ${},并且可以根据作用域的不同来获取相应的属性
1 .数据保存到request的方式
直接使用request的对象:
2.springMVC提供了一个对象Model对象
该对象默认的保存周期和request等价。 如果使用request保存,你需要引入servlet依赖。接受为了解耦。
3. 数据保存到session的方式
直接保存到session对象
@Session Attributes:
三、 返回json数据
1 .什么请求会返回json数据:
ajax异步请求
2. 当时如何返回json对象
-
使用fastjson的工具
-
把java对象转换为json对象
-
out.print(json字符串)
-
out.flush() out.close();
3 .springmvc返回的json操作更加简化
1.引入依赖jackson
<!--jackson-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.18.1</version>
</dependency
2.在方法上使用@ResponseBody注解
3.测试后
<body>
<button οnclick="ajax()">提交</button>
</body>
<script>
function ajax(){
$.get("/list",function(data){
console.log(data);//浏览器控制台输出
},"json")
}
</script>
四、拦截器
1. 跳转不经过视图解析器: forward: redirect: 2. controller如何保存数据: request, session, Model 3. controller层如何返回json数据: [1]jackson依赖 [2]方法上添加@ResponseBody 把该方法返回的对象转换为json格式。等价于out.print();
拦截不符合规则的,放行符合规则的。 等价于过滤器。
拦截器只拦截controller层API接口。
1. 如何定义拦截器。
1.定义一个类并实现拦截器接口
public class MyInterceptor implements HandlerInterceptor { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //获取session对象 HttpSession session=request.getSession(); //获取session当前用户的信息 Object userinfo = session.getAttribute("userinfo"); if(userinfo==null){ //没有登录,跳转到登录页面 response.sendRedirect("/login.jsp"); return false; } return true; //如果返回值为true,表示拦截器放行。否则,拦截器不放行 } }
2.注册拦截器并配置拦截规则--springmvc配置文件中
<!--注册自定义拦截器以及拦截规则--> <mvc:interceptors> <mvc:interceptor> <!--path:拦截的路径 /**表示拦截多层路径--> <mvc:mapping path="/**"/> <!--排除的路径。--> <mvc:exclude-mapping path="/user/login"/> <!--放置自定义的拦截器类--> <bean class="com.aaa.interceptor.MyInterceptor"/> </mvc:interceptor> </mvc:interceptors>
五、全局异常处理
如果controller发生异常,我们需要对controller层中的所有方法都进行处理。这样比较麻烦。我们可以对所有controller中的接口提供一个统一的异常处理。
1.定义全局异常类
//全局异常处理类. @ControllerAdvice public class MyGlobalException { @ExceptionHandler(Exception.class) //当发生Exception类型的异常会执行该方法,并异常对象传递给该方法的参数。 @ResponseBody public String handlerException(Exception e){ System.out.println(e.getMessage()); System.out.println("错误~~~~~~~~~~~~~~~~~~~~~~~~~"); return "error2222222222222222222222";//经过视图解析器: /views/error.jsp } @ExceptionHandler(ArithmeticException.class) @ResponseBody public String handlerArithmeticException(Exception e){ System.out.println("错误****************************"); return "error2222222222222222222"; } }
2.注意:保证springmvc能够扫描到该异常处理类
function loadEmp(){ $.ajax({ url:"/emp/list", type:"get", dataType:"json", //服务器响应成功 success:function(data){ console.log(data) var str=""; for(var i=0;i<data.length;i++){ str+="<tr>" str+="<td>"+data[i].empId+"</td>" str+="<td>"+data[i].empName+"</td>" str+="<td>"+data[i].empJob+"</td>" str+="<td>"+data[i].empSalary+"</td>" str+="<td>"+data[i].dept.deptName+"</td>" str+="<td><a οnclick='deleteEmp("+data[i].empId+")'>删除</a><a οnclick='/views/update.jsp'>修改</a></td>" str+="</tr>" } document.getElementById("empBody").innerHTML=str; }, //服务器响应故障 error: function (data){ console.log(data); } }) }
六、 文件上传
1 .原理
2. 完成文件上传--本地服务器保存
1. 引入文件上传的依赖jar
<!--文件上传依赖--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.5</version> </dependency>
2.配置文件上传解析器
<!--文件上传解析器--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--最大上传的大小。单位byte字节。5M=5*1024*1024--> <property name="maxUploadSize" value="5242880"/> <!--设置文件上传的编码--> <property name="defaultEncoding" value="utf-8"/> </bean>
3.编写文件上传的页面
<%--文件上传的表单提交方式必须为post.而且需要设置表单提交的编码格式。enctype="multipart/form-data" 该类型表示既能上传文本又能上传文件。--%> <form action="/upload" method="post" enctype="multipart/form-data"> 选择文件:<input type="file" name="myfile"/><br> 姓名:<input type="text" name="username"/><br> <input type="submit"/> </form>
4.编写上传的api接口
@RequestMapping("/upload") public String upload(MultipartFile myfile, HttpServletRequest request) throws IOException { //1.获取保存文件的路径 String realPath = request.getSession().getServletContext().getRealPath("/images"); //2.根据上面的路径创建文件对象 File file=new File(realPath); //3.判断该文件夹是否存在 if(!file.exists()){ file.mkdirs(); } //4.获取上传文件的名称. 获取登录者ip+登录者id+登录者的时间戳 String filename = UUID.randomUUID().toString().replace("-","")+myfile.getOriginalFilename(); //5.把上传的文件保存到指定服务器下的路径。 File target=new File(realPath+"/"+filename); myfile.transferTo(target); System.out.println("上传成功"); return "main"; }
3. 完成文件上传--文件保存到文件服务器
如果把文件存在本地服务器,服务器与服务器之间无法共享文件。我们需要一个专门存放文件的服务器。
可以自己搭建文件服务器[FastDFS Hadoop] 或者租第三方阿里云。
3.1 登录阿里云
容器:---针对不同的项目建立不同的容器。
创建一个bucket 并设置公共读。
3.2 申请密钥和key
3.3 开始使用
<dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.17.4</version> </dependency>
一定是在之前文件上传的基础上。
public static void main(String[] args) throws Exception { // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。 String endpoint = "oss-cn-beijing.aliyuncs.com"; // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。 // EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); DefaultCredentialProvider defaultCredentialProvider = CredentialsProviderFactory.newDefaultCredentialProvider("XXXXX", "XXXX"); // 填写Bucket名称,例如examplebucket。 String bucketName = "qy179"; // 填写Object完整路径,完整路径中不能包含Bucket名称 上传到oss的bucket中的名称 String objectName = "2.jpg"; // 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。 // 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。 String filePath= "D:\\2.jpg"; // 填写Bucket所在地域。以华东1(杭州)为例,Region填写为cn-hangzhou。 String region = "cn-beijing"; // 创建OSSClient实例。 ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(defaultCredentialProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { InputStream inputStream = new FileInputStream(filePath); // 创建PutObjectRequest对象。 PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream); // 创建PutObject请求。 PutObjectResult result = ossClient.putObject(putObjectRequest); } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } finally { if (ossClient != null) { ossClient.shutdown(); } } }
写一个添加员工: 增加一个头像。普通的表单提交。oss.
七、综合案例:
完成crud操作(数据库增删改查)登录注册添加查询删除修改界面端jsp通过EL表达式获取。
1. 工程搭建
1.创建maven的web工程并引入依赖
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zyl</groupId> <artifactId>springmnv_mybatis</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>springmnv_mybatis Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <maven.compiler.source>8</maven.compiler.source> <maven.compiler.target>8</maven.compiler.target> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.17</version> </dependency> <!--文件上传依赖--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.5</version> </dependency> <!-- Commons FileUpload --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency> <!-- Commons IO --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.8.0</version> </dependency> <!--阿里云存储--> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.17.4</version> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.25</version> </dependency> <!--springmvc--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.15.RELEASE</version> </dependency> <!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.30</version> </dependency> <!--servlet--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> </dependency> <!--引入log4j--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.12</version> </dependency> <!--jackson--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.18.1</version> </dependency> </dependencies> <build> <finalName>springmnv_mybatis</finalName> </build> </project>
2.实体类和dao和映射文件
使用插件完成,代码生成器
3.配置spring和mybatis配置文件
拿就行:spring.xml和mybatis.xml另外还有db.properties(我再加一个log4j.properties)
<?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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--扫描包--> <context:component-scan base-package="com.zyl"/> <!--开启注解驱动--> <mvc:annotation-driven/> <mvc:default-servlet-handler/> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/views/"/> <property name="suffix" value=".jsp"/> </bean> <!--文件上传解析器--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--最大上传的大小。单位byte字节。5M=5*1024*1024--> <property name="maxUploadSize" value="5242880"/> <!--设置文件上传的编码--> <property name="defaultEncoding" value="utf-8"/> </bean> <!--配置拦截器--> <mvc:interceptors> <mvc:interceptor> <!--拦截所有请求--> <mvc:mapping path="/**"/> <!--放行的路径--> <mvc:exclude-mapping path="/user/login"/> <mvc:exclude-mapping path="/views/main.jsp"/> <mvc:exclude-mapping path="/upload"/> <!--指定拦截器--> <bean class="com.zyl.interceptor.MyInterceptor"/> </mvc:interceptor> </mvc:interceptors> </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> <!--1.引入数据源文件--> <properties resource="db.properties"/> <!--2.起别名--> <typeAliases> <!--2.1为单个实体类起别名--> <!-- <typeAlias type="org.example.entity.Role" alias="R"/>--> <!--2.2为指定的包下的实体类起别名:默认就是包名--> <!--<package name ="org.example.entity"/>--> </typeAliases> <!--配置pagehelper配置--> <!-- <plugins> <!– com.github.pagehelper为PageHelper类所在包名 –> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <!– 使用下面的方式配置参数,后面会有所有的参数介绍 –> <property name="param1" value="value1"/> </plugin> </plugins>--> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <!--name是固定的 value根据配置需要为自己的内容--> <property name="driver" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </dataSource> </environment> </environments> <mappers> <!--3.注解模式下的映射文件路径,可写可不写,好像不写也不出错--> <!-- <mapper class="org.example.dao.RoleDao"/>--> <!--原本的映射文件--> <mapper resource="mapper/DeptMapper.xml"/> <mapper resource="mapper/EmpMapper.xml"/> <mapper resource="mapper/UserinfoMapper.xml"/> </mappers> </configuration>-------------------------------------------------------------------------------------------------------------------------
#key=value key ????????? jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/bb jdbc.username=root jdbc.password=root-----------------------------------------------------------------------------------------------------------------------
log4j.rootLogger=DEBUG, Console #Console log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.layout=org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n log4j.logger.java.sql.ResultSet=INFO log4j.logger.org.apache=INFO log4j.logger.java.sql.Connection=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG
4.注册公共servlet
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list> <!--第四步: 注册公共的servlet-DispatcherServlet--> <!--注册公共servlet--> <servlet> <servlet-name>spring03</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--加载 读取 spring 配置文件--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring03.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>spring03</servlet-name> <!--访问任何路径都要经过servlet--> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
5.编码过滤器
package com.zyl.filter; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import java.io.IOException; /** * @className: Myfilter * @author: Zyl * @date: 2024/12/16 11:36 * @Version: 1.0 * @description: */ //编码过滤器 @WebFilter("/*") public class Myfilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { servletRequest.setCharacterEncoding("utf-8"); servletResponse.setCharacterEncoding("utf-8"); filterChain.doFilter(servletRequest,servletResponse); } @Override public void destroy() { } }
6.创建一个登录页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script src="/js/jquery-3.7.1.min.js"></script> </head> <body> <h2>登录页面</h2> <form action="/user/login" method="post"> <input type="text" name="username" id="username"> <input type="password" name="password" id="password"> <input type="button" value="登录" οnclick="login()"> <a href="/views/register.jsp">注册</a> </form> <script> function login(){ var name = document.getElementById("username").value; var pwd = document.getElementById("password").value; $.post("/user/login",{"name":name,"pwd":pwd},function(data){ if(data){ location.href="/views/main.jsp" }else{ alert("用户名或密码错误") } },"json") } </script> </body> </html>
7.拦截器:
package com.zyl.interceptor; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * @className: MyInterceptor * @author: Zyl * @date: 2024/12/17 9:09 * @Version: 1.0 * @description: */ public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception{ /* // 获取请求的URI String uri = request.getRequestURI(); // 判断是否为 /upload 请求 if (uri.endsWith("/upload")) { return true; // 放行 /upload 请求 }*/ //拦截器界面 //System.out.println("拦截器拦截"); //写代码,如果不登录,其他的功能接口获取不到,和白名单相似 //获取session的信息 HttpSession session =request.getSession() ; //获取用户的信息 Object useinfo=session.getAttribute("userinfo" ); if(useinfo==null){ response.sendRedirect("/login.jsp"); } return true; } }
8.全局异常处理
package com.zyl.handler; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; /** * @className: MyGlobalException * @author: Zyl * @date: 2024/12/17 10:34 * @Version: 1.0 * @description: */ @ControllerAdvice//全局异常处理 public class MyGlobalException { @ExceptionHandler(value = RuntimeException.class) //发生Exception类型的异常会执行此方法 ,并将异常 // @ResponseBody public String handleException2(Exception e) { System.out.println("----------------"); System.out.println(e.getMessage()); return "error";//经过视图解析器: /views/error.jsp } // @ExceptionHandler(value = Exception.class) //发生Exception类型的异常会执行此方法 @ResponseBody // public String handleException1(Exception e) { // System.out.println("----------------"); // System.out.println(e.getMessage()); // return "error"; // // } }
9.文件上传(图片,阿里云对象存储)
package com.zyl.utils; import com.aliyun.oss.*; import com.aliyun.oss.common.auth.CredentialsProviderFactory; import com.aliyun.oss.common.auth.DefaultCredentialProvider; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.model.PutObjectRequest; import com.aliyun.oss.model.PutObjectResult; import org.springframework.core.env.Environment; import org.springframework.web.multipart.MultipartFile; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.UUID; public class UploadUtils { // private static Environment env; // // public static void setEnv(Environment env) { // UploadUtils.env = env; // } public static String uploadToOss(MultipartFile myfile) { // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。 String endpoint = "oss-cn-beijing.aliyuncs.com"; // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。 // EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); DefaultCredentialProvider defaultCredentialProvider = CredentialsProviderFactory.newDefaultCredentialProvider("LTAI5tMfYsVWQbGq8VchJHAh", "wy9uw3rZny72PrKuPkCU25EqZ3ozb0"); // 填写Bucket名称,例如examplebucket。 String bucketName = "qy1217"; // 生成上传到oss的object名称 String objectName = UUID.randomUUID().toString().replace("-", "") + "_" + myfile.getOriginalFilename(); // 填写Bucket所在地域。以华东1(杭州)为例,Region填写为cn-hangzhou。 String region = "cn-beijing"; // 创建OSSClient实例。 ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(defaultCredentialProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { InputStream inputStream = myfile.getInputStream(); // 创建PutObjectRequest对象。 PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream); // 创建PutObject请求。 PutObjectResult result = ossClient.putObject(putObjectRequest); // 生成文件的URL return "http://" + bucketName + "." + endpoint + "/" + objectName; } catch (Exception oe) { throw new RuntimeException("上传oss失败"); } finally { if (ossClient != null) { ossClient.shutdown(); } } } }
10.自已加的单元测试
test:
import com.zyl.entity.Userinfo; import com.zyl.mapper.UserinfoMapper; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import javax.servlet.http.HttpSession; import java.io.InputStream; /** * @className: Test * @author: Zyl * @date: 2024/12/16 14:33 * @Version: 1.0 * @description: */ public class Test { private UserinfoMapper userinfoMapper; private SqlSession sqlSession; @org.junit.Test public void test01() throws Exception{ //1.读取mybatis的配置文件 InputStream resourcesAsStream= Resources.getResourceAsStream("mybatis.xml"); //2.创建SqlSessionFactory工厂 SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(resourcesAsStream); //3.创建SqlSession对象 SqlSession sqlSession=sqlSessionFactory.openSession(); //3.创建SqlSession sqlSession=sqlSessionFactory.openSession(); //4.创建mapper userinfoMapper=sqlSession.getMapper(UserinfoMapper.class); Userinfo userinfo=userinfoMapper.selectByNameAndPwd("张三","123456"); System.out.println(userinfo); //提交 sqlSession.commit(); } }
创建web并引入依赖
实体类映射文件dao
配置文件--springmvc和mybatis
注册servlet--DispatcherServlet
编码过滤器
登录网页
拦截器
全局异常处理
文件上传(图片,阿里云对象存储)
自己加的单元测试
五、项目业务:
springmvc-mybatis
1. 登录业务
1. maper(dao)接口:UserinfoMapper
package com.zyl.mapper; import com.zyl.entity.Userinfo; import org.apache.ibatis.annotations.Param; /** * @author * @description 针对表【tbl_userinfo】的数据库操作Mapper * @createDate 2024-12-16 11:20:58 * @Entity com.zyl.entity.Userinfo */ public interface UserinfoMapper { int deleteByPrimaryKey(Long id); int insert(Userinfo userinfo); int insertSelective(Userinfo record); Userinfo selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(Userinfo record); int updateByPrimaryKey(Userinfo record); //根据账号和密码登录 Userinfo selectByNameAndPwd(@Param("name") String name, @Param("pwd") String pwd); //定义用户名是否重复 Userinfo selectByName(String name); //定义一个注册的方法 // int register(@Param("name")String name,@Param("password")String password,@Param("userAge")Integer age,@Param("userSex") String sex); int register(Userinfo userinfo); }
2.映射文件:UserinforMapper.xml
<?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.zyl.mapper.UserinfoMapper"> <resultMap id="BaseResultMap" type="com.zyl.entity.Userinfo"> <id property="id" column="id" jdbcType="INTEGER"/> <result property="name" column="name" jdbcType="VARCHAR"/> <result property="password" column="password" jdbcType="VARCHAR"/> <result property="userAge" column="user_age" jdbcType="INTEGER"/> <result property="userSex" column="user_sex" jdbcType="VARCHAR"/> <result property="rid" column="rid" jdbcType="INTEGER"/> </resultMap> <sql id="Base_Column_List"> id,name,password, user_age,user_sex,rid </sql> <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from tbl_userinfo where id = #{id,jdbcType=INTEGER} </select> <!--注册--> <insert id="register"> insert into tbl_userinfo(name, password, user_age, user_sex) values(#{name}, #{password}, #{userAge}, #{userSex}) </insert> <!--登录--> <select id="selectByNameAndPwd" resultMap="BaseResultMap"> select * from tbl_userinfo where name=#{name} and password=#{pwd} </select> <select id="selectByName" resultType="com.zyl.entity.Userinfo"> select * from tbl_userinfo where name=#{name} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Long"> delete from tbl_userinfo where id = #{id,jdbcType=INTEGER} </delete> <insert id="insert" keyColumn="id" keyProperty="id" parameterType="com.zyl.entity.Userinfo" useGeneratedKeys="true"> insert into tbl_userinfo ( id,name,password ,user_age,user_sex,rid ) values (#{id,jdbcType=INTEGER},#{name,jdbcType=VARCHAR},#{password,jdbcType=VARCHAR} ,#{userAge,jdbcType=INTEGER},#{userSex,jdbcType=VARCHAR},#{rid,jdbcType=INTEGER} ) </insert> <insert id="insertSelective" keyColumn="id" keyProperty="id" parameterType="com.zyl.entity.Userinfo" useGeneratedKeys="true"> insert into tbl_userinfo <trim prefix="(" suffix=")" suffixOverrides=","> <if test="id != null">id,</if> <if test="name != null">name,</if> <if test="password != null">password,</if> <if test="userAge != null">user_age,</if> <if test="userSex != null">user_sex,</if> <if test="rid != null">rid,</if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="id != null">#{id,jdbcType=INTEGER},</if> <if test="name != null">#{name,jdbcType=VARCHAR},</if> <if test="password != null">#{password,jdbcType=VARCHAR},</if> <if test="userAge != null">#{userAge,jdbcType=INTEGER},</if> <if test="userSex != null">#{userSex,jdbcType=VARCHAR},</if> <if test="rid != null">#{rid,jdbcType=INTEGER},</if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.zyl.entity.Userinfo"> update tbl_userinfo <set> <if test="name != null"> name = #{name,jdbcType=VARCHAR}, </if> <if test="password != null"> password = #{password,jdbcType=VARCHAR}, </if> <if test="userAge != null"> user_age = #{userAge,jdbcType=INTEGER}, </if> <if test="userSex != null"> user_sex = #{userSex,jdbcType=VARCHAR}, </if> <if test="rid != null"> rid = #{rid,jdbcType=INTEGER}, </if> </set> where id = #{id,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.zyl.entity.Userinfo"> update tbl_userinfo set name = #{name,jdbcType=VARCHAR}, password = #{password,jdbcType=VARCHAR}, user_age = #{userAge,jdbcType=INTEGER}, user_sex = #{userSex,jdbcType=VARCHAR}, rid = #{rid,jdbcType=INTEGER} where id = #{id,jdbcType=INTEGER} </update> </mapper>
3.UserController
package com.zyl.controlly; import com.zyl.entity.Userinfo; import com.zyl.mapper.UserinfoMapper; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpSession; import java.io.IOException; import java.io.InputStream; /** * @className: UserController * @author: Zyl * @date: 2024/12/16 11:23 * @Version: 1.0 * @description: */ @Controller //表示控制层--等价servlet @RequestMapping("/user") public class UserController { private UserinfoMapper userinfoMapper; private SqlSession sqlSession; public UserController() throws Exception { try { //1. 连接数据库,读取mybatis 的配置文件 InputStream inputStream = Resources.getResourceAsStream("mybatis.xml"); //2. 创建SqlSessionFactory 工厂 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //3. 创建SqlSession sqlSession = sqlSessionFactory.openSession(); //4. 创建mapper userinfoMapper = sqlSession.getMapper(UserinfoMapper.class); } catch (Exception e) { e.printStackTrace(); throw e; } } @RequestMapping("login") @ResponseBody//表示返回的是json数据 public boolean login(String name, String pwd ,HttpSession session){ //调用dao 代码。UserinfoMapper Userinfo userinfo=userinfoMapper.selectByNameAndPwd(name,pwd); if(userinfo!=null){ session.setAttribute("userinfo" ,userinfo); return true; }else{ return false; } } @RequestMapping("register") @ResponseBody public boolean register( Userinfo userinfo ){ //调用dao代码。UserinfoMapper //检查用户名是否重复 Userinfo userinfo1=userinfoMapper.selectByName(userinfo.getName()); if(userinfo1!=null){ return false; }else { // System.out.println(userinfo.getName()); // System.out.println(userinfo.getPassword()); // System.out.println(userinfo.getUserAge()); // System.out.println(userinfo.getUserSex()); // int i=userinfoMapper.register( userinfo.getName(), userinfo.getPassword(), userinfo.getUserAge(), userinfo.getUserSex()); int i = userinfoMapper.register(userinfo); sqlSession.commit(); if (i > 0) { return true; } else { return false; } } } }
4.前端页面:login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script src="/js/jquery-3.7.1.min.js"></script> </head> <body> <h2>登录页面</h2> <form action="/user/login" method="post"> <input type="text" name="username" id="username"> <input type="password" name="password" id="password"> <input type="button" value="登录" οnclick="login()"> <a href="/views/register.jsp">注册</a> </form> <script> function login(){ var name = document.getElementById("username").value; var pwd = document.getElementById("password").value; $.post("/user/login",{"name":name,"pwd":pwd},function(data){ if(data){ location.href="/views/main.jsp" }else{ alert("用户名或密码错误") } },"json") } </script> </body> </html>
2. 主页=展示所有员工的信息
展示对应的部门信息
1.dao接口
List<Emp> selectAll();
EmpMapper:
package com.zyl.mapper; import com.zyl.entity.Emp; import java.util.List; /** * @author 赵亚雷 * @description 针对表【tbl_emp】的数据库操作Mapper * @createDate 2024-12-16 11:20:58 * @Entity com.zyl.entity.Emp */ public interface EmpMapper { int deleteByPrimaryKey(Long id); int insert(Emp record); int insertSelective(Emp record); Emp selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(Emp record); int updateByPrimaryKey(Emp record); //显示所有的员工信息 public List<Emp> selectAllEmp(); //定义添加的功能 public int addEmp(Emp emp); }
2.映射文件:EmpMapper.xml:
<?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.zyl.mapper.EmpMapper"> <resultMap id="BaseResultMap" type="com.zyl.entity.Emp"> <id property="empId" column="emp_id" jdbcType="INTEGER"/> <result property="empName" column="emp_name" jdbcType="VARCHAR"/> <result property="empJob" column="emp_job" jdbcType="VARCHAR"/> <result property="empSalary" column="emp_salary" jdbcType="DECIMAL"/> <result property="empHeader" column="emp_header"/> <result property="did" column="did" jdbcType="INTEGER"/> <association property="dept" javaType="com.zyl.entity.Dept"> <id property="deptId" column="dept_id" jdbcType="INTEGER"/> <result property="deptName" column="dept_name" jdbcType="VARCHAR"/> <result property="deptLoc" column="dept_loc" jdbcType="VARCHAR"/> </association> </resultMap> <sql id="Base_Column_List"> emp_id,emp_name,emp_job, emp_salary,did </sql> <!--显示所有员工的信息--> <select id="selectAllEmp" resultMap="BaseResultMap"> select * from tbl_emp e join tbl_dept d on e.did = d.dept_id </select> <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from tbl_emp where emp_id = #{empId,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Long"> delete from tbl_emp where emp_id = #{empId,jdbcType=INTEGER} </delete> <insert id="insert" keyColumn="emp_id" keyProperty="empId" parameterType="com.zyl.entity.Emp" useGeneratedKeys="true"> insert into tbl_emp ( emp_id,emp_name,emp_header,emp_job ,emp_salary,did) values (#{empId,jdbcType=INTEGER},#{empName,jdbcType=VARCHAR},#{empHeader},#{empJob,jdbcType=VARCHAR} ,#{empSalary,jdbcType=DECIMAL},#{did,jdbcType=INTEGER}) </insert> <insert id="insertSelective" keyColumn="emp_id" keyProperty="empId" parameterType="com.zyl.entity.Emp" useGeneratedKeys="true"> insert into tbl_emp <trim prefix="(" suffix=")" suffixOverrides=","> <if test="empId != null">emp_id,</if> <if test="empName != null">emp_name,</if> <if test="empJob != null">emp_job,</if> <if test="empSalary != null">emp_salary,</if> <if test="did != null">did,</if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="empId != null">#{empId,jdbcType=INTEGER},</if> <if test="empName != null">#{empName,jdbcType=VARCHAR},</if> <if test="empJob != null">#{empJob,jdbcType=VARCHAR},</if> <if test="empSalary != null">#{empSalary,jdbcType=DECIMAL},</if> <if test="did != null">#{did,jdbcType=INTEGER},</if> </trim> </insert> <!--添加员工--> <insert id="addEmp"> insert into tbl_emp(emp_name,emp_job,emp_salary,did) values(#{empName},#{empJob},#{empSalary},#{did}) </insert> <update id="updateByPrimaryKeySelective" parameterType="com.zyl.entity.Emp"> update tbl_emp <set> <if test="empName != null"> emp_name = #{empName,jdbcType=VARCHAR}, </if> <if test="empJob != null"> emp_job = #{empJob,jdbcType=VARCHAR}, </if> <if test="empSalary != null"> emp_salary = #{empSalary,jdbcType=DECIMAL}, </if> <if test="did != null"> did = #{did,jdbcType=INTEGER}, </if> </set> where emp_id = #{empId,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.zyl.entity.Emp"> update tbl_emp set emp_name = #{empName,jdbcType=VARCHAR}, emp_job = #{empJob,jdbcType=VARCHAR}, emp_salary = #{empSalary,jdbcType=DECIMAL}, did = #{did,jdbcType=INTEGER} where emp_id = #{empId,jdbcType=INTEGER} </update> </mapper>
3.EmpController:
package com.zyl.controlly; import com.zyl.entity.Emp; import com.zyl.mapper.EmpMapper; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpSession; import java.io.InputStream; import java.util.List; /** * @className: EmpController * @author: Zyl * @date: 2024/12/16 15:10 * @Version: 1.0 * @description: */ @Controller //表示控制层--等价servlet @RequestMapping("/emp") public class EmpController { private EmpMapper empMapper; private SqlSession sqlSession; public EmpController() throws Exception{ InputStream resourceAsStream = Resources.getResourceAsStream("mybatis.xml"); //2.创建SqlSessionFactory工厂--获取SqlSession对象 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream); //3.获取SqlSession对象---理解为java与数据库而一次会话 sqlSession = sqlSessionFactory.openSession(); empMapper = sqlSession.getMapper(EmpMapper.class); } @RequestMapping("list") @ResponseBody//表示返回的是json数据 public List<Emp> lsit(){ List<Emp> emp=empMapper.selectAllEmp(); System.out.println(emp); /* int i=10/0;*/ return emp; } @RequestMapping("delete") @ResponseBody public boolean delete(Long id){ int i = empMapper.deleteByPrimaryKey(id); sqlSession.commit(); return i>0; } @RequestMapping("add") @ResponseBody public boolean addEmp (Emp emp, HttpSession session){ int i=empMapper.addEmp(emp); if(i>0){ session.setAttribute("emp",emp); sqlSession.commit(); return true; }else{ return false; } } }
4.前端页面:main.jsp
<%-- Created by IntelliJ IDEA. User: Date: 2024/12/16 Time: 14:21 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>员工管理</title> <script src="/js/jquery-3.7.1.min.js"></script> <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate"> <style> body { font-family: Arial, sans-serif; background-color: #f4f4f9; margin: 0; padding: 0; } .container { width: 80%; margin: 20px auto; background: #fff; padding: 20px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); } table { width: 100%; border-collapse: collapse; margin-top: 20px; } th, td { padding: 10px; text-align: left; border-bottom: 1px solid #ddd; } th { background-color: #f2f2f2; } tr:hover { background-color: #f1f1f1; } a { color: #007bff; text-decoration: none; margin-right: 5px; } a:hover { text-decoration: underline; } img { max-width: 100px; height: auto; } .add-link { display: block; margin-bottom: 20px; } @media (max-width: 768px) { .container { width: 95%; } table { font-size: 14px; } th, td { padding: 8px; } img { max-width: 50px; } } </style> </head> <body οnlοad="loadEmp()"> <div class="container"> <a href="/views/add.jsp" class="add-link">添加员工</a> <table> <thead> <tr> <th>编号</th> <th>姓名</th> <th>职位</th> <th>薪资</th> <th>头像</th> <th>部门号</th> <th>操作</th> </tr> </thead> <tbody id="empBody"> </tbody> </table> </div> <script> function loadEmp() { $.get("/emp/list", function(data) { var str = ""; for (var i = 0; i < data.length; i++) { str += "<tr>"; str += "<td>" + data[i].empId + "</td>"; str += "<td>" + data[i].empName + "</td>"; str += "<td>" + data[i].empJob + "</td>"; str += "<td>" + data[i].empSalary + "</td>"; str += "<td><img src='" + data[i].empHeader + "' alt='头像'></td>"; str += "<td>" + data[i].dept.deptName + "</td>"; str += "<td><a οnclick='deleteEmp(" + data[i].empId + ")'>删除</a><a οnclick='editEmp(" + data[i].empId + ")'>修改</a></td>"; str += "</tr>"; } document.getElementById("empBody").innerHTML = str; }, "json"); } function deleteEmp(id) { if (confirm("确定要删除该员工吗?")) { $.get("/emp/delete", { "id": id }, function(data) { if (data) { loadEmp(); } else { alert("删除失败"); } }, "json"); } } function editEmp(id) { // 这里可以添加编辑功能的实现 alert("编辑员工 ID: " + id); } </script> </body> </html>
3..删除
EmpController层
4.添加
add.jsp:
<%-- Created by IntelliJ IDEA. User: Date: 2024/12/16 Time: 19:07 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script src="/js/jquery-3.7.1.min.js"></script> </head> <body οnlοad="loadDept()"> <form action="post" method="post"> 姓名:<input type="text" name="name" id="name"/><br> 职位:<input type="text" name="job" id="job"/><br> 薪资:<input type="text" name="salary" id="salary"/><br> 部门号:<select id="did" name="did"> </select> <input type="button" value="添加" οnclick="addDept()"/> </form> <script> function loadDept(){ $.get("/dept/list", function(data){ var str = ""; for(var i = 0; i < data.length; i++){ str += "<option value='" + data[i].deptId + "'>" + data[i].deptName + "</option>"; } document.getElementById("did").innerHTML = str; }, "json"); } </script> <script> function addDept(){ var empName = document.getElementById("name").value; var empJob = document.getElementById("job").value; var empSalary = document.getElementById("salary").value; var did = document.getElementById("did").value; $.post("/emp/add", {"empName": empName, "empJob": empJob, "empSalary": empSalary, "did": did}, function(data){ if(data){ alert("添加成功"); location.href = "/views/main.jsp"; } else { alert("添加失败"); } }, "json"); } </script> </body> </html>
DeptMapper:
这一步查询所有的部门是为了添加时,显示信息和设置部门的选择下拉框
package com.zyl.mapper; import com.zyl.entity.Dept; import java.util.List; /** * @author * @description 针对表【tbl_dept】的数据库操作Mapper * @createDate 2024-12-16 11:20:58 * @Entity com.zyl.entity.Dept */ public interface DeptMapper { int deleteByPrimaryKey(Long id); int insert(Dept record); int insertSelective(Dept record); Dept selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(Dept record); int updateByPrimaryKey(Dept record); //定义一个查询所有部门的方法 public List<Dept> selectAllDept(); }
映射文件:DeptMapper.xml
<?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.zyl.mapper.DeptMapper"> <resultMap id="BaseResultMap" type="com.zyl.entity.Dept"> <id property="deptId" column="dept_id" jdbcType="INTEGER"/> <result property="deptName" column="dept_name" jdbcType="VARCHAR"/> <result property="deptLoc" column="dept_loc" jdbcType="VARCHAR"/> </resultMap> <sql id="Base_Column_List"> dept_id,dept_name,dept_loc </sql> <select id="selectByPrimaryKey" parameterType="java.lang.Long" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from tbl_dept where dept_id = #{deptId,jdbcType=INTEGER} </select> <!--定义一个查询所有部门的方法--> <select id="selectAllDept" resultMap="BaseResultMap"> select * from tbl_dept </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Long"> delete from tbl_dept where dept_id = #{deptId,jdbcType=INTEGER} </delete> <insert id="insert" keyColumn="dept_id" keyProperty="deptId" parameterType="com.zyl.entity.Dept" useGeneratedKeys="true"> insert into tbl_dept ( dept_id,dept_name,dept_loc ) values (#{deptId,jdbcType=INTEGER},#{deptName,jdbcType=VARCHAR},#{deptLoc,jdbcType=VARCHAR} ) </insert> <insert id="insertSelective" keyColumn="dept_id" keyProperty="deptId" parameterType="com.zyl.entity.Dept" useGeneratedKeys="true"> insert into tbl_dept <trim prefix="(" suffix=")" suffixOverrides=","> <if test="deptId != null">dept_id,</if> <if test="deptName != null">dept_name,</if> <if test="deptLoc != null">dept_loc,</if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="deptId != null">#{deptId,jdbcType=INTEGER},</if> <if test="deptName != null">#{deptName,jdbcType=VARCHAR},</if> <if test="deptLoc != null">#{deptLoc,jdbcType=VARCHAR},</if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.zyl.entity.Dept"> update tbl_dept <set> <if test="deptName != null"> dept_name = #{deptName,jdbcType=VARCHAR}, </if> <if test="deptLoc != null"> dept_loc = #{deptLoc,jdbcType=VARCHAR}, </if> </set> where dept_id = #{deptId,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.zyl.entity.Dept"> update tbl_dept set dept_name = #{deptName,jdbcType=VARCHAR}, dept_loc = #{deptLoc,jdbcType=VARCHAR} where dept_id = #{deptId,jdbcType=INTEGER} </update> </mapper>
EmpController层
5.注册:
register.jsp:
<%-- Created by IntelliJ IDEA. User: Date: 2024/12/16 Time: 16:03 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script src="/js/jquery-3.7.1.min.js"></script> </head> <body> <form action="post" method="post"> 用户名:<input type="text" name="username" id="username"> 密码:<input type ="text" name="password" id="password"> 年龄:<input type="text" name="age" id="age"> 性别:<input type="text" name="sex" id="sex"> <input type="button" value="注册" οnclick="register()"> <a href="../login.jsp">已有账号,立即登录</a> </form> </body> <script> function register(){ var name = document.getElementById("username").value; var password = document.getElementById("password").value; var userAge = document.getElementById("age").value; var userSex = document.getElementById("sex").value; $.post("/user/register", {"name":name,"password":password,"userAge":userAge,"userSex":userSex},function(data){ if(data){ alert("注册成功") }else { alert("用户名重复") } },"json") } </script> </html>
6.文件上传添加
<%-- Created by IntelliJ IDEA. User: Date: 2024/12/17 Time: 15:54 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form action="/upload" method="post" enctype="multipart/form-data"> 选择文件:<input type="file" name="myfile"/><br> 姓名:<input type="text" name="empName"/><br> 职位:<input type="text" name="empJob"/><br> 薪资:<input type="text" name="empSalary"/><br> 部门号:<input type="text" name="did"/><br> <input type="submit"/> </form> </body> </html>
UploadController:
标签:name,springmvc,org,跳转,视图,emp,jdbcType,import,id From: https://blog.csdn.net/weixin_64574904/article/details/144644703package com.zyl.controlly; import com.zyl.entity.Emp; import com.zyl.mapper.EmpMapper; import com.zyl.utils.UploadUtils; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.InputStream; import java.util.UUID; /** * @className: UploadController * @author: Zyl * @date: 2024/12/17 16:00 * @Version: 1.0 * @description: */ @Controller public class UploadController{ private EmpMapper empMapper; private SqlSession sqlSession; // public String upload2(MultipartFile myfile, Emp emp, HttpServletRequest request) throws Exception{ // //1.获取保存文件的路径 // String realPath = request.getSession().getServletContext().getRealPath("/images"); // //2.根据上面的路径创建文件对象 // File file=new File(realPath); // //3.判断该文件夹是否存在 // if(!file.exists()){ // file.mkdirs(); // } // //4.获取上传文件的名称. 获取登录者ip+登录者id+登录者的时间戳 // String filename = UUID.randomUUID().toString().replace("-","")+myfile.getOriginalFilename(); // //5.把上传的文件保存到指定服务器下的路径。 // File target=new File(realPath+"/"+filename); // myfile.transferTo(target); // System.out.println("上传成功"); // return "/views/main.jsp"; // } public UploadController() throws Exception{ InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("mybatis.xml"); SqlSessionFactory sqlSessionFactory = new org.apache.ibatis.session.SqlSessionFactoryBuilder().build(inputStream); sqlSession = sqlSessionFactory.openSession(); empMapper = sqlSession.getMapper(EmpMapper.class); } @RequestMapping("/upload") public String upload(MultipartFile myfile, Emp emp, HttpServletRequest request) throws Exception{ String path= UploadUtils.uploadToOss(myfile); emp.setEmpHeader(path); empMapper.insert(emp); sqlSession.commit(); return "main"; } }