SpringMVC(一)

简介: SpringMVC

SpringMVC @PathVariable注解


@Controller
public class PathController {
    @RequestMapping("PathVariable/{id}/{username}")
    public String PathVariable(@PathVariable("id") String id, @PathVariable("username") String userName){
        System.out.println("id:"+id);
        System.out.println("userName:"+userName);
        return "success";
    }
}

Springmvc参数注入引入

@RestController
public class TestDataController {
    /**
     * 紧耦合方式参数注入
     * 使用传统的HttpServletRequest对象获取参数
     */
     @RequestMapping("/getParamByRequest")
     public String getParam1(HttpServletRequest req, HttpServletResponse resp){
         String username=req.getParameter("username");
         String password=req.getParameter("password");
         return "a";
     }
    /**
     * 解耦合方式
     * HttpServletRequest对象获取参数 通过SpringMVC框架功能,自动转换参数
     * 处理单元参数列表中参数名必须和请求中的参数名一致
     *
     */
    @RequestMapping("/getParamByRequest.do")
    public String getParam2(String username,String password){
        System.out.println("username"+username);
        System.out.println("password"+password);
        return "success";
    }
}

SpringMVC接收POJO类型的参数

form表单

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="getDataByPojo">
   姓名: <p><input type="text" name="pname"></p>
   年龄: <p><input type="text" name="page"></p>
    <p>性别:
        <input type="radio" name="gender" value="1">男
        <input type="radio" name="gender" value="0">女
    </p>
    <p>爱好
        <input type="checkbox" name="hobby" value="1">篮球
        <input type="checkbox"  name="hobby" value="2">足球
        <input type="checkbox" name="hobby" value="3">羽毛球
    </p>
    <p>生日:
        <input type="text" name="birthdate">
    </p>
    <input type="submit">
</form>
</body>
</html>

实体类

public class Person implements Serializable {
    private String pname;
    private String page;
    private String gender;
    private String[] hobby;
    private String birthdate;
    public Person(String pname, String page, String gender, String[] hobby, String birthdate) {
        this.pname = pname;
        this.page = page;
        this.gender = gender;
        this.hobby = hobby;
        this.birthdate = birthdate;
    }
    public Person() {
    }
    @Override
    public String toString() {
        return "Person{" +
                "pname='" + pname + '\'' +
                ", page='" + page + '\'' +
                ", gender='" + gender + '\'' +
                ", hobby=" + Arrays.toString(hobby) +
                ", birthdate='" + birthdate + '\'' +
                '}';
    }
    public String getPname() {
        return pname;
    }
    public void setPname(String pname) {
        this.pname = pname;
    }
    public String getPage() {
        return page;
    }
    public void setPage(String page) {
        this.page = page;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public String[] getHobby() {
        return hobby;
    }
    public void setHobby(String[] hobby) {
        this.hobby = hobby;
    }
    public String getBirthdate() {
        return birthdate;
    }
    public void setBirthdate(String birthdate) {
        this.birthdate = birthdate;
    }
}

Controller:

@RestController
public class ReceiveDataController {
    /**
     * 使用pojo接受参数时,注意事项
     * 提交的参数名必须和pojo的属性名保持一致
     * 底层是通过反射给参数列表的属性赋值
     * 通过set方法设置属性值的。不是操作属性。
     * PoJO的属性一定要有set方法,要不然就会接受失败
     * @param p
     * @return
     */
    @RequestMapping("/getDataByPojo")
    public String getDataByPojo(Person p){
        System.out.println(p);
        return "success";
    }
}

注入Date类型的参数

 @RequestMapping("/getDataByPojo")
    public String getDataByPojo(@DateTimeFormat(pattern = "yyyy-MM-dd") Date birthdate){
        System.out.println(birthdate);
        return "success";
    }
//注意,属性值的名称要对应一致

注入List类型的参数

 宠物:
    <p>
        宠物1 :  姓名:<input type="text" name="pets[0].petName"  >   类型:<input type="text" name="pets[0].petType">
    </p>
    <p>
        宠物2 :  姓名:<input type="text" name="pets[1].petName"  >   类型:<input type="text" name="pets[1].petType">
    </p>
//把list当作对象的一个属性

注入Map类型的参数

 <p>
        宠物3 :  姓名:<input type="text" name="petMap['a'].petName"  >   类型:<input type="text" name="petMap['a'].petType">
    </p>
    <p>
        宠物4 :  姓名:<input type="text" name="petMap['b'].petName"  >   类型:<input type="text" name="petMap['b'].petType">
    </p>

实体类:

@AllArgsConstructor
@NoArgsConstructor
@Data
public class Person implements Serializable {
    private String pname;
    private String page;
    private String gender;
    private String[] hobby;
    private String birthdate;
    private List<Pet> pets;
    private Map<String,Pet> petMap;
}

SpringMVC解决乱码问题:

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

SpringMVC常见注解

