欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

荐 SpringMvc基础

程序员文章站 2022-10-04 09:59:25
springmvc为表现层框架,基于MVC设计模式,基于组件流程方式执行流程。简化开发。 springmvc执行流程准备:......

springmvc为表现层框架,基于MVC设计模式,基于组件流程方式执行流程。简化开发。

荐
                                                        SpringMvc基础
springmvc执行流程

                                                     

荐
                                                        SpringMvc基础
项目目录

 


准备:

User      实体类

package xyz.gsdn.domain;

import java.io.Serializable;
import java.util.Date;

public class User implements Serializable
{
    private String username;
    private int age;
    private Date birthday;
    Account account;

    public String getUsername()
    {
        return username;
    }

    public void setUsername(String username)
    {
        this.username = username;
    }

    public int getAge()
    {
        return age;
    }

    public void setAge(int age)
    {
        this.age = age;
    }

    public Date getBirthday()
    {
        return birthday;
    }

    public void setBirthday(Date birthday)
    {
        this.birthday = birthday;
    }

    public Account getAccount()
    {
        return account;
    }

    public void setAccount(Account account)
    {
        this.account = account;
    }

    @Override
    public String toString()
    {
        return "User{" +
                "username='" + username + '\'' +
                ", age=" + age +
                ", birthday=" + birthday +
                ", account=" + account +
                '}';
    }
}

Account          实体类(Account作为User的内部属性)

package xyz.gsdn.domain;

import java.io.Serializable;

public class Account implements Serializable
{
    private int aid;
    private int aage;

    @Override
    public String toString()
    {
        return "Account{" +
                "aid=" + aid +
                ", aage=" + aage +
                '}';
    }

    public int getAid()
    {
        return aid;
    }

    public void setAid(int aid)
    {
        this.aid = aid;
    }

    public int getAage()
    {
        return aage;
    }

    public void setAage(int aage)
    {
        this.aage = aage;
    }
}

springmvc主要就负责web层(controller)

UserController.java                   


@SessionAttributes(value = {"msg","msg2"})//将msg键值对存入session域
@RequestMapping("/user")
@Controller
public class UserController
{
    /**
     RequestMapping注解:
     用于建立请求URL和处理请求方法之间的对应关系。

     @RequestMapping(path = "/hello",method = {RequestMethod.POST},params = {"username=321"})
     path:   请求路径(可以不写,默认,当不止有一个参数时,得写)
     method: 请求方法限制,例现在只接受post请求
     params: 传入参数限制.必须传入username且username的参数为321
     return  String 方法返回一个字符串,根据视图解析器配置,跳转到 字符串.jsp(ok.jsp页面)
     */
    @RequestMapping("/chuan")
    String chuan(User u){
        System.out.println(u);
        return "ok";//视图解析器自动转向ok.jsp,详细看spring.mvc的internalResourceViewResolver
    }
    /**
     *  演示,未配置.返回ModelAndView对象
     *  addObject   返回的数据
     *  setViewName 跳转的页面名称
     *  return mv   返回ModelAndView对象,此对象包含返回的数据和跳转的页面
     */

