SpringMVC框架--个人笔记步骤总结

一、步骤

1.创建工程

2.加入springmvc依赖--pom.xml

<!--springmvc依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>


<!--lombok依赖-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
<!--servlet依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<!--jackson依赖:字符串转换-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>

3.创建springmvc的配置文件

如果没有证明没有引入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"
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">


</beans>

<?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="Index of /schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd Index of /schema/context https://www.springframework.org/schema/context/spring-context.xsd Index of /schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">

<!--包扫描-->

<context:component-scan base-package="com.wjy.controller"/>

<!--开启注解驱动-->

<mvc:annotation-driven/>

<!--视图解析-->

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix" value="/views/"/>

<property name="suffix" value=".jsp"/>

</bean>

</beans>

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="Java EE: XML Schemas for Java EE Deployment Descriptors http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"

version="4.0">

</web-app>

<?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">

    <!--注册DispatcherServlet-->
    <servlet>
        <servlet-name>springmvc01</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映射 /表示任意路径 -->
    <servlet-mapping>
        <servlet-name>springmvc01</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

5.创建控制层处理类

6.部署tomcat并访问

二、

1.流程

1.客户端发送请求:http://localhost:8080/hello

2.来到tomcat服务器

3.springmvc的前端控制器DipatcherServlet接受所有的请求

4.查看你的请求地址和哪个@RequesMaping匹配。

5.执行对应的方法。方法返回一个字符串。

6.springmvc把该字符串解析【视图解析器】为要转发的网页。把该字符串经过视图解析器拼接。/prefix/字符串.后缀

7.拿到拼接的地址,找到对应的网页。

8.渲染该网页给客户。

2.springmvc接收参数

2.1接收少量参数

比如删除时,传递一个参数

2.2接收大量参数

表单提交的数据--大量数据,我们可以封装到一个类中。

控制层代码

3.解决中文乱码问题

只能使用过滤器

3.1第一种方式

自己定义时使用的servlet依赖
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>

package com.wjy.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter("/*")
public class EncodingFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        chain.doFilter(request,response);
    }

    public void destroy() {

    }
}

3.2第二种--web.xml

使用spring提供的编码过滤器

<!--注册编码过滤器-->

<filter>

<filter-name>encodingFilter</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>

<init-param>

<param-name>forceRequestEncoding</param-name>

<param-value>true</param-value>

</init-param>

<init-param>

<param-name>forceResponseEncoding</param-name>

<param-value>true</param-value>

</init-param>

</filter>

<filter-mapping>

<filter-name>encodingFilter</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

4.处理日期类

5.处理静态资源--springmvc.xml

<!--放行静态资源:只处理servlet请求,其他的请求不会经过springmvc-->
<mvc:default-servlet-handler/>

6.小测试

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String username;
    private String password;
// 日期格式转换
    @DateTimeFormat(pattern = "yyyy-MM-dd")
//日期显示时间戳
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")//json的格式
    private Date birthday;
}

搭建好上面的框架后(一、步骤的内容)写控制处理类的内容--关于登录

@Controller
public class LoginController {
    @RequestMapping("/g")//跳转的位置
    public String login(User user){
        if ("admin".equals(user.getUsername())&&"123".equals(user.getPassword())){
            return "success";//符合要求--经过视图解析器(转发):/views/success.jsp
        }
        return "redirect:/login.jsp";//重定向跳转--且不经过视图解析器
    }
}

三、

1. 控制层如何保存数据到页面

Servlet保存数据可以使用四大域对象:PageContext、Request、Session、Appliaction

request.setAttribute(key,value);//存放数据到request中

request.getAttribute(key);或者${key}//获取request对象中保存的数据

第一种:先加入session依赖才能使用

<!--servlet依赖-->

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>

第二种:springmvc封装好的,直接加入注解使用

总结:

spring保存数据可以像之前servlet保存数据一样。也可以使用model类对象保存

model类中保存数据默认作用域request,设置作用域为session。@SessionAttributes(value={"key"})

2. springmvc返回json数据

1.ajax异步请求时需要响应json数据

实现ajax的方式:①jquery②axios

2.servlet之前响应json数据的步骤:

①引入fastjson依赖

②JSON.toJsonString(java对象)//把java对象转化为json字符串

③out.print(json数据)

④out.flush();out.close();

3.springmvc响应json数据

1.引入jackson依赖

