1.什么是MVC?
MVC就是一个分层架构模式:
2.什么是SpringMVC框架。
springMVC它是spring框架的一个分支,该springMVC框架主要完成的功能是:==接收浏览器的请求响应,对数据进行处理,然后返回页面进行显示== 可以把它理解为和Servlet干的工作是一样的。
3.为什么要使用SpringMVC框架。
4如何使用springmvc
(1)创建一个maven-web工程。
注意: ==现在的web.xml文件写下面的==
<?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">
</web-app>
(2)引入springmvc的依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.15.RELEASE</version>
</dependency>
</dependencies>
(3) 注册DispatcherServlet到web.xml文件上
<servlet>
<servlet-name>DispactherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!--classpath:表示编译后的路径-->
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DispactherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
(4) 创建我们的springmvc配置文件
里面写下面的
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns: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 https://www.springframework.org/schema/context/spring-context.xsd">
<!--包扫描-->
<context:component-scan base-package="com.ykq.controller"/></beans>
(5)创建一个controller类,
@Controller //该注解标记该类为处理层类---类似@WebServlet
public class HelloController {@RequestMapping(value = "/hello01") //把请求路径映射到该方法上。
public String hello01(){
System.out.println("业务处理");return "hello01.jsp"; //响应一个页面
}
}
5.springmvc的运行流程* 1. 客户端发生请求http://localhost:8080/qy151_springmvc01/abc
* 2. 来到tomcat服务器。
* 3. springmvc的前端控制器DipatcherServlet接受所有的请求。
* 4. 查看你的请求地址和哪个@RequestMaping匹配。
* 5. 执行对应的方法。方法会返回一个字符串。springmvc把该字符串解析为要转发的网页。
* 6. 把该字符串经过视图解析器拼接。
* 7. 拿到拼接的地址,找到对应的网页。
* 8. 渲染该网页给客户
6.接受大量的参数
譬如: 表单提交。
封装一个实体类来接受这些参数:
发现接受的参数值乱码:---只能添加过滤器
(1)自己创建编码过滤器. jdk1.8一定要重写init和destory方法 1.9以后可以不写
springmvc写这个过滤器
<filter>
<filter-name>encodingfilter</filter-name>
<filter-class>com.ykq.filter.MyEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>encodingfilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
(2)springmvc提供了一个编码过滤器.
在时间类型的属性上添加一个注解:@DateTimeFormat(pattern = "yyyy-MM-dd")
//yyyy年 MM:月 dd日 24小时制
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date birthday;//出生日期
在springmvc配置文件上开启注解驱动
<!--开启注解驱动-->
<mvc:annotation-driven/>
7.处理静态资源
无法加载图片: 原因:springmvc的前端控制器DispatcherSerlvet也把静态资源拦截器。放行静态资源
<!--放行静态资源:哪些资源为静态资源。css img js html-->
<mvc:default-servlet-handler/>
8.如何把controller数据返回到网页并回显。
回顾: 之前我们讲解servlet时,如何把数据保存并可以在网页上获取该数据。
request: 作用范围: 同一个请求内有效。setAttribute(key,value)
session:作用范围: 同一个会话有效,只要会话不关闭会一直有效。setAttribute(key,value)
网页如何获取保存的数据呢:可以使用EL表达式。${scope.key}
在springmvc中如何保存数据到网页上。
@Controller
@SessionAttributes(value = {"user","user2"}) //设置哪些model的key在session范围
public class HelloController02 {
@RequestMapping("/list")
public String list(HttpServletRequest request){
//查询到一个学生信息。
Student student=new Student(1,"hi","110@qq.com",new Date());
//可以保存到request中,同一个请求
request.setAttribute("s",student);
return "list.jsp"; //转发
}
@RequestMapping("/list2")
public String list2(Model model){ //如果你使用request,你和tomcat容器绑定了。 建议使用Model.
//查询到一个学生信息。
Student student=new Student(1,"halou","110@qq.com",new Date());
//可以保存到model中,同一个请求 和request是一样。
model.addAttribute("s2",student);
return "list.jsp"; //转发
}
//上面讲解都是保存request范围。如何保存到session范围。
@RequestMapping("/list3")
public String list3(HttpSession session){
Student student=new Student(3,"郭家昊","120@qq.com",new Date());
session.setAttribute("user",student);
return "list.jsp"; //转发
}
@RequestMapping("/list4")
public String list4( Model model){
Student student=new Student(3,"dyt2","120@qq.com",new Date());
Student student2=new Student(3,"dyt~~~~","120@qq.com",new Date());
model.addAttribute("user",student);
model.addAttribute("user2",student2); //默认在request范围
return "list.jsp"; //转发
}
}
9.如何使用重定向跳转
在方法的返回字符串的内容时加上redirect:
@RequestMapping("list5")
public String list5(){
System.out.println("!!!!!!!!!!!!!!!!!");
return "redirect:list.jsp"; //当springmvc看到你返回的字符串钟含有redirect:时 它认为你要进行重定向跳转
}
springmvc返回json数据
(1)什么时候需要返回json数据。
异步请求时,ajax请求时。
(2)之前在servlet时如何返回json数据呢?
借助了Fastjson---手动把java对象转换为json格式的数据,并使用out.print(json)输出json数据。 关闭out对象。
springmvc如何返回json数据呢!
(1)内置了一个jar. jackson的jar包
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.2.2</version>
</dependency>
(2) 在controller返回的数据类型变成javabean对象。
@RequestMapping("json01")
@ResponseBody //作用:把java对象转换为json对象
public List<Student> json01(){ //这里返回的类型为java对象。 之前都是返回字符串
List<Student> list=new ArrayList<Student>();
list.add(new Student(1,"dyt","2300316070@qq.com",new Date()));
list.add(new Student(2,"刘德华","110@qq.com",new Date()));
list.add(new Student(3,"黎明","210@qq.com",new Date()));
list.add(new Student(4,"张学友","220@qq.com",new Date()));
return list; //当中json
}
(3) 访问该路径
上面返回的时间类型的json数据显示的为毫秒,正常情况应该显示时间格式。如何解决。
10.springmvc的全局异常处理类
全局异常处理类的作用: 当controller发生异常,则有全局异常类来处理并执行相应的处理方法。
(1)如何使用全局异常处理类
[1] 创建一个异常类: @ControllerAdvice注解
@ControllerAdvice //表示该为类controller的异常处理类
public class MyExceptinHandle {
@ExceptionHandler(value = RuntimeException.class) //当发生RuntimeException就会触发该方法
public String error(){
return "error.jsp";
}@ExceptionHandler(value = Exception.class) //当发生Exception就会触发该方法
public String error2(){
return "error2.jsp";
}
}
[2] 保证springmvc能够扫描到该类。
如果是ajax请求返回的应该是一个json数据。
11.springmvc拦截器
过滤器: 过滤掉某些资源,
拦截器只会拦截controller层的资源路径。
如何使用拦截器:
(1)创建一个类,并实现HandlerInterceptor
public class MyInterceptor implements HandlerInterceptor {
//拦截器的处理方法。
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("经过了该拦截器");
return true;//true:表示拦截器放行 false:不放行
}
}
(2) 把该类注册到springmvc配置文件上。
<!--拦截器的配置-->
<mvc:interceptors>
<mvc:interceptor>
<!--mapping:哪些路径需要经过拦截器
/**: 表示n层路径
/*:表示一层路径
-->
<mvc:mapping path="/**"/>
<!--exclude-mapping:设置不经过该拦截的路径-->
<mvc:exclude-mapping path="/list2"/>
<mvc:exclude-mapping path="/list3"/>
<!--bean表示你自定义的拦截器类路径-->
<bean class="com.ykq.interceptor.MyInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
12.文件上传到本地服务器。
(1)文件上传的依赖。
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
(2) 创建一个页面
<html>
<head>
<title>Title</title>
</head>
<body>
<%--
method: 提交方式 文件上传必须为post提交。
enctype:默认application/x-www-form-urlencoded 表示提交表单数据
multipart/form-data:可以包含文件数据input的类型必须为file类型,而且必须有name属性
--%>
<form method="post" action="upload01" enctype="multipart/form-data">
<input type="file" name="myfile"/>
</form>
</body>
</html>
(3)在springmvc中配置文件上传解析器
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--这里的单位为字节10M*1024K*1024-->
<property name="maxUploadSize" value="10485760"/>
</bean>
(3)创建upload01接口方法
@RequestMapping("/upload01")
public String upload01(MultipartFile myfile, HttpServletRequest request) throws Exception{
//(1)得到本地服务目录的地址
String path = request.getSession().getServletContext().getRealPath("upload");
//(2)判断该目录是否存在
File file=new File(path);
if(!file.exists()){
file.mkdirs();
}
//(3)//把myfile保存到本地服务中某个文件夹下。 缺点:文件的名称
String filename= UUID.randomUUID().toString().replace("-","")+myfile.getOriginalFilename();
File target=new File(path+"/"+filename);
myfile.transferTo(target); //把myfile转移到目标目录下
return "";
}elementui+vue+axios完成文件上传
<html>
<head>
<title>Title</title>
<!--引入element得css样式-->
<link type="text/css" rel="stylesheet" href="css/index.css"/>
<!--引入vue得js文件 这个必须在element之前引入-->
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript" src="js/qs.min.js"></script>
<script type="text/javascript" src="js/axios.min.js"></script>
<!--element得js文件-->
<script type="text/javascript" src="js/index.js"></script>
</head>
<body>
<div id="app">
<%--action:文件上传的路径--%>
<el-upload
class="avatar-uploader"
action="/upload02"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</div>
</body>
<script>
var app=new Vue({
el:"#app",
data:{
imageUrl:"",
},
methods:{
//上传成功后触发的方法
handleAvatarSuccess(res, file) {
this.imageUrl=res.data;
},
//上传前触发的方法
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isPNG = file.type === 'image/png';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!');
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
}
return isJPG && isLt2M;
}
}
})
</script>
<style>
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409EFF;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
</style>
</html>
(2)后台的接口
@RequestMapping("/upload02")
@ResponseBody
public Map upload02(MultipartFile file, HttpServletRequest request) {
try {
//1.获取上传到服务器的文件夹路径
String path = request.getSession().getServletContext().getRealPath("upload");
File file1 = new File(path);
//判断指定的目录是否存在
if (!file1.exists()) {
file1.mkdirs();
}
//设置上传后的文件名称
String filename = UUID.randomUUID().toString().replace("-", "") + file.getOriginalFilename();
File target = new File(path+"/"+filename);
file.transferTo(target);
Map map=new HashMap();
map.put("code",2000);
map.put("msg","上传成功");
//通过访问服务器地址来访问图片.
map.put("data","http://localhost:8080/upload/"+filename);
return map;
}catch (Exception e){
e.printStackTrace();
}
Map map=new HashMap();
map.put("code",5000);
map.put("msg","上传失败");
return map;
}
上传到oss阿里云的服务器
上传到本地服务器的缺点: 如果搭建集群,导致文件无法在集群中共享。 它的解决方法就是把文件专门上传到一个文件服务器上,这些tomcat服务器都操作同一个文件服务器。
申请oss文件服务。
在oss界面上操作文件上传
*(1)创建bucket容器
可以在该bucket中通过网页面板的形式操作该bucket.
但是实际开发我们应该通过java代码往bucket中上传文件。
申请阿里云的密钥
普通的文件上传到OSS文件服务器
(1)引入阿里云的OSS依赖
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
(2)代码的书写。
@RequestMapping("/upload03")
public String upload03(MultipartFile myfile,HttpServletRequest request){
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
String endpoint = "oss-cn-hangzhou.aliyuncs.com";//LTAI78XQAZq2s5Rv
//qdyZxR0x4LoUpTVbuyvCGdcrhEyw7H
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
String accessKeyId = "自己的";
String accessKeySecret = "自己的";
// 填写Bucket名称,例如examplebucket。
String bucketName = "名字随便起";
//你上传到oss后的名字 会根据日期帮你创建文件夹。
Calendar calendar=Calendar.getInstance();
String objectName =calendar.get(Calendar.YEAR)+"/"+(calendar.get(Calendar.MONTH)+1)+"/"+
calendar.get(Calendar.DATE)+"/"+UUID.randomUUID().toString().replace("-","")+
myfile.getOriginalFilename();// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);try {
InputStream inputStream =myfile.getInputStream();
// 创建PutObject请求。
ossClient.putObject(bucketName, objectName, inputStream);
} catch (Exception oe) {} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
//https://qy151.oss-cn-hangzhou.aliyuncs.com/2022/6/10/20d3d7e6b5bb455cb548675501f7270fgdnj.jpg
String url="https://"+bucketName+"."+endpoint+"/"+objectName;
request.setAttribute("imgUrl",url);
return "success.jsp";
}
elementui 异步上传OSS服务器
(1)前端
<head>
<title>Title</title>
<!--引入element得css样式-->
<link type="text/css" rel="stylesheet" href="css/index.css"/>
<!--引入vue得js文件 这个必须在element之前引入-->
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript" src="js/qs.min.js"></script>
<script type="text/javascript" src="js/axios.min.js"></script>
<!--element得js文件-->
<script type="text/javascript" src="js/index.js"></script>
</head>
<body>
<div id="app">
<%--action:文件上传的路径--%>
<el-upload
class="avatar-uploader"
action="/upload04"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</div>
</body>
<script>
var app=new Vue({
el:"#app",
data:{
imageUrl:"",
},
methods:{
//上传成功后触发的方法
handleAvatarSuccess(res, file) {
this.imageUrl=res.data;
},
//上传前触发的方法
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isPNG = file.type === 'image/png';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!');
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
}
return isJPG && isLt2M;
}
}
})
</script><style>
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409EFF;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
</style>
</html>
(2)后端工具:
public class OSSUtils {
public static String upload(MultipartFile myfile){
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
String endpoint = "oss-cn-hangzhou.aliyuncs.com";//LTAI78XQAZq2s5Rv
//qdyZxR0x4LoUpTVbuyvCGdcrhEyw7H
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
String accessKeyId = "LTAI78XQAZq2s5Rv";
String accessKeySecret = "qdyZxR0x4LoUpTVbuyvCGdcrhEyw7H";
// 填写Bucket名称,例如examplebucket。
String bucketName = "qy151";
//你上传到oss后的名字 会根据日期帮你创建文件夹。
String objectName =fileName(myfile);
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);try {
InputStream inputStream =myfile.getInputStream();
// 创建PutObject请求。
ossClient.putObject(bucketName, objectName, inputStream);
} catch (Exception oe) {} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
//https://qy151.oss-cn-hangzhou.aliyuncs.com/2022/6/10/20d3d7e6b5bb455cb548675501f7270fgdnj.jpg
String url="https://"+bucketName+"."+endpoint+"/"+objectName;
return url;
}//获取上传到oss后的名字
private static String fileName(MultipartFile myfile){
Calendar calendar=Calendar.getInstance();
String name=calendar.get(Calendar.YEAR)+"/"+(calendar.get(Calendar.MONTH)+1)+"/"+
calendar.get(Calendar.DATE)+"/"+ UUID.randomUUID().toString().replace("-","")+
myfile.getOriginalFilename();return name;
}
}
(3) controller接口
@RequestMapping("/upload04")
@ResponseBody
public Map upload04(MultipartFile file) {
try {
String url = OSSUtils.upload(file);
Map map = new HashMap();
map.put("code", 2000);
map.put("msg", "上传成功");
map.put("data", url);
return map;
} catch (Exception e) {
e.printStackTrace();
}
HashMap map = new HashMap();
map.put("code", 5000);
map.put("msg", "上传失败");
return map;
}
保存用户信息--头像(1)前端的布局
<head>
<title>Title</title>
<!--引入element得css样式-->
<link type="text/css" rel="stylesheet" href="css/index.css"/>
<!--引入vue得js文件 这个必须在element之前引入-->
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript" src="js/qs.min.js"></script>
<script type="text/javascript" src="js/axios.min.js"></script>
<!--element得js文件-->
<script type="text/javascript" src="js/index.js"></script>
</head>
<body>
<div id="app">
<el-form label-width="80px" :model="userForm">
<el-form-item label="头像:">
<el-upload
class="avatar-uploader"
action="/uploadAvatar"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</el-form-item>
<el-form-item label="账号:">
<el-input v-model="userForm.name"></el-input>
</el-form-item>
<el-form-item label="密码:">
<el-input v-model="userForm.pwd"></el-input>
</el-form-item>
<el-form-item label="地址:">
<el-input v-model="userForm.address"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit">查询</el-button>
</el-form-item>
</el-form>
</div>
</body>
<script>
var app=new Vue({
el:"#app",
data:{
userForm:{},
imageUrl:""
},
methods:{
handleAvatarSuccess(result,file){
this.imageUrl=result.data;
//为表单对象添加头像地址的属性
this.userForm.avatarUrl=this.imageUrl;
},
//提交
onSubmit(){
axios.post("/addUser",this.userForm).then(function(result){});
},
//上传前触发的方法
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isPNG = file.type === 'image/png';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!');
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
}
return isJPG && isLt2M;
}
}
})
</script>
<style>
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409EFF;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
</style>
</html>
(2)后台代码
@Controller
public class UserController {@RequestMapping("uploadAvatar")
@ResponseBody
public CommonResult uploadAvatar(MultipartFile file) {
try {
String avatar = OSSUtils.upload(file);
return new CommonResult(2000, "上传成功", avatar);
} catch (Exception e) {
e.printStackTrace();
}
return new CommonResult(5000, "失败", null);
}//@RequestBody:把请求体中json数据转换为java对象
@RequestMapping("/addUser")
@ResponseBody
public CommonResult addUser(@RequestBody User user){
System.out.println(user);
//TODO 调用dao完成保存到数据库--省略
return new CommonResult(2000,"成功",null);
}
}
程序的耦合
耦合性(Coupling),也叫耦合度,是对模块间关联程度的度量。耦合的强弱取决于模块间接口的复杂性、调用模块的方式以及通过界面传送数据的多少。模块间的耦合度是指模块之间的依赖关系,包括控制关系、调用关系、数据传递关系。模块间联系越多,其耦合性越强,同时表明其独立性越差( 降低耦合性,可以提高其独立性)。耦合性存在于各个领域,而非软件设计中独有的,但是我们只讨论软件工程中的耦合。在软件工程中,耦合指的就是就是对象之间的依赖性。对象之间的耦合越高,维护成本越高。因此对象的设计应使类和构件之间的耦合最小。软件设计中通常用耦合度和内聚度作为衡量模块独立程度的标准。划分模块的一个准则就是高内聚低耦合。
它有如下分类:
(1)内容耦合。当一个模块直接修改或操作另一个模块的数据时,或一个模块不通过正常入口而转入另一个模块时,这样的耦合被称为内容耦合。内容耦合是最高程度的耦合,应该避免使用之。
(2)公共耦合。两个或两个以上的模块共同引用一个全局数据项,这种耦合被称为公共耦合。在具有大量公共耦合的结构中,确定究竟是哪个模块给全局变量赋了一个特定的值是十分困难的。
(3) 外部耦合 。一组模块都访问同一全局简单变量而不是同一全局数据结构,而且不是通过参数表传递该全局变量的信息,则称之为外部耦合。
(4) 控制耦合 。一个模块通过接口向另一个模块传递一个控制信号,接受信号的模块根据信号值而进行适当的动作,这种耦合被称为控制耦合。
(5)标记耦合 。若一个模块 A 通过接口向两个模块 B 和 C 传递一个公共参数,那么称模块 B 和 C 之间存在一个标记耦合。
(6) 数据耦合。模块之间通过参数来传递数据,那么被称为数据耦合。数据耦合是最低的一种耦合形式,系统中一般都存在这种类型的耦合,因为为了完成一些有意义的功能,往往需要将某些模块的输出数据作为另一些模块的输入数据。
(7) 非直接耦合 。两个模块之间没有直接关系,它们之间的联系完全是通过主模块的控制和调用来实现的。
总结:耦合是影响软件复杂程度和设计质量的一个重要因素,在设计上我们应采用以下原则:如果模块间必须存在耦合,就尽量使用数据耦合,少用控制耦合,限制公共耦合的范围,尽量避免使用内容耦合。
内聚与耦合:内聚标志一个模块内各个元素彼此结合的紧密程度,它是信息隐蔽和局部化概念的自然扩展。内聚是从功能角度来度量模块内的联系,一个好的内聚模块应当恰好做一件事。它描述的是模块内的功能联系。耦合是软件结构中各模块之间相互连接的一种度量,耦合强弱取决于模块间接口的复杂程度、进入或访问一个模块的点以及通过接口的数据。 程序讲究的是低耦合,高内聚。就是同一个模块内的各个元素之间要高度紧密,但是各个模块之间的相互依存度却要不那么紧密。内聚和耦合是密切相关的,同其他模块存在高耦合的模块意味着低内聚,而高内聚的模块意味着该模块同其他模块之间是低耦合。在进行软件设计时,应力争做到高内聚,低耦合。
解决办法IOC控制反转
控制反转(Inversion of Control,缩写为IoC),是面向对象编程中的一种设计原则,可以用来减低计算机代码之间的耦合度。其中最常见的方式叫做依赖注入(Dependency Injection,简称DI),还有一种方式叫“依赖查找”(Dependency Lookup)。通过控制反转,对象在被创建的时候,由一个调控系统内所有对象的外界实体将其所依赖的对象的引用传递给它。也可以说,依赖被注入到对象中。
==使用对象的时候不再是我们直接new,而是将创建对象的权利交给框架中的核心容器IOC,需要使用对象的时候直接从容器中获取。==
IoC的思想早就出现了,但是没有一个具体的实现,大家都是各自根据这个思想去写代码(自己去创建工厂)。后来有一个大师 Rod Johnson(Spring Framework创始人,著名作者。 Rod在悉尼大学不仅获得了计算机学位,同时还获得了音乐学位。更令人吃惊的是在回到软件开发领域之前,他还获得了音乐学的博士学位。),写了一个框架,将IoC思想具体的实现了,这个框架后来起了个名字叫做 Spring。(因为在这之前 大家都是用hibernate这个框架,这个框架中文名字叫做冬眠,并且这个框架比较笨重,耦合比较高。Rod Johnson写的框架就是用来解决类似于hibernate高耦合的问题 ,所以他将自己框架的名字命名为 Spring 告诉全世界 冬天过去了 春天来了)。
如何使用spring.
(1)引入相关的依赖
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.15.RELEASE</version>
</dependency>
</dependencies>
(2)创建Spring的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--表示一个类交于spring容器来创建
id:bean的唯一标识。
class: 类的全路径
-->
<bean id="userDao" class="com.aaa.UserDao"></bean>
</beans>
(3)创建一个Dao类
public interface IUserDao {
public void show();
}
public class UserDao implements IUserDao {public void show(){
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
}
}
(4)测试
public class Test01 {
public static void main(String[] args) {
//读取spring配置文件
ApplicationContext app=new ClassPathXmlApplicationContext("application.xml");
//获取bean对象 多态.
IUserDao userDao = (IUserDao) app.getBean("userDao");
userDao.show();
}
}
BeanFactory和ApplicationContext的区别
Spring容器顶层接口:获取Bean对象;管理类和类之间的关系(依赖关系)BeanFactory由org.springframework.beans.factory.BeanFactory接口定义 BeanFactory是工厂模式(Factory pattern)的实现,是IOC容器的核心接口,它的职责包括:实例化、定位、配置应用程序中的对象及建立这些对象间的依赖。
BeanFactory接口包含以下基本方法:
containsBean(String beanName) 判断工厂中是否包含给定名称的bean定义,若有则返回true。
Object getBean(String str) 返回给定名称注册的bean实例。根据bean的配置情况,如果是singleton模式将返回一个共享实例,否则将返回一个新建的实例,如果没有找到指定bean,该方法可能会抛出异常。
Object getBean(String, Class) 返回以给定名称注册的bean实例,并转换为给定class类型
Class getType(String name) 返回给定名称的bean的Class,如果没有找到指定的bean实例,则排除NoSuchBeanDefinitionException异常
boolean isSingleton(String) 判断给定名称的bean定义是否为单例模式
String[] getAliases(String name) 返回给定bean名称的所有别名
ApplicationContext接口
是基于BeanFactory之上的,提供了应用程序框架服务,扩展的新功能如下:提供国际化的支持资源访问,如URL和文件 事件传递载入多个配置文件等 实现类常见有三个
ClassPathXmlApplicationContext:-classpath路径加载xml文件的
FileSystemXmlApplicationContext:基于项目根路径进行加载xml文件的
AnnotationConfigApplicationContext:基于注解的配置。基于类书写的配置。
public class TestBeanFactoryAndApplication {
// public static void main(String[] args) {
// //读取配置文件
// ClassPathResource resource = new ClassPathResource("application.xml");
// //解析配置文件
// XmlBeanFactory factory = new XmlBeanFactory(resource);
// Object userDao = factory.getBean("userDao"); //拿到哪个bean时才会调用构造函数创建该bean.
//
// //当使用到bean对象时,spring才会帮你创建.
// Object people = factory.getBean("people");
// }
public static void main(String[] args) {
//在加载spring容器时,spring会把配置文件中所有的bean创建好。
ApplicationContext app=new ClassPathXmlApplicationContext("application.xml");
}
}
BeanFactory和ApplicationContext区别: BeanFactory 才是 Spring 容器中的顶层接口。
ApplicationContext 是它的子接口。
单例模式下创建对象的时间点不一样:
ApplicationContext:(饿汉模式)只要一读取配置文件,马上就会创建配置文件中配置的对象。
BeanFactory:(懒汉模式)什么时候getBean("id"),也就是说当根据id获取对象时,才会创建。
获取bean的方式
A 通过bean.xml文件中bean标签的id的值获取bean(使用默认构造方法)
IUserDao iUserDao= (IUserDao) app.getBean("userDao");
//根据bean的id获取Bean对象,强制转换.
B 通过类型去获取
IUserDao userDao = app.getBean(IUserDao.class); //通过类型获取bean对象。
确保bean的类型是唯一的 不然会报错:org.springframework.beans.factory.NoUniqueBeanDefinitionException
C 通过 id + 类型去获取
IUserDao userDao = app.getBean("userDao2", IUserDao.class);
bean的作用范围:
bean对象的作用范围调整需要配置scope属性,设置单例还是多例(只针对ApplicationContext接口来说,默认是单例的)
单例:---无论创建多少次对象 他们始终指向同一个实例。
scope:常用 singleton,prototype
singleton:单例的(默认值)当加载配置文件时,就会创建对象。
prototype:多例的(当getBean时才会创建对象)
request:作用于请求范围---同一个那么使用bean同一个。
session:作用于会话范围---同一个会话