springMVC

/main/webapp/WEB-INF/web.xml

javaWeb的配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">
    <servlet-mapping> 
        <servlet-name>dispatcherServlet</servlet-name><!--对应servlet名-->
        <url-pattern>/*</url-pattern><!--拦截的路径(可以*.后缀通配,*.html不能返回json),/*下不能返回静态资源,会被循环拦截-->
    </servlet-mapping>
    <servlet> 
        <servlet-name>dispatcherServlet</servlet-name> <!-- servlet名-->
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><!--配置调度器-->
        <init-param>
            <param-name>contextConfigLocation</param-name> <!--加载的配置文件-->
            <param-value>classpath:springMVC.xml</param-value><!--classpath当前模块resources目录-->
        </init-param> 
        <load-on-startup>1</load-on-startup><!--servlet加载顺序( <=0表示第一次请求时加载,>0正整数越小越早加载-->
    </servlet>
</web-app>

springMVC.xml

springMVC的配置

<?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: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="包.controller"/><!--扫描Controller-->

	<!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
        <property name="prefix" value="/路径/"/><!--响应资源路径前缀-->
        <property name="suffix" value=".html"/><!--响应资源路径后缀-->
    </bean>

    <mvc:annotation-driven/><!--SpringMVC注解驱动-->
	<context:property-placeholder location="classpath:*.properties"/><!---全局属性文件->
</beans>

@RequestMapping

@Controller
@RequestMapping("路径") //根路径
public class class{
	@Value("${}")//全局属性可以自动注入
    private String string;

	@RequestMapping(value = "访问路径,后缀可以省略" , 
		method = {请求方法} , 
		params = {"key=value","key!=value"} , //限定请求参数
		headers = {"key"} //限定请求头必须有key
	)
	public 返回值 funtion(参数){}
}

表单添加请求方法支持

from表单只支持GET和POST,要添加过滤器转换
web.xml

<filter-mapping> 
	<filter-name>hiddenHttpMethodFilter</filter-name> 
	<url-pattern>/*</url-pattern> 
</filter-mapping>

<filter>
	<filter-name>hiddenHttpMethodFilter</filter-name> 
	<filter- class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> 
</filter>
<form action="提交路径" method="post(使用过滤器必须用post)">
	<input type="hidden" name="_method" value="PUT"/><!--设置提交方法-->
</form>

支持的参数

HttpServletRequest 请求对象

HttpServletResponse 响应对象

HttpSession session

Model 用model.addAttribute("key","value")存入数据,在返回页面中可以获取

@RequestParam(value = "key",defaultValue = "默认值",required = 是否必须) 绑定参数,基本数据类型(不能为null),包装数据类型(可以空),多个同名参数绑定为数组或集合,参数名一致可以不写注解

@PathVariable("key") 使用地址传参,有时加了有bug,@RequestMapping("/{key1}/{key2}"),绑定URL中参数

@CookieValue("key") 获取cookie信息

对象 参数自动封装成对象

MultipartFile 上传文件

@RequestBody json自动封装到实体类

上传文件配置

springMVC.xml

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
	<property name="maxUploadSize" value="10485760"/> <上传的最大值: 单位B --> 
</bean>

保存MultipartFile

MultipartFile.transferTo(new File("路径"));

参数乱码配置

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>

参数转换

public 返回值 funtion(T){}时传入S,会进入Converter转换成T

public class CustomConverter implements Converter<S,T> {
    @Override
    public T convert(S s) {
        return null;
    }
}

在springMVC.xml中加入容器

<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> 
	<property name="converters"> 
		<set>
			<bean class="包.CustomConverter"> </bean> 
		</set> 
	</property> 
</bean>

返回数据

页面跳转

public String funtion(Model model){
	model.addAttribute("key", "value");
	return "路径";//访问静态文件,路径会拼接prefix和suffix
	return "redirect:路径";//相对当前controller路径的方法
	return "forward:路径";//转发,不拼接prefix和suffix
}

模型与视图对象

public ModelAndView funtion(){
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("路径");
		modelAndView.addObject("key","value");
		return modelAndView;
}

josn数据

@ResponseBody //返回对象转换为json,需要手动添加jackson-core和jackson-databind依赖
public Object funtion(/*不用加@RequestBody,加了会报错*/ Object object){
	return Object;
}

自定义异常解析器

实现HandlerExceptionResolver后,放入容器中

public class CustomExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("错误页面");
        modelAndView.addObject("errorMsg",e.getMessage());//可以添加错误信息在页面显示
        return modelAndView;
    }
}

SpringMVC拦截器

只拦截进入@Controller的请求

springMVC.xml

<mvc:interceptors>
	<mvc:interceptor>
		<mvc:mapping path="/**"/> <!--拦截路径,拦截所有用/**-->
		<bean class="包.CustomHandlerInterceptor"/>
	</mvc:interceptor>
</mvc:interceptors>
public class CustomHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //前置方法
        return true;//true继续执行,false不进入@Controller
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //后置方法
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //最终方法
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值