    @RequestMapping; //用于建立请求URL和处理请求方法之间的对应关系
    @RequestParam //用于对指定的形参赋值(当页面中请求的参数和代码中处理的参数名称不一致时,需要使用这个注解)
    @PathVariable //用于绑定url中的占位符,取出某一个字符串段的数据。/delete/{id},如果想取出id这个属性,需要这个注解
    @RequestHeader//获取请求头的信息
    @CookieValue //获取请求中的cookie信息

SpringMVC请求转发和重定向

@Controller
public class TestResponse {
    /**
     * 返回字符串告诉DispatcherServlet跳转的路径
     * 在路径之前放上一个forward:关键字,就是请求转发
     * 如果路径前的关键字是forward,那么可以省略不写
     * @return
     */
    @RequestMapping("demo2")
    public String testDemo2(){
        return "forward:/forward.jsp";
    }
    /**
     * 返回字符串告诉DispatcherServlet跳转的路径
     * 在路径之前放上一个redirect:关键字,就是重定向
     * 如果路径前的关键字是redirect,那么不可以省略
     * /表示当前项目下,这里不需要项目的上下文路径
     * @return
     */
    @RequestMapping("demo3")
    public String testDemo3(){
        return "redirect:/forward.jsp";
    }
}
 @RequestMapping("demo4")
    public View testDemo4(){
        View view=null;
        view=new InternalResourceView("/forwardPage.jsp");
        view=new RedirectView("/redirectPage.jsp");
        return view;
    }

SpringMVC响应JSON

导入依赖:

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

控制器操作:

    @ResponseBody
    @RequestMapping("testAjax")
    public Pet testAjax() throws JsonProcessingException {
        Pet pet=new Pet("Tom","cat");
        return pet;
    }

SpringMVC SSM 整合

ssm整合就是将spring ,springmvc mybatis整合起来。mybatis中要用到的sqlsessionfactory和sqlsession交给spring容器来创建。

配置文件

124f0e818ecc44d099bfdc52f0575cb4.png


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">
<!--DispatcherServlet-->
  <servlet>
    <servlet-name>dispatcherServlet</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>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
<!--  CharcterEncodingFilter-->
  <filter>
    <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
<!--  向ServletContext中添加spring核心配置文件的位置-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
<!--  Spring核心容器配置
通过监听器,监听JavaWeb项目中的ServletContext创建的时候,就创建一个spring容器,并放入ServletContext对象中
-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
</web-app>

SpringMVC.xml:

<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-4.3.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--     扫描controller-->
    <context:component-scan base-package="com.msb.controller"></context:component-scan>
<!--   开启mvc注解驱动,自动给我们配置好处理器映射器和处理器适配器-->
    <mvc:annotation-driven/>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    </bean>
<!--&lt;!&ndash;        指定前缀和后缀&ndash;&gt;-->
<!--        <property name="prefix"  value="/WEB-INF/"></property>-->
<!--        <property name="suffix"   value=".jsp"></property>-->
<!--    </bean>-->
<!--    静态资源放行-->
<!--    mapping url中的路径  location=对应的路径到项目-->
<!--    <mvc:resources mapping="/js/**" location="/js/"></mvc:resources>-->
</beans>
相关文章
|
Java Maven 容器
java依赖冲突解决问题之Maven在编译打包过程中对依赖的jar包如何解决
java依赖冲突解决问题之Maven在编译打包过程中对依赖的jar包如何解决
|
11月前
|
存储 Java 数据库
使用 AuraDB 免费版构建 Java 微服务
使用 AuraDB 免费版构建 Java 微服务
128 11
|
11月前
|
机器学习/深度学习 人工智能 TensorFlow
解锁AI潜力:让开源模型在私有环境绽放——手把手教你搭建专属智能服务,保障数据安全与性能优化的秘密攻略
【10月更文挑战第8天】本文介绍了如何将开源的机器学习模型(如TensorFlow下的MobileNet)进行私有化部署,包括环境准备、模型获取与转换、启动TensorFlow Serving服务及验证部署效果等步骤,适用于希望保护用户数据并优化服务性能的企业。
371 4
|
安全 数据处理 数据格式
深入浅出:FFmpeg 音频解码与处理AVFrame全解析(三)
深入浅出:FFmpeg 音频解码与处理AVFrame全解析
487 0
|
12月前
|
缓存 NoSQL 算法
本地缓存Caffeine系列(四)
本地缓存Caffeine系列(四)
|
10月前
|
安全 API UED
WebSocket API 中的 close 事件是如何触发的?
【10月更文挑战第26天】close事件的触发涵盖了从正常的连接关闭到各种异常情况导致的连接中断等多种场景。通过监听close事件,开发人员可以在连接关闭时进行相应的处理,如清理资源、更新界面状态或尝试重新连接等,以确保应用程序的稳定性和良好的用户体验。
|
存储 Java 开发者
Java 中的线程局部变量是什么?
【8月更文挑战第21天】
180 0
|
前端开发 Oracle Java
JSF(JavaServer Face)标签库简介(JavaEE)
JSF(JavaServer Faces)是JavaEE框架,用于简化Web应用开发,采用组件驱动方式和MVC模式确保可维护性。主要实现包括PrimeFaces、Apache MyFaces和ICEFaces。JSF通过JCP标准化,Oracle提供了JSF2.2和2.3的实现库。JSF应用涉及UI设计、前后端分离及JavaBean交互。实现过程包括网站结构创建、库文件配置、Tomcat的JSF标签库设置以及启动验证。通过创建JSF页面如hello.xhtml,展示其工作原理。
519 2
|
SQL Java 数据库连接
IDEA开发插件有哪些值得推荐?
这篇文章介绍了IntelliJ IDEA中一些实用的神仙插件,包括RestfulTool(用于快速定位请求处理代码)、Translation(方便代码中的英文翻译)、Alibaba Java Coding Guidelines(遵循阿里巴巴编码规范)、Free MyBatis Tool(增强MyBatis支持)和Mybatis Log(整理SQL日志)。此外,还提到了Vue.js插件和可选装的Grep Console(日志高亮)、Maven Helper(解决Maven依赖冲突)以及Private Notes和Rainbow Brackets(代码注释和括号颜色标记)。
246 2
|
存储 NoSQL 中间件
单点登录简述
单点登录简述
258 1