Spring MVC 简单入门

Spring MVC 简单入门

Spring MVC 与Struts2 在web 应用中所要达到的效果是一样的, 但是 spring MVC 更简单方便 一点, struts2 比较复杂

阐述一下简历 spring MVC 的步骤

1.  在 web.xml 中  配置

  spring 的文件名中要 以 -servlet 为结尾   springmvc-servlet.xml 

	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<!-- 不要使用/* -->
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>


2. spring mvc 可以用配置文件 这里用到的是注解 方式

 

<!-- 
		component-scan已经支持了注解的驱动
		<mvc:annotation-driven/> -->
		
		<context:component-scan base-package="com.ithm.controller"/>
<!--视图解析器 /WEB-INF/jsp/index.jsp -->
		<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
			<property name="prefix" value="/WEB-INF/jsp/"></property>
			<property name="suffix" value=".jsp"></property>
		</bean>


prefix 代表返回客户端的路径     suffix 代表 返回文件的 类型 在服务端返回的方法 看下面的配置

 

 

@Controller
@RequestMapping("/test")//标识当前的controller,相当于命名空间
public class TestController {
@RequestMapping("/hello.do")
	public String hello(){
		System.out.println("hello springmvc anno");
		return "jsp1/index";
	}
}

 @RequestMapping("/hello.do")

代表 访问的路径如果 是hello.do 就会访问到这个hello 这个方法  如果 类上面 加 RequestMapping  代表一个模块 路径 要变成 test./hello.do

 

3, 如果在业务用用到转发

 

配置如下:

 @RequestMapping("/redirect1.do")
 public String redirect1(){
  return "redirect:toForm.do";
  //return "redirect:/test/toForm.do"; 如果转发到其他模块的方法 路径模块的命令空间
 }

 

4. spring mvc 方法的参数是经常用到的

 

(1)  参数列表可以支持HttpServletRequest 

客户端request 可以直接获取客户端的属性 值

@RequestMapping("/toPerson.do")
	public String toPerson(HttpServletRequest request){
		String name = request.getParameter("name");
		System.out.println(name);
		return "jsp1/index";
	}
 
 

(2) 使用ModelAndView可以返回给页面结果集    作用域 就是 request 作用域

@RequestMapping("/toPerson4.do")
	public ModelAndView toPerson4(){
		Person person = new Person();
		person.setName("zhangsan");
		person.setId(1);
		person.setAddress("beijing");
		person.setAge(22);
		person.setBirthday(new Date());
		Map<String, Object> map = new HashMap<String,Object>();
		//把结果集放到map里,相当于request.setAttribute("p", person);
		map.put("p", person);
		
		return new ModelAndView("jsp1/index", map);
		
	}

 

(3)  Model 和View分开来写,在参数列表中直接定义Model,建议使用

 

@RequestMapping("/toPerson5.do")
	public String toPerson5(Model model){
		Person person = new Person();
		person.setName("zhangsan");
		person.setId(1);
		person.setAddress("beijing");
		person.setAge(22);
		person.setBirthday(new Date());
		//相当于request.setAttribute("p", person);
		model.addAttribute("p", person);
		return "jsp1/index";
	}

 

spring mvc 文件上传

 

<form action="test/toPerson10.do" method="post" enctype="multipart/form-data">
    		id:<input type="text" name="id"><br>
    		name:<input type="text" name="name"><br>
    		age:<input type="text" name="age"><br>
    		address:<input type="text" name="address"><br>
    		birthday:<input type="text" name="birthday"><br>
    		pic:<input type="file" name="pic">
    		<input type="submit" value="submit"><br>
    	</form>


spring 文件配置

<!-- 注意id=multipartResolver必须要配 -->
		<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
			<!-- maxUploadSize:文件最大限制,单位是字节 -->
			<property name="maxUploadSize" value="10485760"></property>
		</bean>

 

	@RequestMapping("/toPerson10.do")
	public String toPerson10(Person person, HttpServletRequest request) throws IOException{
		//强制转换request
		MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
		//接收文件
		CommonsMultipartFile cfile =  (CommonsMultipartFile) mr.getFile("pic");
		//拿到字节数组
		byte[] fbyte = cfile.getBytes();
		
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		
		String fileName = format.format(new Date());
		Random random = new Random();
		for(int i = 0; i < 3; i++){
			fileName = fileName + random.nextInt(10);
		}
		//获得原始文件名
		String origFileName = cfile.getOriginalFilename();
		//后缀名
		String suffix = origFileName.substring(origFileName.lastIndexOf("."));
		//拿到跟目录的路径
		String path = request.getSession().getServletContext().getRealPath("/");
		//定义输出流
		OutputStream out = new FileOutputStream(new File(path+"/upload/"+fileName+suffix));
		out.write(fbyte);
		out.flush();
		out.close();
		
		return "success";
		
	}
 
 


定一个指定的时间类型的属性编辑器 (客户端日期格式可以根据编辑器进行转化,与实体类的类型对应

 

@InitBinder
	public void initBinder(ServletRequestDataBinder binder){
		binder.registerCustomEditor(Date.class, 
				new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
	}

 


Spring mvc 自定义拦截器

 

spring配置文件

		<mvc:interceptors>
			<mvc:interceptor>
				<!-- <mvc:mapping path="/test/**"/> -->
				<mvc:mapping path="/**"/>
				<bean class="com.ithm.interceptor.MyInterceptor"></bean>
			</mvc:interceptor>
		</mvc:interceptors>


 

public class MyInterceptor implements HandlerInterceptor {

	/**
	 * 最终拦截:执行时机页面已经生成之后,主要记录异常信息,try catch 中finally
	 */
	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception ex)
			throws Exception {
		System.out.println("afterCompletion");
		ex.printStackTrace();
	}

	/**
	 * 后置拦截:执行时机controller之后在视图解析器解析视图之前,用于追加或统一修改数据
	 */
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView mv) throws Exception {
		Map<String, Object> map = mv.getModel();
		map.put("ph", "postHandle text");
		System.out.println("postHandle...");
	}

	/**
	 * 执行时机:在controller之前执行
	 * 布尔返回值类型:true放行,false被拦截
	 */
	@Override
	public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object obj) throws Exception {
		System.out.println("preHandler...");
		System.out.println(obj.getClass());
		return true;
	}

}


 



 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值