SPRINGMVC

springmvc底层也是servlet,以servlet为核心,接受请求,返回响应。

springmvc的核心是 DispatcherServlet,这个继承了 HttpServlet,也叫前端控制器

springmvc是管理控制器对象

建立工程步骤

1.建立空工程

IDEA---》FILE----->NEW----》 PROJECT --->EMPTY PROJECT

2.添加模块

 依赖       servlet-api这个依赖只能使用 tomcat9及以下的版本,tomcat10里面的servlet-api,已经被改成jakarta这个包下了,DispatcherServlet继承的还是  javax包下的HttpServlet,配置服务器时需要用tomcat9发布

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>5.2.8.RELEASE</version>
</dependency>
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>4.0.1</version>
</dependency>

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">
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/mymvc</url-pattern>
  </servlet-mapping>
</web-app>

配置tomcat9,启动服务

 选择  tomcat  local

 

 

 然后启动服务,访问  http://localhost:8080/firstmvc/mymvc,前面是项目名,后面是DispatcherServlet配置的url,出现如下报错

提示我们需要在DispathcerServlet里面配置初始化参数

IOException parsing XML document from ServletContext resource [/WEB-INF/springmvc-servlet.xml]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/springmvc-servlet.xml],这个红色的就是web.xml里面配置的DispatcherServlet的<servlet-name>的值,

修改web.xml

<servlet>
  <servlet-name>springmvc</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <!--使用自定义配置文件-->
  <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:springmvc.xml</param-value>
  </init-param>
  <!--服务器启动时,创建DispatcherServlet这个对象-->
  <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>springmvc</servlet-name>
  <url-pattern>/</url-pattern>
</servlet-mapping>

在Resource目录下新建一个springmvc.xml文件

 添加包扫描

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

在com.abc包下建立controller类,标注@Controller注解,这个类就是后端的控制器

@Controller
public class HelloController {
    @RequestMapping("/f1")
    public ModelAndView f1(String name,String pass){
//方法的特点,参数是表示请求中的参数,返回值,表示本次请求的结果
        ModelAndView mv = new ModelAndView();
        mv.addObject("MSG","hellocontroller");
        mv.setViewName("res.jsp");
        return mv;
    }
}

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">
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--使用自定义配置文件-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <!--服务器启动时,创建DispatcherServlet这个对象-->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

springmvc.xml的配置  这个文件在resources目录下

<?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:p="http://www.springframework.org/schema/p" 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.abc"></context:component-scan>
  <mvc:default-servlet-handler/>
    <mvc:annotation-driven />
    <mvc:resources mapping="/js/"  location="/js/**" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/"></property>
    <property name="suffix" value=".jsp"></property>
</bean>
</beans>

PathVariable

@RequestMapping("/f2/{a}/{b}")
public String f2(@PathVariable String a,@PathVariable String b){
    System.out.println(a);
    System.out.println(b);
    return "abc";
}

maven依赖

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>5.2.8.RELEASE</version>
</dependency>
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>4.0.1</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>2.11.1</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.11.1</version>
</dependency>
<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.11</version>
  <scope>test</scope>
</dependency>

AJAX发送请求  发送json请求

jsp文件

<input type="button" id="bt1" value="测试ajax" οnclick="fb()">

js文件夹在webapp目录下面和WEB-INF同级

<script type="text/javascript" src="js/jquery-3.5.1.js"></script>
<script>
   function fb() {
       var data={name:"zs",age:"20"};
       var ff = JSON.stringify(data); //转换为json字符串
       var r={};
       $.ajax({
           url:"f2",
           method:"post",
           dataType:"json",
           data:ff,
           contentType:"application/json",
           success:function (res){   //返回的是json对象
               alert(res.name);
               alert(res.age);
           }
       })
   }
</script>

controller文件

@PostMapping("/f2")
public void f2(@RequestBody Student student, HttpServletResponse response) throws IOException {   //加上@RequestBody注解会把前端上送的json字符串,直接封装到student对象中,如果不加此注解,框架会把 form表单请求的数据封装到student,处理不了json字符串
    System.out.println(student);
   
    ObjectMapper om = new ObjectMapper();
    String jj = om.writeValueAsString(student);

    response.setContentType("application/json");
    PrintWriter writer = response.getWriter();
    writer.print(jj);
    writer.flush();
    writer.close();
}

返回responseBody数据

@RequestMapping("/f3")
@ResponseBody   //返回json字符串,不会通过视图解析器去找视图文件了
public String f3(@RequestBody Student student) throws JsonProcessingException {
    System.out.println(student);
    ObjectMapper objectMapper  = new ObjectMapper();
    String ress = objectMapper.writeValueAsString(student);
    return  ress;
}

乱码问题

tomcat配置文件中修改  server.xml文件


    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" 
URIEncoding="UTF-8"/>
 

web.xml文件添加过滤器

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

解决返回的json是乱码的问题 

这是单独解决某个请求的乱码问题

@RequestMapping(value="/f1",produces={"application/json;charset=UTF-8"})

HttpMessageConverter接口,消息转换,可以转换前端上送的数据,以及转换返回给前端的数据

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值