暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

springmvc快速入门

JAVA不归路 2021-09-09
254

springmvc的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>com.baidu</groupId>
 <artifactId>springmvc_day01</artifactId>
 <version>1.0-SNAPSHOT</version>
   <packaging>war</packaging>

 <name>springmvc_day01 Maven Webapp</name>
 <!-- FIXME change it to the project's website -->
 <url>http://www.example.com</url>

 <properties>
   <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   <maven.compiler.source>1.7</maven.compiler.source>
   <maven.compiler.target>1.7</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>
     </dependency>
     <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
     <version>4.11</version>
     <scope>test</scope>
   </dependency>
 </dependencies>

 <build>
   <finalName>springmvc_day01</finalName>
   <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
     <plugins>
       <plugin>
         <artifactId>maven-clean-plugin</artifactId>
         <version>3.1.0</version>
       </plugin>
       <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
       <plugin>
         <artifactId>maven-resources-plugin</artifactId>
         <version>3.0.2</version>
       </plugin>
       <plugin>
         <artifactId>maven-compiler-plugin</artifactId>
         <version>3.8.0</version>
       </plugin>
       <plugin>
         <artifactId>maven-surefire-plugin</artifactId>
         <version>2.22.1</version>
       </plugin>
       <plugin>
         <artifactId>maven-war-plugin</artifactId>
         <version>3.2.2</version>
       </plugin>
       <plugin>
         <artifactId>maven-install-plugin</artifactId>
         <version>2.5.2</version>
       </plugin>
       <plugin>
         <artifactId>maven-deploy-plugin</artifactId>
         <version>2.8.2</version>
       </plugin>
     </plugins>
   </pluginManagement>
 </build>
</project>

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>Archetype Created Web Application</display-name>
   <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>
<!--   解决中文乱码问题,配置过滤器-->
   <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>

springmvc的xml文件配置

建议起名springmvc.xml

<?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">
   <context:component-scan base-package="com.baidu"></context:component-scan>
<!--           配置视图解析器-->
   <bean name="internalResourceViewResolver" class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
       <property name="prefix" value="/WEB-INF/pages/"></property>
       <property name="suffix" value=".jsp" ></property>
   </bean>
<!--               告诉前端控制器,哪些资源不要拦截-->
       <mvc:resources mapping="/js/" location="/js/**" />

<!--   配置自定义类型转换器-->
   <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
       <property name="converters">
           <set>
<!--               注册自定义的转换类-->
               <bean class="com.baidu.utils.StringToDateConverter" />

           </set>
       </property>
   </bean>

<!--   开启spring框架注解的支持-->
   <mvc:annotation-driven conversion-service="conversionService"/>
</beans>


入门案例

<!--html前端页面-->
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>Title</title>
</head>
<body>
   <a href="user/testString">入门案例</a>
</body>
</html>

package com.baidu.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
//controller层
@Controller
@RequestMapping(value = "/user") //value为请求的地址
public class UserController {
   @RequestMapping(value = "/testString")
   public String testString(){
       System.out.println("haha...");
       return "success";//跳转到成功页面
  }

}

解决日期格式转换问题的配置类

package com.baidu.utils;

import javafx.scene.input.DataFormat;
import org.springframework.core.convert.converter.Converter;

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

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 {
           return df.parse(s);
      } catch (ParseException e) {
           throw new RuntimeException("数据格式化错误");
      }
  }
}

常用注解

@RequestParam   当请求参数与形参不一致时,可以用此注解指定请求参数的name,默认required 为true表必须传该属性 public String sayHello(@RequestBody (name="uname") String username){ 。。。}

    @RequestBody    不能用于get请求  
      此注解表示可以直接拿到请求体(uname=aa&age=20)
public String sayHello(@RequestBody String body){ 。。。 }

@PathVariable  
用于绑定url中的占位符  
   例如 url /delete/{id},这个{id}就是 url 占位符。
       <a href="test/delete/10">
@RequestMapping("/testPathVatiable/{sid}")
public String usePathVariable(@PathVariable("sid") Integer id){ }
可以将这个id赋值给形参

@RequestHeader   获取请求头信息
public String testRequestHeader(@RequestHeader(value="Accept") String header){   }  
可以获取Accept请求头信息

@CookieValue   获取cookie的值
public String testRequestHeader(@CookieValue (value="JSESSIONID") String cookieValue) {   }  可以获取cookie的值

@ModelAttribute  
       用于修饰方法,此方法会在控制器执行之前执行(在被请求方法执行之前执行)
如果有返回值,返回的结果可以直接被封装到被请求方法的参数中去
如果没有参数
@RequestMapping(value="xxx")
public String testModelAttribute(@ModelAttribute("aaa") User user){。。。}
@ModelAttribute
public void showUser(String uname ,map<String,User> map){
User user = new User(uname,age,new Date());
map.put(user);  

       这个方法执行之后再执行被请求的方法,

    此方法的map可以被被请求方法得到并取值,

       具体值以表单中为准,没有用map集合中的填补
}
sessionAttribute : 用于多次执行控制器方法间的参数共享  作用在类上

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

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

@SessionAttributes(value={"key"})
class a{}
Model model   可以存入键值对到request域中  model.addAttribute(key,value)
ModelMap  modelMap.get(key)  从session域中取值
SessionStatus status.setComplete()  重置session域  相当于删除

响应返回值

    String      如果返回值是String类型,那么会跳转到返回值.jsp页面

Void 如果返回值是void,默认会跳转到请求路径.jsp页面  
       @RequestMapping("/testVoid")   testVoid.jsp
如果想返回void又想跳转,可以调用HttpServletRequest,HttpServletResponce对象来完成跳转
request.getRequestDispatcher("/WEB-INF/pages/success.jsp")
      .forward(request,response);  