2.在controller方法上使用@ResponseBody:java对象转化为json字符串

3.该方法返回类型java对象

①引入依赖jackson

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>

 @RequestMapping("/ajax01")
    @ResponseBody//把该方法返回的java对象转化为json字符串--jackson
    public User ajax01(){
        User user = new User("wjy","123456",new Date());
        return user;
    }

    @RequestMapping("/ajax02")
    @ResponseBody
    public List<User> ajax02(){
        ArrayList<User> users = new ArrayList<User>();
        users.add(new User("王佳瑶","1203",new Date()));
        users.add(new User("高元浩","0906",new Date()));
        return users;
    }

2.1日期显示时间戳

// 日期格式转换
@DateTimeFormat(pattern = "yyyy-MM-dd")
//日期显示时间戳,timezone表示时区,GMT+8表示东八区(中国)
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")//json的格式
private Date birthday;

3. springmvc全局异常处理

当controller出现异常时,全部交于springmvc的全局异常处理类解决

@ControllerAdvice//控制层的异常处理
public class MyGlobeExceptionHandler {
    //当控制层发生RuntimeException异常类型时交于该方法处理
    @ExceptionHandler(value = RuntimeException.class)
    public String my01(RuntimeException e){//把异常处理的对象交于该方法的参数
        System.out.println("发生了运行时异常");
        return "fail";
    }

    //当控制层发生Exception异常类型时交于该方法处理
    @ExceptionHandler(value = Exception.class)
    public String my02(Exception e){//把异常处理的对象交于该方法的参数
        System.out.println("发生了Exception时异常");
        return "fail";
    }
}
    @RequestMapping("/list01")
    public String list01(HttpSession session,int id) throws Exception {
        //如果上面的异常处理类只有一个Exception异常不管这里有什么异常它都会执行
        //Exception所有异常的父类
        if(id==1){//等于1时会输出第一个异常
            int c=10/0;
        }else if(id==2){//输出第二个异常
            throw new Exception("~~~~~~~~");
        }
        //保存数据到session
        session.setAttribute("name","王五");
        return "redirect:/views/main.jsp";
    }

3.扫描异常处理类

<!--com.wjy:扫描该包以及该包下的子包(范围广)-->
<context:component-scan base-package="com.wjy"/>
<!--扫描多个包之间使用逗号隔开-->
<context:component-scan base-package="com.wjy.Controller,com.wjy.handle"/>

4. springmvc拦截器

之前使用filter过滤,拦截不符合要求的一切请求资源

拦截器:拦截器只会拦截controller层的资源

4.1创建一个拦截器

public class MyInterceptor implements HandlerInterceptor {
    //前缀拦截器--Boolean。如果返回true允许放行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception{
        System.out.println("拦截器");
        return false;
    }
}

4.2配置拦截规则

<!--配置拦截器规则-->
<mvc:interceptors>
<mvc:interceptor>
<!--mapping:拦截的规则/**:表示多层路径-->
<mvc:mapping path="/**"/>
<!--exclude-mapping:不会被拦截的路径-->
<mvc:exclude-mapping path="/g"/>
<!--bean:表示自定义的拦截器的路径-->
<bean class="com.wjy.interceptor.MyInterceptor"/>
</mvc:interceptor>


</mvc:interceptors>

5.restful风格

@ResController:控制层类(表示该类中所有的方法返回的都是json数据)

@GetMapping():只处理get请求方式(一般处理查询请求)

@PostMapping():添加 (使用Post发送请求)

@DeleteMapping():删除

@PutMapping():修改

@RequestBody:把json字符串转化为java对象,使用在方法的参数上

四、文件上传

1.引入上传的依赖

<!--文件上传依赖-->

<dependency>

<groupId>commons-fileupload</groupId>

<artifactId>commons-fileupload</artifactId>

<version>1.4</version>

</dependency>

2.配置文件上传的拦截器

<!--文件上传解析器 id:必须为multipartResolver-->

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

<!--设置文件上传的大小 单位为byte字节 1M=1024kb=1024b 10*1024*1024-->

<property name="maxUploadSize" value="10485760"/>

<!--设置编码-->

<property name="defaultEncoding" value="utf-8"/>

</bean>

3.完成上传文件的代码

<%--表单: 提交方式必须为post enctype编码:multipart/form-data文件编码--%>

<form method="post" action="/upload" enctype="multipart/form-data">

<%--input必须设置文件文件框 而且必须起名称--%>

选择上传的文件:<input type="file" name="myfile"/><br>

<input type="submit" value="上传"/>

</form>

1.本地上传

@Controller

public class UploadController {

/**

*

* @param myfile 接受你上传的文件对象信息封装到该类。该类中可以获取上传文件的信息。比如:文件名 文件大小 文件后缀等

* 这个名称必须为文件上传表单的文件框的名称一致

* @return

*/

