springmvc学习

你看到的逆袭,不过是一场预备

springmvc入门学习笔记

目录

1丶springmvc原理

2丶搭建环境

3丶入门例子

4丶注解开发

5丶参数绑定

6丶数据回显

7丶json交互

8丶controller三种返回值

9丶restful风格

10丶全局异常

11丶上传图片

12丶拦截器

13丶springmvc和strtus2区别

14丶处理get和post乱码

详细知识点

1.1springmvc web框架

springmvcSpringMVC是一种基于Java,实现了Web MVC设计模式,请求驱动类型的轻量级Web框架,将Web层进行职责解耦,继承httpServlet,封装扩展了servlet,开发效率比一般servlet高,但一般servlet性能好。
spring体系下的:springmvcheima1/WebContent/WEB-INF/lib/spring-webmvc-4.1.3.RELEASE.jar
用途:接收浏览器的请求响应,对数据进行处理,然后返回页面进行显示。

1.2

构成:四大器,即前端控制器,处理器适配器,处理器映射器,视图解析器。
作用流程:
1、 用户发送请求至前端控制器DispatcherServlet
2、 DispatcherServlet收到请求调用HandlerMapping处理器映射器。
3、 处理器映射器根据请求url找到具体的处理器,生成处理器对象及处理器拦截器(如果有则生成)一并返回给DispatcherServlet。
4、 DispatcherServlet通过HandlerAdapter处理器适配器调用处理器
5、 执行处理器(Controller,也叫后端控制器)。
6、 Controller执行完成返回ModelAndView
7、 HandlerAdapter将controller执行结果ModelAndView返回给DispatcherServlet
8、 DispatcherServlet将ModelAndView传给ViewReslover视图解析器
9、 ViewReslover解析后返回具体View
10、 DispatcherServlet对View进行渲染视图(即将模型数据填充至视图中)。
11、 DispatcherServlet响应用户

2.1搭建环境

导包:
在这里插入图片描述
创建web-xml----------->创建springmvc.xml------->视图jsp---------->pojo---------->编写controller
web.xml tomcat启动加载web-xml,再加载springmvc.xml继续加载

3.1 web.xml
<?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" id="WebApp_ID" version="2.5">
  <display-name>springmvcheima1</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>spirngMvcheima1</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>
    <!-- 1 2 3.....代表第几个启动 -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>spirngMvcheima1</servlet-name>
    <url-pattern>*.action</url-pattern>
  </servlet-mapping>
</web-app>

springmvc.xml

<?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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" 
	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.0.xsd
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://code.alibabatech.com/schema/dubbo 
        http://code.alibabatech.com/schema/dubbo/dubbo.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.0.xsd">
        
<!-- 配置@Controller注解扫描 -->
<context:component-scan base-package="cn.itheima.controller"></context:component-scan>
        
        <!-- 如果没有显示的配置处理器映射器和处理器适配那么springMvc会去默认的dispatcherServlet.properties中查找对应的处理器映射器和处理器适配器去使用,这样每个请求都要扫描一次他的默认配置文件,效率非常低,会降低访问速度,所以要显示的配置处理器映射器和处理器适配器 -->
        <!-- 注解形式的处理器映射器 -->
		<!--         <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">     </bean> -->
        <!-- 注解形式的处理器适配器 -->
        <!--         <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">    </bean> -->
        
        <!-- 配置最新版的注解的处理器映射器 -->
        <!--         <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean> -->
        <!-- 配置最新版的注解的处理器适配器 -->
        <!--         <bean  class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean> -->

<!-- 注解驱动:	作用:替我们自动配置最新版的注解的处理器映射器和处理器适配器     -->	
<mvc:annotation-driven></mvc:annotation-driven>
	
	
	
<!-- 配置视图解析器 作用:在controller中指定页面路径的时候就不用写页面的完整路径名称了,可以直接写页面去掉扩展名的名称	-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	<!-- 真正的页面路径 =  前缀 + 去掉后缀名的页面名称 + 后缀 -->
	<!-- 前缀 -->
	<property name="prefix" value="/WEB-INF/jsp/"></property>
	<!-- 后缀 -->
	<property name="suffix" value=".jsp"></property>
</bean>
	
</beans>

controller