请求可以直接请求目录下jsp
response.sendRedirect(request.getContextPath()+"/index.jsp");
也可以直接进行相应 response.getWriter().print("hello");

备注:请求之后的代码依旧会执行,如果不想执行可以直接写  return
设置中文乱码: response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");  

ModelAndView 返回值为ModelAndView,把对象存入ModelAndView中,也会把user对象存入request域中
ModelAndView mv = new ModelAndView();
mv.addObject("user",user);
mv.setViewName("success");  
设置跳转到哪个页面,配置过视图解析器,返回字符串底层也会调用此类
           
使用关键字进行转发和重定向(返回字符串)
return "forward:/WEB-INF/pages/index.jsp";

return "redirect:/index.jsp";  
使用这个关键字不需要写项目名,底层帮我们加上了

响应json数据之过滤静态资源
<mvc:resource location="/css/" mapping="/css/**" />  不拦截css
<mvc:resource location="/images/" mapping="/images/**" />
<mvc:resource location="/js/" mapping="/js/**" />

在springmvc.xml里面配置,

相当于告诉前端控制器DispatcherServlet(web.xml中)

 不要拦截以上资源
响应json格式数据
需要在形参里面加@RequestBody 来获取对象封装到javaben
在返回值处加 @ResponseBody 返回json格式数据

视图及视图处理器

SpringMVC如何解析视图:

对于那些返回String、view或ModelMap等类型的处理方法,SpringMvc都会将其装配成一个ModelAndView对象。view接口时无状    态的,不会有线程安全问题

重定向

如果返回的字符串中带有“forward:”或“redirect:”前缀时,SpringMVC会对他们进行特殊处理,将其当成指示符,其后的字符串作为URL来处理。

数据的转换、格式化、校验

数据转换

pringMVC定义了3种类型的转换器接口:

 Converter<S,T>:将S类型转换为T类型对象
ConverterFactory:将相同系列多个“同质”Conterver封装在一起
GenericConverter: 会根据源类对象及目标所在的宿主主类中的上下文信息进行类型转换

表单


<form action="testConverter" method="POST">
    <!-- 例如:Harry-000-00 -->
    Employee:<input type="text" name="user">
    <input type="submit" name="Submit">
</form>

转换器


@Component
public class UserConverter implements Converter<String, User> {
@Override
public User convert(String source) {
if(source != null) {
System.out.println("aa");
String[] vals = source.split("-");
if(vals != null) {
String username = vals[0];
String password = vals[1];
String age = vals[2];
User user = new User(username, password, Integer.parseInt(age));
System.out.println("converter:"+user);
return user;
}
}
return null;
}
}

配置文件

<mvc:annotation-driven conversion-service="converterService"></mvc:annotation-driven>
  <!-- 配置converterService -->
  <bean id="converterService" class="org.springframework.context.support.ConversionServiceFactoryBean">
     <property name="converters">
       <set>
          <ref bean="userConverter"/>
       </set>
     </property>
  </bean>

目标方法


@RequestMapping("/testConverter")
public String testConverter(@RequestParam("user") User user) {
System.out.println(user);
return "success";
}

数据格式化

在springmvc.xml中开启支持
<mvc:annotation-driven ></mvc:annotation-driven>
在目标类型的属性上配置

@NumberFormat(pattern="#.##")
private double price;

@DateTimeFormat(pattern="yyyy-mm-dd")
private Date birth;

数据的校验

.使用 JSR 303 验证标准,在 springmvc.xml 配置文件中添加 
<mvc:annotation-driven />
<mvc:annotation-driven />会默认装配好一个LocalValidatorFactoryBean

.需要在 bean 的属性上添加对应的注解
 例如:
 @NotNull :被注释的元素不能为空
@Past  :备注是的元素必须是一个过去的日期    
@Email  :被注释的元素必须是一个email
   
在目标方法 bean 类型的前面添加 @Valid 注解

文件上传

SpringMvc通过MutipartResolver实现文件上传

配置MutipartResolver

<!-- 配置 MultipartResolver -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="maxUploadSize" value="1024000"></property>
</bean>
//表单
<form action="testFileUpload" method="POST" enctype="multipart/form-data">
File: <input type="file" name="file"/>
Desc: <input type="text" name="desc"/>
<input type="submit" value="Submit"/>
</form>
方法
@RequestMapping("/testFileUpload")
public String testFileUpload(@RequestParam("desc") String desc,
        @RequestParam("file") MultipartFile file) throws Exception {
System.out.println("InputStream:" + file.getInputStream());
return "success";
}

拦截器

springmvc也可以使用拦截器对请求进行拦截,可以自定义拦截器来实现特定的功能,

自定义拦截器必须实现HandlerInterceptor接口

//实现HandlerInterceptor接口
public class FirstInterceptor implements HandlerInterceptor {

/**
* 渲染视图之后被调用. 释放资源
*/
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
System.out.println("afterCompletion");

}

/**
* 调用目标方法之后, 但渲染视图之前.
* 可以对请求域中的属性或视图做出修改.
*/
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
System.out.println("postHandle");

}

/**
* 该方法在目标方法之前被调用.
* 若返回值为 true, 则继续调用后续的拦截器和目标方法.
* 若返回值为 false, 则不会再调用后续的拦截器和目标方法.
*/
@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
System.out.println("preHandle");
return true;
}

}
在springmvc.xml文件中配置
<!-- 配置拦截器 -->
  <mvc:interceptors>
     <bean class="springmvc.helloworld.FirstInterceptor"></bean>
  </mvc:interceptors>



文章转载自JAVA不归路,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论