@PostMapping("/upload")

public String upload(MultipartFile myfile, HttpServletRequest request) throws IOException {

//获取tomcat上下文中的指定目录的路径

String realPath = request.getSession().getServletContext().getRealPath("/upload");

//根据上面的路径创建一个文件对象

File file=new File(realPath);

//如果没有该目录则创建

if (!file.exists()) {

file.mkdirs();

}

//把上传的文件转移到upload目录下--重名覆盖了

String uuid = UUID.randomUUID().toString().replace("-", "");

File target=new File(realPath+"/"+(uuid+myfile.getOriginalFilename()));

myfile.transferTo(target);

return "success";

}

}

2.Oss服务器上传

  1. 如果项目搭建了集群。那么导致文件数据无法共享。
  2. 如果项目的target删除了。导致文件数据丢失。

引入oss的依赖[jdk8]

<dependency>

<groupId>com.aliyun.oss</groupId>

<artifactId>aliyun-sdk-oss</artifactId>

<version>3.15.1</version>

</dependency>

代码

 @PostMapping("/upload2")
    public String upload(MultipartFile file){
        // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
        String endpoint = "oss-cn-beijing.aliyuncs.com";
        // 填写Bucket名称,例如examplebucket。
        String bucketName = "qy174-wjy-01";
        //上传到oss后的名字
        String objectName = UUID.randomUUID().toString().replace("-","")+file.getOriginalFilename();
        // 创建OSSClient实例。
        /**
         * String endpoint,自己的endpoint
         * String accessKeyId, 自己的id
         * String secretAccessKey自己的密钥
         */
        String accessKeyId="LTAI5tGhFRyaoCHa7jm7Mjzx";
        String secretAccessKey="dkOIOg15IDUJZ2LJCOU4Tz7arnGfOC";
        OSS ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,secretAccessKey);

        try {
            InputStream inputStream = file.getInputStream();
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
             //上传的地址
            String path="https://"+bucketName+"."+endpoint+"/"+objectName;
            return path;
        } catch (Exception oe) {
        }
        finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return "失败";
    }
<%-- 添加对话的开始--%>
<el-dialog title="添加" :visible.sync="addDialogForm">
    <el-form ref="addForm" :rules="rules" :model="addForm" label-width="80px">
        <el-form-item label="广告标题" prop="title">
            <el-input v-model="addForm.title"></el-input>
        </el-form-item>
        <el-form-item label="广告照片" prop="imageUrl">
         <%--   action:文件上传的路径
            show-file-list:列表的数列值
                on-success:上传成功触发的函数
                before-upload:上传前触发的函数--%>
            <el-upload
                    class="avatar-uploader"
                    action="/upload"
                    :show-file-list="false"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                    <%-- v-model="addForm.imageUrl"--%>
            >
                <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>
            <el-button type="primary" @click="addSubmit('addForm')">提交</el-button>
            <el-button @click="addDialogForm=false">取消</el-button>
        </el-form-item>
    </el-form>
</el-dialog>
<%-- 添加对话的结束--%>

 //上传后的地址
            handleAvatarSuccess(res, file) {
                this.imageUrl = res;
               /* let reader = new FileReader()
                reader.readAsDataURL(file.raw)
                reader.onload = () => {
                    this.imageUrl  = reader.result
                }*/
            },
            //上传前触发的函数
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },


            //点击添加--打开对话框
            showAdd(){
                this.addDialogForm=true;
            },
            //确认添加
            addSubmit(formName){
                this.$refs[formName].validate((valid)=> {
                    if (valid) {
                        this.addForm.imageUrl = this.imageUrl;
                        this.addDialogForm = false;
                        axios.post("insertLunBo", this.addForm).then(result => {
                            if (result.data.code === 200) {
                                this.$message.success(result.data.msg);
                                this.addForm = {};
                                this.loadMessage();
                            } else {
                                this.$message.error(result.data.msg);
                            }
                        })
                    }
                })
            },

  • 20
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值