温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

springMVC框架是什么样的

发布时间:2021-10-20 17:40:55 来源:亿速云 阅读:133 作者:柒染 栏目:大数据

这篇文章给大家介绍springMVC框架是什么样的,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

SpringMVC

概念:SpringMVC是一种基于java的实现MVC设计模型的请求驱动类型的轻量级web框架,属于springFramework的后续产品,已经融合在Spring Web Flow里面,Spring框架提供了构建web应用程序的全功能MVC模块,使用Spring可插入的MVC框架,从而在使用Spring进行WEB开发时,可以选择使用Spring的SpringMVC框架或集成其他MVC框架。

它通过一套注解,让一个简单的Java类成为处理请求的控制器,而无序实现任何接口,同时它还支持RESTful编程风格的请求。

入门代码:

第一步:配置前端控制器,在web.xml中

<!--配置前端控制权-->
<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>
  <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
  <servlet-name>dispatcherServlet</servlet-name>
  <url-pattern>/</url-pattern>
</servlet-mapping>

2、创建控制类

@Controller
public class HelloController {

    @RequestMapping(path = "/hello")//用于建立请求URL和处理请求方法之间的对应关系
    /*
    * 属性;path/value ,映射路径
    *      method,当前方法可以接受怎么样的请求方式
    *      params,用于请求参数的条件
    *      handers,发送的请求必须包含请求头
    * */
    public  String sayHello(){
        System.out.println("hello StringMvc");
        return "success";
    }
}

3、在资源文件夹下创建配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        https://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">



    <context:component-scan base-package="lianbang.wu"></context:component-scan>

    <!--视图解析器对象-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >

        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--开启-springmvc框架注解支持 自动配置处理器映射器和处理器适配器-->
    <mvc:annotation-driven />


    <!--配置类型转换器-->
    <bean id="cs" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters" >
            <set>
                <bean class="lianbang.wu.utils.StringToDateConverter"></bean>
            </set>
        </property>
    </bean>

    <!--前端控制权哪些静态资源不拦截-->
    <mvc:resources mapping="/js/**" location="/js/**"/>
</beans>

程序解析:

1、启动服务器,加载一些配置文件

2、发送请求,后台处理请求

组件介绍:springmvc框架基于组件方式执行流程

前端控制器:DispatcherServlet,它相当于mvc中的c,由它调用其他组件处理用户的请求,降低组件间的耦合性

处理器映射器:HandlerMapping,负责根据用户请求找到handler(处理器)

处理器适配器:HandlerAdapter,对处理器进行执行

处理器:Handler,它就是我们开发中要编写的具体业务控制器

视图解析器:ViewResolver,负责处理结果生成view视图

请求参数绑定

入门代码:

1、发送请求参数

<form action="/param/testParam" method="post">
    用户名:<input type="text" name="username"/><br>
</form>

2、请求参数绑定,自动进行同名参数的绑定

@Controller
@RequestMapping("/param")
public class ParamController {

    @RequestMapping("/testParam")
    public String testParam(String username){
        System.out.println("执行了。。。"+username);
        return "success";
    }
}

请求参数绑定实体类:

1、创建实体类

public class DemoClass implements Serializable {
    private  String username;
    private String password;
    private Double money;
//------省略get,set方法,自行添加
}

2、发送请求

<form action="/param/save" method="post">
    用户名:<input type="text" name="username"/><br>
    密码:<input type="text" name="password"/><br>
    金额:<input type="text" name="money"/><br>
</form>

3、自动进行实体类型绑定

@Controller
@RequestMapping("/param")
public class ParamController {
@RequestMapping("/save")
public String save(DemoClass demoClass){
    System.out.println(demoClass);
    return "success";
}
}

注意:解决POST请求中文乱码:添加过滤器,在web.xml中添加

<!--配置解决中文乱码的过滤器-->
<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>

请求参数绑定集合类型:

1、发送请求

</form>
用户id:<input type="text" name="list[0].id"/><br>
用户年龄:<input type="text" name="list[0].age"/><br>
</form>

2、创建对应的实体类

3、自动进行参数绑定

自定义内容转换器:解决数据内容转换异常问题

第一步:定义一个类,实现Convrter接口,该接口有两个泛型,分别表示接受的类型和目标类型

//自定义类型转换器
public class StringToDateConverter implements Converter <String , Date> {

    @Override
    public Date convert(String s) {
        if (s == null){
            throw  new  RuntimeException("请传入数据");
        }
        DateFormat df  = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date = df.parse(s);
            return date;
        } catch (ParseException e) {
            e.printStackTrace();
            throw  new RuntimeException("数据类型转换异常");
        }

    }
}

