springMVC学习笔记

x33g5p2x  于11个月前 转载在 Spring  
字(11.6k)|赞(0)|评价(0)|浏览(127)

前言:笔记是参考B站up主遇见狂神说,图片、代码都是哦。因为最近特别喜欢他教的课程,所以就一边跟着学习,一边在blog写笔记~(图片、代码来源狂神说Java,侵权必删!)
狂神说Java学习路线B站网站:https://www.bilibili.com/read/cv5702420

@Component   组件
@Service    service层
@Controller   controller层
@Repository   dao层

SpringMCV报404问题

可能遇到的问题:访问出现404或者500,排除步骤:
1.查看控制台输出,看一下是不是缺少了什么jar包。
2.如果jar包存在,显示无法输出,就在IDEA的项目发布中,添加lib依赖。
3.重启Tomcat即可解决!

SpringMVC项目搭建

使用springMVC必须配置的三大件:
处理器映射器、处理器适配器、视图解析器。
通常,我们只需要手动配置视图解析器,而处理器映射器和处理器适配器只需要开启注解驱动即可!

1.新建一个web项目

2.pom依赖(pom.xml)

<!--导入依赖-->
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.18</version>
        </dependency>
    </dependencies>

3.导入相关jar包

4.编写web.xml,注册DispatcherServlet

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

    <!--配置DispatchServlet:这个是springMVC的核心;请求分发器,前端控制器-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--DispatcherServlet要绑定spring的配置文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <!--启动级别 :1-->
        <load-on-startup>1</load-on-startup>

    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

5.编写springMVC配置文件(springmvc-servlet.xml)

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

    <!-- 自动扫描包,让指定包下的注解生效,由IOC容器统一管理 -->
    <context:component-scan base-package="com.ckm.controller"/>

    <!-- 让SpringMVC不处理静态资源 .css .js .html .mp3 .jpg ... -->
    <mvc:default-servlet-handler />

    <!-- 注解完成映射关系,自动开启,自动配置,自动注入 ... -->
    <mvc:annotation-driven />

    <!--视图解析器 : 模板引擎 Thymeleaf Freemarker ...-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!--后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

6.创建controller类

@Controller代表这个类会被spring接管,被这个注解的类中的所有方法,如果返回值是String,并且有具体的页面可以跳转(如,有一个hello.jsp,就需要rentun “hello”;),就会被视图解析器解析。

package com.ckm.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Controller
//@RestController //@RestController不会被视图解析器解析 主要处理json格式
//@RequestMapping("/hello")
public class HelloController {

    @RequestMapping("/hello")
    public String hello(Model model){
        //封装数据
        model.addAttribute("msg","hello,springMVC");

        return "hello"; //会被视图解析器处理
    }

}

7.创建.jsp视图

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${msg}
</body>
</html>

8.测试

小结:

如果类上标注@Controller且方法上没有标注@ResponseBody的话,return的值会被视图解析器处理。
如果类上标注的是@RestController的话,或者在方法上标注了@ResponseBody的话,renturn的值就不会被视图解析器处理。

RestFul url风格

package com.ckm.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class RestFulController {

    //原来的 : http://localhost:8080/add?a=1&b=2
    //RestFul : http://localhost:8080/add/a/b

    @RequestMapping("/add/{a}/{b}")
// @GetMapping("/add/{a}/{b}") //get请求
// @PostMapping("/add/{a}/{b}") //post请求 --- 提交表单 ajax等···
    public String test(@PathVariable int a, @PathVariable int b, Model model){
        int res = a + b;
        model.addAttribute("msg","结果:"+res);
        return "test";
    }
}

SpringMVC转发和重定向

package com.ckm.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ModelTest01 {
    @RequestMapping("/zf")
    public String test(Model model){
        model.addAttribute("msg","转发");
        //配置了视图解析器默认就是转发
        //return "zf";
        //如果没有配置视图解析器
        //return "forward:/WEB-INF/jsp/test.jsp"

        //重定向 
        return "redirect:/index.jsp";
    }

}

SpringMVC接收请求参数

package com.ckm.controller;

import com.ckm.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Controller
@RequestMapping("/user")
public class UserController {
    @GetMapping("/t1")
    public String test1(@RequestParam("username") String name, Model model){
        //接收前端参数
        System.out.println("name="+name);
        //将返回的结果传递给前端
        model.addAttribute("msg",name);
        //视图跳转
        return "test";
    }

    @GetMapping("/t2")
    public String test2(User user,Model model){
        //接收前端参数
        System.out.println(user);
        //将返回的结果传递给前端
        model.addAttribute("msg",user);
        //视图跳转
        return "test";
    }
}

SpringMVC解决乱码问题

第一种方法:

1.编写EncodingFilter类

package com.ckm.filter;

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

public class EncodingFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        chain.doFilter(req,resp);
    }

    @Override
    public void destroy() {

    }
}

2.在web.xml中增加filter

<filter>
        <filter-name>encoding</filter-name>
        <filter-class>com.ckm.filter.EncodingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

第二种方法:

直接在web.xml中增加spring封装好的filter

<filter>
        <filter-name>encoding</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>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

SpringMVC中使用jackson(json格式)

1.pom导入依赖

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

2.lib导入依赖

3.pojo实体类

package com.ckm.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private int id;
    private String name;
    private int sex;

}

4.controller控制器

package com.ckm.controller;

import com.ckm.pojo.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

@Controller
public class JsonController {

    @RequestMapping(value = "/j1",produces = "application/json;charset=utf-8")
    @ResponseBody //一旦写了这个注解,就不会走视图解析器,会返回一个字符串
    public String json1() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        User user = new User(2,"测试",1);
        String str = mapper.writeValueAsString(user);
        return str;
    }

// @RequestMapping(value = "/j2",produces = "application/json;charset=utf-8")
// @ResponseBody //一旦写了这个注解,就不会走视图解析器,会返回一个字符串
// public String json2() throws JsonProcessingException {
// ObjectMapper mapper = new ObjectMapper();
// ArrayList<User> userList = new ArrayList<>();
// User user1 = new User(1, "测试1", 2);
// User user2 = new User(2, "测试2", 1);
// User user3 = new User(3, "测试3", 1);
// User user4 = new User(4, "测试4", 1);
// userList.add(user1);
// userList.add(user2);
// userList.add(user3);
// userList.add(user4);
// String str = mapper.writeValueAsString(userList);
// return str;
//
// }
//
// @RequestMapping(value = "/j3",produces = "application/json;charset=utf-8")
// @ResponseBody //一旦写了这个注解,就不会走视图解析器,会返回一个字符串
// public String json3() throws JsonProcessingException {
// ObjectMapper mapper = new ObjectMapper();
// Date date = new Date();
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// return mapper.writeValueAsString(sdf.format(date));
// }

}

SpringMVC中使用Fastjson(json格式)

1.pom导入依赖

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.60</version>
        </dependency>

2.lib导入依赖

3.controller控制器

package com.ckm.controller;
import com.alibaba.fastjson.JSON;
import com.ckm.pojo.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;

@Controller
public class JsonController {
    
    @RequestMapping(value = "/j2",produces = "application/json;charset=utf-8")
    @ResponseBody //一旦写了这个注解,就不会走视图解析器,会返回一个字符串
    public String json2() throws JsonProcessingException {

        ArrayList<User> userList = new ArrayList<>();
        User user1 = new User(1, "测试1", 2);
        User user2 = new User(2, "测试2", 1);
        User user3 = new User(3, "测试3", 1);
        User user4 = new User(4, "测试4", 1);
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);

        String str = JSON.toJSONString(userList);

        return str;

    }
}

相关文章