    ModelAndView chuanModelView(User u){
        ModelAndView mv = new ModelAndView();
        mv.addObject("Object对象");//这个地方传入的是Object对象,返回的数据
        mv.setViewName("ok");//跳转的页面名称
        return mv;
    }
//    --------------------------------------------------------------------------------------------------------
    /**
     * 关于session处理的三个方法
     * @param model  Modelmap是Model的子类
     * @param request
     * @return
     * return String    方法返回一个字符串,根据视图解析器配置,跳转到 字符串.jsp(ok.jsp页面)
     */
    @RequestMapping("/setSession")
    String setSession(ModelMap model, HttpServletRequest request){
        //存储到request域中
        //可以在该方法的类名上添加@SessionAttributes将其添加到session域
        model.addAttribute("msg","msg_value");
        model.addAttribute("msg2","msg_value2");
        return "ok";
    }
    @RequestMapping("/getSession")
    String getSession(ModelMap model,HttpServletRequest request){
        String msg = (String)model.get("msg");
        System.out.println(msg);
        //使用HttpServletRequest对象获取session
        //此方法有耦合,springmvc中使用 model.addAttribute + @SessionAttributes 替代
        HttpSession session = request.getSession();
        String msg_request = (String) session.getAttribute("msg");
        System.out.println("request打印msg:"+msg_request);
        return "ok";
    }
    /**
     * 从request域删除,cong
     * @param model
     * @param sessionStatus
     * @return
     */
    @RequestMapping("/delSession")
    String delSession(ModelMap model, SessionStatus sessionStatus){
        //从request域移除
        model.remove("msg");
        System.out.println("sessionStatus:"+sessionStatus);
        //清除session域
        sessionStatus.setComplete();
        System.out.println("sessionStatus:"+sessionStatus);
        return "ok";
    }
//    --------------------------------------------------------------------------------------------------------
    /**
     * 关于ajax异步请求
     * ResponseBody将返回参数加入response的返回体,前端就可以接收到
     */
    @RequestMapping("/testAjax")
    public @ResponseBody User testAjax( User user) {

        user.setUsername("23csf");
        user.setAge(111);
        user.setBirthday(new Date("2000/1/1"));
        Account account = new Account();
        account.setAid(13);
        System.out.println("---------------------------");
        System.out.println("UserController.testAjax");
        System.out.println(user);
        System.out.println(user.getAge());
        return user;
    }
//    --------------------------------------------------------------------------------------------------------
    /**
     * RequestBody可以获取请求体,直接存入body
     * @param body
     * void方法会默认跳转到  项目名.jsp (reqBody.jsp)页面
     */
    @RequestMapping("reqBody")
    void reqBody(@RequestBody String body)
    {
        System.out.println(body);
    }
//    --------------------------------------------------------------------------------------------------------
    /**
     * 文件上传,得在springmvc.xml中配置multipartResolver文件解析器对象
     * @param request
     * @param upload
     * @throws Exception
     *  void void方法会默认跳转到  项目名.jsp (uploadFile.jsp)页面
     */
    @RequestMapping("/uploadFile")
    void uploadFile(HttpServletRequest request, MultipartFile upload) throws Exception
    {
        //tomcat的webapp下项目文件下的根目录
        //  System.out.println(request.getSession().getServletContext().getRealPath(""));
        String path = "C:\\Users\\shen_i\\Desktop/file";//要写入文件的路径
        File file = new File(path);
        if (!file.exists()){
            file.mkdirs();
        }

        String name = upload.getOriginalFilename();//获取文件名
//    更改文件名为filename   "uuid_name"
        String filename=  UUID.randomUUID().toString().replace("-","") +"_"+ name;

        /*上传文件  (文件路径,文件名)*/
        upload.transferTo(new File(path,filename));

        return;
    }


}

index.jsp               页面,进行访问Controller

<%--
  Created by IntelliJ IDEA.
  User: shen_i
  Date: 2020/7/11 0011
  Time: 10:08
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>index--跳转ok.jsp</title>
    <%--    导入jquery,用于Ajax--%>
    <script src="js/jquery-3.4.1.min.js" ></script>
    <script>
        $(function ()
        {
            $("#btn").click(//按钮绑定ajax
                function ()
                {

                    //发送post请求,请求路径 user/Ajax
                    //传过去的参数为username:"kk",age:"99",birthday:"2020-01-01"
                    //细节:birthday:"2020-01-01" 必须为-连接,  /连接无法封装(I don't understand)
                    //     结果配置了一个转为"/"的converter后,可以封装"2020/01/01,但无法封装"2020-01-01"???
                    //接着 删除自定义的类型转换器StringToDataConverter(其可以将日期字符串转为2020-01-01)
                    //就可以封装"2020/01/01",却无法封装"2020-01-01"
                    $.post("user/testAjax",{"username":"kk","age":"99","birthday":"2020-01-01"},function (data)
                    {
                        alert("hello");
                        $("#ajax_val").css("background-color","#fff");
                        //显示ajax请求结果
                        $("#ajax_val").html(data.username +"  "+data.age+"  "+data.birthday);
                    });
                });
        });
    </script>
</head>
<body style="background-color:rgb(239, 255, 255)">
<br>
<form action="user/chuan" method="post">
    姓名:<input type="text" name="username" />
    年龄:<input type="text" name="age" />
    日期:<input type="date" name="birthday">

    <br>
    <%--    User内部属性Account account--%>
    <%--   Account 想要自动封装,name名必须为 account.aid ,和Account内部属性名完全相同--%>
    Account aid:<input type="text" name="account.aid">
    Account aage:<<input type="text" name="account.aage">
    <input type="submit" value="提交">
    <br>  <br>
    <hr>
    <br>
    <%--    细节:"user/setSession" 前边不要加/,写为"/user/setSession"跳转时会缺失项目名--%>
    <a href="user/setSession">/user/setSession</a>
    <a href="user/getSession">/user/getSession</a>
    <a href="user/delSession">/user/delSession</a>
    <input type="text">