第二步:注册类型转换器

<!--开启-springmvc框架注解支持 自动配置处理器映射器和处理器适配器-->
<mvc:annotation-driven  conversion-service="cs"/>


<!--配置类型转换器-->
<bean id="cs" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters" >
        <set>
            <bean class="lianbang.wu.utils.StringToDateConverter"></bean>
        </set>
    </property>
</bean>

获取servlet原生API

//获取原生API
public String testServlet(HttpServletRequest request, HttpServletResponse response){

    return "success";
}

常用注解:

@RequsetParams

作用:把请求中指定名称的参数给控制器中的形参赋值。

属性:value,请求参数中的名称

         required,请求参数重是否必须提供此参数,默认值:true,表示必须提供,如果不提供将报错。

//@RequestParam
public  String testRequestParam(@RequestParam(name = "name") String username){
    return "success";
}

@RequsetBody

作用:用于获取请求体内容,直接使用得到是key=value&key=value···结构的数据,get请求不适用

属性:required;是否必须有请求体,默认值是true,当取值为true时,get请求方式会报错,如果取值为false,get请求得到null。

//@RequestBody
public String testRequestBody(@RequestBody String body){
    System.out.println(body);
    return "success";
}

@PathVariable

作用:用于绑定url中的占位符的

属性:value:指定url中的占位符名称

Restful风格的URL:

1、请求路径一样,可以根据不同的请求方式去执行后台的不同方法

2、restful风格的URL优点:1、结构清晰,2、符合标准,3、易于理解,4、扩展方便

//@PathVariable
@RequestMapping("/testPathVariable/{uid}")
public String testPathVariable(@PathVariable(name = "uid") String id){
    System.out.println(id);
    return "success";
}

@HiddentHttpMethodFilter

作用;由于浏览器的form表单只支持GET和POST请求,而DELETE、PUT等method并不支持,spring3.0添加了一个过滤器,可以将浏览器请求改为指定的请求方式,发送给我们的控制器方法,使得支持GET,POST,PUT和DELETE

使用方法:

第一步:在web. xml中配置该过滤器

第二步:请求方式必须使用POST请求

第三步:按照要求提供_method请求参数,该参数的取值就是我们需要的请求方式。

@RequestHeader

作用:用于获取请求消息头

属性:value:提供消息头名称

         required:是否必须有此消息头

//@RequestHeader
public String testRequestHeader(@RequestHeader(value = "Accept") String header){
    System.out.println(header);
    return "success";
}

@CookieValue

作用:用于把指定cookie名称的值传入控制器方法参数

属性:value:指定cookie的名称

         required:是否必须有此cookie

//@CookieValue
public String testCookieValue(@CookieValue(value = "JSESSIONID") String cookie){
    System.out.println(cookie);
    return "success";
}

@ModelAttribute

作用:用于修饰方法和参数,出现在方法上,表示当前方法会在控制器的方法执行之前,先执行。它可以修饰没有返回值的方法,也可以修饰有具体返回值的方法。出现在参数上,获取指定的数据给参数赋值

属性:value,用于获取数据的key,key可以上POJO的属性名称,也可以上map结构的key

应用场景:当表当提交数据不是完整的实体类数据时,保证没有提交数据的字段使用数据库对象原来的数据。

//@ModelAttribute
@ModelAttribute
public void MyShow(){
    System.out.println("MyShow执行了");
}

@SessionAttribute

作用:用于多次执行控制器方法间的参数共享

属性:value:用于指定存入的属性名称

         type:用于指定存入的数据类型

作用于类上。

Springmvc的响应数据和结果视图

响应返回值是String类型:

//返回值为String
@RequestMapping("/testString")
public String testString(Model model){
    System.out.println("testString执行了");
    return "success";
}

响应返回值是void类型:

//返回值为void
public void testvoid(HttpServletRequest request , HttpServletResponse response) throws ServletException, IOException {
    System.out.println("testvoid方法执行");
    request.getRequestDispatcher("/WEB-INF/Pages/success.jsp").forward(request,response);//请求转发
    response.sendRedirect(request.getContextPath()+"/success.jsp");//重定向
    //直接响应
    response.setCharacterEncoding("UTF-8");
    response.setContentType("text/html;charset=UTF-8");
    response.getWriter().print("hello");
}

 文件上传

传统方式代码:

<h4>文件上传:传统方式</h4>
<form action="/user/fileupload1" method="post" enctype="multipart/form-data">
    选择文件:<input type="file" name="upload"/><br/>
    <input type="submit" value="上传"/>