@Controller
public class ItemsController {
	//静态模拟
	//指定url到请求方法的映射
	//url中输入一个地址,找到这个方法.例如:localhost:8080/springmvcheima1/list.action
	@RequestMapping("/list")
	public ModelAndView  itemsList() throws Exception{
		List<Items> itemList = new ArrayList<>();
		
		//商品列表
		Items items_1 = new Items();
		items_1.setName("联想笔记本_3");
		items_1.setPrice(6000);
		items_1.setDetail("联想笔记本电脑!");
		
		Items items_2 = new Items();
		items_2.setName("苹果手机");
		items_2.setPrice(5000f);
		items_2.setDetail("苹果手机!");
		
		itemList.add(items_1);
		itemList.add(items_2);
		
		//模型和视图
		//model模型: 模型对象中存放了返回给页面的数据
		//view视图: 视图对象中指定了返回的页面的位置
		ModelAndView modelAndView = new ModelAndView();
		
		//将返回给页面的数据放入模型和视图对象中
		modelAndView.addObject("itemList", itemList);
		
		//指定返回的页面位置
		modelAndView.setViewName("itemList");
		//视图中用<c:forEach items="${itemList }" var="item">  ${item.name }    ${item.price }
		return modelAndView;

	}
4.1注解开发

@Controller @RequestMapping @ModelAttribute @SessionAttributes @PathVariable @RequestParam
@ResponseBody @RequestBody

@Controller
Controller处理由DispatcherServlet分发的请求,主要流程为:Controller调用业务处理层处理后封装成一个model,该注解标记到一个类上,说明是一个控制器类。
@RequestMapping
处理请求地址的映射,可以用在类或者方法中,这样访问的地址就得加上本注解的值,属性有value,method 等。
    @RequestMapping ( "/test/{variable1}" )
    public class MyController {
       @RequestMapping ( "/showView/{variable2}" )
       public ModelAndView showView( @PathVariable String  variable1, @PathVariable ( "variable2" ) 
@ModelAttribute
两种方式:一种标注在方法上,一种标注到方法参数上
该注解的方法会先执行,把返回的对象存在session或者模型属性中,如模型属性(ModelAttribute("attributeName")),若未指定,返回的是类名称(首字母小写)作为属性名称,再执行真正请求的方法
	@ModelAttribute("tmodel")
	public TModel t(){
	    TModel t = new TModel();t.setEmail("dfdafdasf");
	    return t;
	}
		@RequestMapping("item")
	public TModel t(){
	    TModel t = new TModel();t.setEmail("dfdafdasf");
	    return t;
	}
	@ModelAttribute单独在方法上使用,同时结合@ModelAttribute使用在形参上
    	@ModelAttribute("tmodel")
    	public TModel t(){
    	    TModel t = new TModel();t.setEmail("dfdafdasf1");
    	    return t;
    	}
    	    @RequestMapping(value = "/activity_view2", method = RequestMethod.GET)
    	    public String f3(@ModelAttribute("tmodel") TModel email){
    	        return "migucactivites/migucactivites_config";
    	    }
这种情况下,根据debug,也是在requestmapping处理完毕以后,才真正写入到session中的。
但是,这里spring Mvc做了处理,在形参处,可以获取到在t方法中设置的tmodel值。虽然此时session中其实没有这个内容。
@SessionAttributes
	@SessionAttributes只能使用在类定义上。
    若希望在多个请求之间共用某个模型属性数据,则可以在
    控制器类上标注一个 @SessionAttributes, Spring MVC
	将在模型中对应的属性暂存到 HttpSession 中
 @SessionAttributes(value={"names"},types={Integer.class})
  @Controller
  public class Test {
    @RequestMapping("/test")
     public String test(Map<String,Object> map){
        map.put("names", Arrays.asList("caoyc","zhh","cjx"));
        map.put("age", 18);
        return "hello";
    }
}
两者一起用:
@Controller
@RequestMapping(value = "/migucactivites")
@SessionAttributes("tmodel")
public class MigucActivityController {	    
        @RequestMapping(value = "/activity_view2", method = RequestMethod.GET)
	    public String f3(@ModelAttribute("tmodel") TModel email){
	        return "migucactivites/migucactivites_config";
	    }
}
这种情况下,@ModelAttribute一定会去session中找对应的tmodel对象。如果找不到,就会报错,请求在后台直接抛出异常。
如果session中有tmodel对象,传入连接中没有传入email字段,则email直接得到的是session中值,并且会把值再set回model中,并放到session中。
如果session中有tmodel对象,并且传入参数也有email值。例如url:http://127.0.0.1:8081/migucactivites/activity_view2.htm?email=2d,这种情况下,代码email的值为2d,并且也会把tmodel=2d放到model中,放到session中

@PathVariable
@RequestParam
    @pathVariable("pageSize") 	需要配合rest风格url使用,目的是接收rest Url中的参数 	http://127.0.0.1:8082/hello/4
    @RequestParam((value = "pageSize", required = false, defaultValue = "10")) 	接收普通?后面携带的参数 	http://127.0.0.1:8082/hello?pageSize=4
    @RequestMapping(value = "/hello/{pageSize}", method = RequestMethod.GET)
    public String say(@PathVariable("pageSize") String pageSize) {
        return pageSize;
    }
    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String say2(@RequestParam(value = "pageSize", required = false, defaultValue = "10") String pageSize) {
        return pageSize;
    }
@ResponseBody
@RequestBody  
	//请求json串(商品信息),输出json(商品信息)
	//@RequestBody将请求的商品信息的json串转成itemsCustom对象
	//@ResponseBody将itemsCustom转成json输出
	@RequestMapping("/requestJson")
	public @ResponseBody ItemsCustom requestJson(@RequestBody ItemsCustom itemsCustom){
		//@ResponseBody将itemsCustom转成json输出
		return itemsCustom;
	}
	//请求key/value,输出json
	@RequestMapping("/responseJson")
	public @ResponseBody ItemsCustom responseJson(ItemsCustom itemsCustom){
		//@ResponseBody将itemsCustom转成json输出
		return itemsCustom;
	}
@RequestHeader
@CookieValue
    可以把Request请求header部分的值绑定到方法的参数上。
5.1参数绑定

意思:把客服端传过来的数据如key/value的数据,绑定到controller中方法的形参上,则此过程名为参数绑定。
适配器中注入参数绑定。
1:默认支持的参数绑定类型:
HttpServletRequest HttpServletResponse HttpSession Modelj接口 ModelMap实现类.

直接在controller的方法参数上加入HttpServletRequest对象,用途将前端传过来的数据封装到域中.
public ModelAndView queryItems(Model model)
如model.addAttribute("user", user);

:2:简单参数绑定:
在springmvc方法中不用传入的参数名称和方法参数名称一致,可以用@RequestParam来绑定简单类型参数,如果不用此注解,则必须一致。
传入参数和形参一致的情况:

    @RequestMapping("/updateitem1")
    //没用request.getParameter(id);都可以获取到传入的值。
    public String update1(Integer id, String name, Float price, String detail) throws Exception {
        Items items = new Items();
        items.setId(id);
        items.setName(name);
        items.setPrice(price);
        items.setDetail(detail);
        itemsService.updateItems(items);
        return "success";
    }
    jsp:
	<form id="itemForm"    action="${pageContext.request.contextPath }/updateitem1.action" method="post">
        <input type="hidden" name="id" value="${item.id }" /> 修改商品信息:
        <table width="100%" border=1>
            <tr>
                <td>商品名称</td>
                <td><input type="text" name="name" value="${item.name }" /></td>
            </tr>
            ....price detail 

用注解不一致的情况:

	@RequestMapping(value = "/editItems", method = { RequestMethod.POST,RequestMethod.GET })
	// @RequestParam里边指定request传入参数名称和形参进行绑定,本例中id和items_id绑定。
	// 通过required属性指定参数是否必须要传入
	// 通过defaultValue可以设置默认值,如果id参数没有传入,将默认值和形参绑定。
	public String editItems(Model model,@RequestParam(value = "id", required = true) Integer items_id) throws Exception {

		// 调用service根据商品id查询商品信息
		ItemsCustom itemsCustom = itemsService.findItemsById(items_id);
		// 通过形参中的model将model数据传到页面
		// 相当于modelAndView.addObject方法
		model.addAttribute("items", itemsCustom);

		return "items/editItems";
	}

3:pojo绑定:
需要页面上的input中的name属性和pojo属性名一致。

实体类User.java
package cn.itheima.pojo;
import java.util.Date;
public class User {
    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username == null ? null : username.trim();
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex == null ? null : sex.trim();
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address == null ? null : address.trim();
    }
}
editItem.jsp
<form id="itemForm"    action="${pageContext.request.contextPath }/updateitem2.action" method="post">
        <input type="hidden" name="id" value="${item.id }" /> 修改商品信息:
        <table width="100%" border=1>
            <tr>
                <td>商品名称</td>
                <td><input type="text" name="name" value="${item.name }" /></td>
            </tr>
            <tr>
                <td>商品价格</td>
                <td><input type="text" name="price" value="${item.price }" /></td>
            </tr>
            <tr>
                <td>商品简介</td>
                <td><textarea rows="3" cols="30" name="detail">${item.detail }</textarea>
                </td>
            </tr>
            <tr>
                <td colspan="2" align="center"><input type="submit" value="提交" />
                </td>
            </tr>
        </table>
    </form>
Controller:
    @RequestMapping("/updateitem2")
    public String update2(Items items) throws Exception {
    //Items /pojo类中的属性和input中属性需一致
        itemsService.updateItems(items);
        return "success";
    }

4:包装pojo类型绑定:

jsp:
<input name="itemsCustom.name">
controller;
public ModelAndView 	queryItems(HttpServletRequest request,ItemsQueryVo itemsQueryVo);
pojo包装:
public class ItemsQueryVo
{
	private Items items;
	//此属性.属性为input输出的name
	private ItemsCustom itemsCustom;
}

5:数组类型参数绑定

例如批量删除
input和形参相同items_id  
将多个商品的id传给controller方法的形参,这个形参就是数组
controller:
// 批量删除 商品信息
	@RequestMapping("/deleteItems")
	public String deleteItems(Integer[] items_id) throws Exception {
		// 调用service批量删除商品
		// ...
		return "success";
	}
	jsp:
	<td><input type="checkbox" name="items_id"         value="${item.id}"/></td>

6:list类型参数绑定

jsp页面传入的数据和形参绑定起来,形参用包装类,方法体中用存包装类的list集合接收
input中name和vo中属性一致
controller:
	@RequestMapping("/editItemsQuery")
	public ModelAndView editItemsQuery(HttpServletRequest request,
		ItemsQueryVo itemsQueryVo) throws Exception {
		// 调用service查找 数据库,查询商品列表
		List<ItemsCustom> itemsList = itemsService.findItemsList(itemsQueryVo);
		// 返回ModelAndView
		ModelAndView modelAndView = new ModelAndView();
		// 相当 于request的setAttribut,在jsp页面中通过itemsList取数据
		modelAndView.addObject("itemsList", itemsList);
		modelAndView.setViewName("items/editItemsQuery");
		return modelAndView;
	}
jsp:
<c:forEach items="${itemsList }" var="item" varStatus="status">
<tr>	
	<td><input name="itemsList[${status.index }].name" value="${item.name }"/></td>
	<td><input name="itemsList[${status.index }].price" value="${item.price }"/></td>
	<td><input name="itemsList[${status.index }].createtime" value="<fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>"/></td>
	<td><input name="itemsList[${status.index }].detail" value="${item.detail }"/></td>
</tr>
</c:forEach>
	// 批量修改商品提交
	// 通过ItemsQueryVo接收批量提交的商品信息,将商品信息存储到itemsQueryVo中itemsList属性中。
	@RequestMapping("/editItemsAllSubmit")
	public String editItemsAllSubmit(ItemsQueryVo itemsQueryVo)
			throws Exception {

		return "success";
	}

7:自定义参数绑定:
如日期类型,将页面输入中的日期字符串转化为pojo中日期属性类型,即java.util.Data类型。

public class CustomGlobalStrToDateConverter implements Converter<String, Date> {

	@Override
	public Date convert(String source) {
		try {
			Date date = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(source);
			return date;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	springmvc中:
		<!-- 配置自定义转换器 
	注意: 一定要将自定义的转换器配置到注解驱动上
	-->
	<bean id="conversionService"
		class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
		<property name="converters">
			<set>
				<!-- 指定自定义转换器的全路径名称 -->
				<bean class="cn.itheima.controller.converter.CustomGlobalStrToDateConverter"/>
			</set>
		</property>
	</bean>
6.1数据回显

springmvc默认回显pojo
pojo数据用input输入传到方法中,springmvc自动回显到input中,数据自动存到request域中,key为小写的pijo类名。
@modelAttribute制定pojo回显到页面在request中的key。

public String editItemSubmit(Model model , @ModelAttribute("item") ItemsCustom itemsCustom)
<td><input type="text"name="name" value="${item.name}"/></td>
如果不用@ModelAttribute也可以使用model.addAttribute("item", itemsCustom)完成数据回显。

@modelAttribute可以将方法的返回值传到页面。

   @ModelAttribute("itemtypes")
      public Map<String, String>getItemTypes(){
        Map<String,String> itemTypes = new HashMap<String,String>();
        itemTypes.put("101", "数码");
        itemTypes.put("102", "母婴")
        return itemTypes;
      }
<select name="itemtype">
   <c:forEach items="${itemtypes }" var="itemtype">
      <option value="${itemtype.key}">${itemtype.value }</option>   
   </c:forEach>
</select>
7.1json数据交互

导包

	//导入jackson的jar包在 controller的方法中可以使用@RequestBody,让spirngMvc将json格式字符串自动转换成java中  的pojo
	//页面json的key要等于java中pojo的属性名称
	//controller方法返回pojo类型的对象并且用@ResponseBody注解,springMvc会自动将pojo对象转换成json格式字符串
	@RequestMapping("/sendJson")
	@ResponseBody
	public Items json(@RequestBody Items items) throws Exception{
		System.out.println(items);
		return items;
	}
	<script type="text/javascript">
	function sendJson(){
		//请求json响应json
		$.ajax({
			type:"post",
			url:"${pageContext.request.contextPath }/items/sendJson.action",
			contentType:"application/json;charset=utf-8",
			data:'{"name":"测试商品","price":99.9}',
			success:function(data){
				alert(data);
			}
		});
	}
8.1controller方法返回值

1:modelAndView
modelAndView.addObject(“itemList”,list);
modelAndView.setViewName(“itemList”);
2:String
页面的逻辑视图名

//返回数据
    request.setAttribute("", arg1);
		//指定返回的页面(如果controller方法返回值为void,则不走springMvc组件,所以要写页面的完整路径名称)
	request.getRequestDispatcher("/WEB-INF/jsp/success.jsp").forward(request, response);
		
		     ]//重定向:浏览器中url发生改变,request域中的数据不可以带到重定向后的方法中
	model.addAttribute("id", items.getId());
		     //在springMvc中凡是以redirect:字符串开头的都为重定向
	return "redirect:itemEdit/"+items.getId();
		
		     //请求转发:浏览器中url不发生改变,request域中的数据可以带到转发后的方法中
	model.addAttribute("id", items.getId());
		     //spirngMvc中请求转发:返回的字符串以forward:开头的都是请求转发, 
		     //后面forward:itemEdit.action表示相对路径,相对路径就是相对于当前目录,当前为类上面指定的items目录.在当前目录下可以使用相对路径随意跳转到某个方法中
		     //后面forward:/itemEdit.action路径中以斜杠开头的为绝对路径,绝对路径从项目名后面开始算
	return "forward:/items/itemEdit.action";

3:void
不走springmvc组件,需写完整路径名
类似一般servlet,用request.setAttribute request.getRequestDispatche("")r.forward(request,response)

9.1restful风格

url的命名风格,Restful就是一个资源定位及资源操作的风格。不是标准也不是协议,只是一种风格,是对http协议的诠释。
资源定位:互联网所有的事物都是资源,要求url中没有动词,只有名词。没有参数
Url格式:http://blog.csdn.net/beat_the_world/article/details/45621673
资源操作:使用put、delete、post、get,使用不同方法对资源进行操作。分别对应添加、删除、修改、查询。一般使用时还是post和get。Put和Delete几乎不使用。
资源是以json(或其他Representation)为载体的、面向用户的一组数据集,资源对信息的表达倾向于概念模型中的数据:
相对而言,数据(尤其是数据库)是一种更加抽象的、对计算机更高效和友好的数据表现形式,更多的存在于逻辑模型中
REST最大的几个特点为:资源、统一接口、URI和无状态。
在这里插入图片描述

10.1异常处理

自定义异常处理器,全局处理,在springmvc中,一般把dap,servlet,controller通过throws Exception向上抛出,最后交给springmvc的异常处理器

<!-- 配置全局异常处理器 -->
	<bean class="cn.itheima.exception.CustomGlobalExceptionResolver"></bean>
11.1上传图片

企业项目一般用图片服务器存图片,不放硬盘
本例中在tomcat中配置图片虚拟目录,在tomcat server中 点击modules------->add web module
document base E:\image path /pic
那么就可以对外访问localhost:/8080/pic/m.jpg
或者可以修改tomcat:在conf/server.xml文件,添加虚拟 目录 :

导入上传图片的两个包
<form id="itemForm" action="${pageContext.request.contextPath }/items/updateitem" method="post" enctype="multipart/form-data">
	<tr>
				<td>商品图片</td>
				<td>
					<c:if test="${item.pic !=null}">
						<img src="/pic/${item.pic}" width=100 height=100/>
						<br/>
					</c:if>
					<input type="file"  name="pictureFile"/> 
				</td>
			</tr>
				<tr>
				<td colspan="2" align="center"><input type="submit" value="提交" />
				</td>
			</tr>
	<!-- 文件上传 -->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 设置上传文件的最大尺寸为5MB -->
		<property name="maxUploadSize">
			<value>5242880</value>
		</property>
	</bean>
	//商品修改提交
	@RequestMapping("/editItemSubmit")
	public String editItemSubmit(Items items, MultipartFile pictureFile)throws Exception{
		
		//原始文件名称
		String pictureFile_name =  pictureFile.getOriginalFilename();
		//新文件名称
		String newFileName = UUID.randomUUID().toString()+pictureFile_name.substring(pictureFile_name.lastIndexOf("."));
		
		//上传图片
		File uploadPic = new java.io.File("F:/develop/upload/temp/"+newFileName);
		
		if(!uploadPic.exists()){
			uploadPic.mkdirs();
		}
		//向磁盘写文件
		pictureFile.transferTo(uploadPic);

.....

12.1拦截器

springmvzc中拦截器类似servlet中的filter

	<!-- 配置拦截器 -->
	<mvc:interceptors>
		<!-- 多个拦截器的执行顺序等于springMvc.xml中的配置顺序 -->
<!-- 	<mvc:interceptor> -->
			<!-- 拦截请求的路径    要拦截所有必需配置成/** -->
<!-- 			<mvc:mapping path="/**"/> -->
			<!-- 指定拦截器的位置 -->
<!-- 			<bean class="cn.itheima.interceptor.Interceptor1"></bean> -->
<!-- 	</mvc:interceptor> -->
		
<!-- 	<mvc:interceptor> -->
			<!-- 拦截请求的路径    要拦截所有必需配置成/** -->
<!-- 			<mvc:mapping path="/**"/> -->
			<!-- 指定拦截器的位置 -->
<!-- 			<bean class="cn.itheima.interceptor.Interceptor2"></bean> -->
<!-- 	</mvc:interceptor> -->
		
		<mvc:interceptor>
			<!-- 拦截请求的路径    要拦截所有必需配置成/** -->
			<mvc:mapping path="/**"/>
			<!-- 指定拦截器的位置 -->
			<bean class="cn.itheima.interceptor.LoginInterceptor"></bean>
		</mvc:interceptor>
	</mvc:interceptors>
用户身份认证
Public class LoginInterceptor implements HandlerInterceptor{

	@Override
	Public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {

		//如果是登录页面则放行
		if(request.getRequestURI().indexOf("login.action")>=0){
			return true;
		}
		HttpSession session = request.getSession();
		//如果用户已登录也放行
		if(session.getAttribute("user")!=null){
			return true;
		}
		//用户没有登录跳转到登录页面
		request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
		return false;
	}
}

用户登陆controller
//登陆页面
	@RequestMapping("/login")
	public String login(Model model)throws Exception{
		
		return "login";
	}
	//登陆提交
	//userid:用户账号,pwd:密码
	@RequestMapping("/loginsubmit")
	public String loginsubmit(HttpSession session,String userid,String pwd)throws Exception{
		//向session记录用户身份信息
		session.setAttribute("activeUser", userid);
		return "redirect:item/queryItem.action";
	}
	//退出
	@RequestMapping("/logout")
	public String logout(HttpSession session)throws Exception{
		//session过期
		session.invalidate();
		return "redirect:item/queryItem.action";
	}
发送请求,先进行拦截,判断,跳转,再拦截,再执行
13.1springmvc和strtus2区别

springmvc速度快于strtus2
springmvc基于方法,单例开发,strtus2基于类,只能多例开发
springmvc将url和controller的方法进行映射,生成一个handler对象,只包括此方法,完毕即销毁。

14.1解决get和pos乱码

post

  <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>

get

第一种:修改tomcat配置文件,让工程编码和tomcat一致。
第二种,代码参数修改:
String name=new  String(request.getParamter("name").getBytes("iso8859-1"),"utf-8");
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值