</form>
<br>
<hr>
<button id="btn" >Ajax请求</button>&nbsp;&nbsp;&nbsp;传过去的参数为username:"kk",age:"99",birthday:"2020/01/01"
<br>Ajax请求结果:<br>
<div id="ajax_val">
    还没有进行查询...
</div>
<br>
<hr><br>
<form action="user/uploadFile" method="post" enctype="multipart/form-data">
    上传文件:<input type="file" name="upload"/>
    <br>
    <input type="submit" value="提交">
</form>
</body>
</html>

springmvc.xml  主要springmvc配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       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
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">


    <!--    开启注解扫描,将base-package配置的包内的controller加载进容器-->
    <context:component-scan base-package="xyz.gsdn.Controller">
    </context:component-scan>

    <!--    视图解析器对象-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--    前缀:文件目录-->
        <property name="prefix" value="/pages/"/>
        <!--    后缀:文件后缀名-->
        <property name="suffix" value=".jsp"/>
    </bean>

<!--dispatcherServlet会拦截所有资源,包括静态资源-->
<!--    此处标记静态资源位置,让其不拦截-->
<!--    location元素:表示webapp目录下(即服务器根目录)的pages包下的所有文件;-->
<!--    mapping元素:表示以/pages开头的所有文件请求路径,如/pages/**-->
<!--    该配置的作用是:DispatcherServlet不会拦截以/resource开头的所有请求路径,并当作静态资源交由Servlet处理-->
    <mvc:resources mapping="/pages/**" location="/pages/"/>
    <mvc:resources mapping="/css/**" location="/css/"/>
    <mvc:resources mapping="/js/**" location="/js/"/>


    <!--      自定义类型转换器 StringToDataConverter 字符串转Date,2020-01-01 -->
    <bean id="conversionServiceFactory" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
                <set>
<!--                    配置自己的utils包下的类型转换器-->
                   <bean class="xyz.gsdn.utils.StringToDataConverter"/>
                </set>
        </property>
    </bean>

<!--    文件解析器对象-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="10485760"></property>
</bean>

<!--    开启注解支持, 自动加载HandlerMapping(处理器映射器),HandleAdapter:(处理器适配器)-->
<!--    conversion-service="conversionServiceFactory" 是自己上边的类型转换器,使其生效-->
    <mvc:annotation-driven conversion-service="conversionServiceFactory"/>
</beans>

web.xml              

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
  <display-name>springmvc_program</display-name>

  <!--  前端控制器dispatcherServlet-->
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--    顺便在创建前端控制器时加载配置文件springmvc.xml-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <!--   classpath:springmvc.xml表示: 类路径下的springmvc.xml-->
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <!--    使该servlet第一时间加载,1即启动容器就创建.等级有1-10-->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <!--  servlet 使用"/"拦截处理所有请求   -->
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>


  <!--中文乱码解决,过滤器-->
  <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>
</web-app>

StringToDataConverter.java    日期字符串转日期的转换器

package xyz.gsdn.utils;

import org.springframework.core.convert.converter.Converter;

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

/**
 * 自定义类型转换器
 * String 转为 Date
 * String source  : "1000-10-10"
 * Date pattern:"yyyy-MM-dd"
 * Date result:1000-10-10
 *
 */
public class StringToDataConverter implements Converter<String,Date>
{
    @Override
    public Date convert(String source)
    {
        if (source==null)
        {
            //传入字符串为空
            throw new RuntimeException("StringToDataConverter--传入字符为空~");
        }
        try
        {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date =dateFormat.parse(source);
            return  date;
        } catch (Exception e)
        {
            throw new RuntimeException("StringToDataConverter--转换失败~");
        }
    }
}

pom.xml    maven项目依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>xyz.gsdn</groupId>
  <artifactId>springmvc</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <spring.version>5.0.2.RELEASE</spring.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

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

    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.0</version>
      <scope>provided</scope>
      <!--      jackson:字符串和json互转-->
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.9</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.9.0</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.9</version>
    </dependency>
    <!--    文件上传-->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.3</version>
    </dependency>


  </dependencies>

</project>

代码copy完毕后,tomcat启动即可

 

荐
                                                        SpringMvc基础

 

荐
                                                        SpringMvc基础

 

 

 

本文地址:https://blog.csdn.net/qq_43220949/article/details/107281161