</form>
@RequestMapping("/fileupload1")
public String fileUpLoad(HttpServletRequest request) throws Exception {
    System.out.println("文件上传");

    //使用fileupload组件
    String realPath = request.getSession().getServletContext().getRealPath("/uploads");
    File file = new File(realPath);
    if (!(file.exists())){
        file.mkdirs();
    }
    //解析request对象,获取上传文件想
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> fileItems = upload.parseRequest(request);

    for (FileItem item : fileItems){
        //进行判断,当前item对象是否是上传文件
        if (item.isFormField()){
            //普通表单项
        }else {
            //上传文件项
            String filename = item.getName();
            String uuid = UUID.randomUUID().toString().replace("-"," ");
            filename=uuid+"_"+filename;
            item.write(new File(realPath,filename));
            item.delete();
        }
    }

    return "success";
}

springMVC方式代码:

<h4>文件上传:springmvc</h4>
<form action="/user/fileupload2" method="post" enctype="multipart/form-data">
    选择文件:<input type="file" name="upload"/><br/>
    <input type="submit" value="上传"/>
</form>
@RequestMapping("/fileupload2")
public String fileUpLoad2(HttpServletRequest request,MultipartFile upload) throws IOException {
    System.out.println("springmvc文件上传");
    String path = request.getSession().getServletContext().getRealPath("/uploads/");
    File file = new File(path);
    if (!file.exists()){
        file.mkdirs();
    }
    String filename = upload.getOriginalFilename();
    String uuid = UUID.randomUUID().toString().replace("-"," ");
    filename = uuid+"_"+filename;
    upload.transferTo(new File(path,filename));

    return "success";
}

跨服务方式代码:

<h4>文件上传:跨服务器</h4>
<form action="/user/fileupload3" method="post" enctype="multipart/form-data">
    选择文件:<input type="file" name="upload"/><br/>
    <input type="submit" value="上传"/>
</form>
@RequestMapping("/fileupload3")
public String fileUpLoad3(MultipartFile upload) throws IOException {
    System.out.println("跨服务器文件上传");

    //定义上传文件的服务器路径
    String path = "http://localhost:9090/uploads/";



    String filename = upload.getOriginalFilename();
    String uuid = UUID.randomUUID().toString().replace("-"," ");
    filename = uuid+"_"+filename;

    //创建客户端对象
    Client client = Client.create();
    //和图片服务器进行连接
    WebResource resource = client.resource(path + filename);
    // 上传文件
    resource.put(upload.getBytes());

    return "success";
}

在实际开发中,我们会有很多处理不同功能的服务器,例如:

应用服务器:负责部署我们的应用

数据库服务器:运行我们的数据库

缓存和消息服务器:负责处理大并发访问的缓存和消息

文件服务器:负责存储用户上传文件的服务器

SpringMVC的拦截器:类似于servlet的Filter

1、编写拦截器类

/*
自定义拦截器
 */
public class MyInterceptor implements HandlerInterceptor {
    /**
     * 预处理,controller方法执行前
     * 如果return true 放行,执行下一个拦截器,如果没有,执行controller中的方法
     * 如果return false 不放行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyInterceptor执行了");
        return true;
    }

    /**
     * 后处理方法
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 跳转页面后执行
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

2、配置拦截器

<!--配置拦截器-->
<mvc:interceptors>
    <mvc:interceptor>
        <!--要拦截的具体方法-->
        <mvc:mapping path="/user/*"/>
        <!--不要拦截的方法-->
        <!--<mvc:exclude-mapping path=""/>-->
        <!--配置拦截器对象-->
        <bean class="lianbang.wu.interceptor.MyInterceptor"></bean>
    </mvc:interceptor>
</mvc:interceptors>

SpringMVC的异常处理:

1、编写自定义异常类

public class SysException extends Exception {
    private String message;

    @Override
    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public SysException(String message) {
        this.message = message;
    }
}

2、编写异常处理器

public class SysExceptionResolver  implements HandlerExceptionResolver {
    /**
     * 处理异常的业务
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param e
     * @return
     */
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        //获取异常对象
        SysException exception = null;
        if (e instanceof SysException){
            exception= (SysException)e;
        }else {
            exception= new SysException("系统维护");
        }

        ModelAndView mv = new ModelAndView();
        mv.addObject("errorMsg",exception.getMessage());
        mv.setViewName("error");
        return mv;
    }
}

3、配置异常处理器

<!--配置异常处理器-->
<bean id="sysExceptionResolver" class="lianbang.wu.exception.SysExceptionResolver"></bean>

关于springMVC框架是什么样的就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI