码迷,mamicode.com
首页 > 编程语言 > 详细

springmvc的快速实例

时间:2016-05-27 12:01:58      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:

创建好web项目后:

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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	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">
	
	<!-- 中央控制器 -->
	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<!-- struts习惯使用/*,在springmvc不管用 -->
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
	
</web-app>
springmvc-servlet.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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">                            
        <!-- 需要配置controller,handlerMapping,ViewResolver, interceptor -->
        
        <!-- 映射处理器之间是独立的,不相互影响 -->
        <!-- 默认的映射处理器 -->
        <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>
        
        <!-- 简单url的映射处理器 -->
        <bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
            <property name="mappings">
                <props>
                    <prop key="/hello1.do">testController</prop>
                </props>
            </property>
        </bean>
        
        <!-- 控制器的类名映射处理器 -->
        <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"></bean>
        
        <!-- 使用默认的映射处理器来映射controller -->
        <bean id="testController" name="/hello.do" class="cn.itcast.springmvc.TestController"></bean>
        
        <!-- 前缀+ viewName +后缀 -->
        <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <!-- webroot到某一指定的文件夹的路径 -->
            <property name="prefix" value="/WEB-INF/jsp/"></property>
            <!-- 视图名称的后缀 -->
            <property name="suffix" value=".jsp"></property>
        </bean>
</beans>
TestController.java                                                                                                                                                                                 

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class TestController extends AbstractController {

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest arg0,
			HttpServletResponse arg1) throws Exception {
		System.out.println("hello springmvc");
		//viewName不是jsp的名称而是前缀与后缀之间的路径字符串
		return new ModelAndView("jsp1/index");
	}
	
	

}

这就完成了springmvc的web层的简单开发了。大概已经了解springmvc的web开发的步骤。

注解开发模式:

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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	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">
	
	<!-- 中央控制器 -->
	<servlet>
		<servlet-name>springmvc</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>
	</servlet>
	
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<!-- struts习惯使用/*,在springmvc不管用 -->
		<url-pattern>*.do</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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-3.0.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">							
		
		<!-- mvc的注解驱动 -->
		<mvc:annotation-driven/>
		<!-- 一旦有扫描器的定义mvc:annotation-driven不需要,扫描器已经有了注解驱动的功能 -->
		<context:component-scan base-package="cn.itcast.springmvc"/>
		
		
		<!-- 前缀+ viewName +后缀 -->
		<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
			<!-- webroot到某一指定的文件夹的路径 -->
			<property name="prefix" value="/WEB-INF/jsp/"></property>
			<!-- 视图名称的后缀 -->
			<property name="suffix" value=".jsp"></property>
		</bean>
		
		<!-- id="multipartResolver"必须是multipartResolver -->
		<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
			<!-- maxUploadSize:文件上传的最大值以byte为单位 -->
			<property name="maxUploadSize" value="1024000"></property>
		</bean>
		
		<mvc:interceptors>
			<mvc:interceptor>
				<!-- 某一模块的拦截:/myPath/**, 拦截所有的请求/**-->
				<mvc:mapping path="/**"/>
				<bean class="cn.itcast.springmvc.interceptor.MyIntercepor"></bean>
			</mvc:interceptor>
		</mvc:interceptors>
</beans>
TestController.java                                                                                                                                                                                              
@Controller//用来标注当前类是springmvc的控制层的类
@RequestMapping("/test")//controller的唯一标识或者命名空间
public class TestController {
	/**
	 * desc:方法的返回值是ModelAndView中的viewName
	 */
	@RequestMapping("/hello.do")//用来访问控制层的方法的注解
	public String hello(){
		System.out.println("hello springmvc with annotation");
		return "jsp1/index";
	}
	
	/**
	 * desc:HttpServletRequest可以直接定义在参数的列表,可以使用
	 */
	@RequestMapping("/toPerson.do")
	public String toPerson(HttpServletRequest request){
		String result = request.getParameter("name");
		System.out.println(result);
		return "jsp1/index";
	}
	
	/**
	 * 
	 * desc:在参数列表上直接定义要接收的参数名称,只要参数名称能匹配的上就能接收所传过来的数据,
	 * 可以自动转换成参数列表里面的类型,注意的是值与类型之间是可以转换的
	 */
	@RequestMapping("/toPerson1.do")
	public String toPerson1(String name, Integer age, String address, Date birthday){
		System.out.println(name + " "+ age + " "+ address + " " +birthday);
		return "jsp1/index";
	}
	
	/**
	 * 
	 * desc:传递的参数的名字必须要与实体类的属性set方法后面的字符串匹配的上才能接收到参数,首字符的大小写不区分
	 * 请求中传的参数只要是能和参数列表里面的变量名或者实体里面的set后面的字符串匹配的上就能接收到
	 */
	@RequestMapping("/toPerson2.do")
	public String toPerson2(Person person, User user){
		System.out.println(person);
		System.out.println(user);
		return "jsp1/index";
	}
	
	/**
	 * 
	 * desc:对数组的接收
	 */
	@RequestMapping("/toPerson3.do")
	public String toPerson3(String[] name){
		for(String result : name){
			System.out.println(result);
		}
		return "jsp1/index";
	}
	
	/**
	 * 
	 * desc:方法的返回值采用ModelAndView, new ModelAndView("index", map);
	 * ,相当于把结果数据放到request里面
	 */
	@RequestMapping("/toPerson4.do")
	public ModelAndView toPerson4() throws Exception{
		Person person = new Person();
		person.setName("james");
		person.setAge(28);
		person.setAddress("maami");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date date = format.parse("1985-04-22");
		person.setBirthday(date);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("p", person);
		return new ModelAndView("index", map);
	}
	
	/**
	 * 
	 * desc:直接在方法的参数列表中来定义Map,这个Map即使ModelAndView里面的Map,
	 * 由视图解析器统一处理,统一走ModelAndView的接口
	 * 也不建议使用
	 */
	@RequestMapping("/toPerson5.do")
	public String toPerson5(Map<String, Object> map) throws Exception{
		Person person = new Person();
		person.setName("james");
		person.setAge(28);
		person.setAddress("maami");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date date = format.parse("1985-04-22");
		person.setBirthday(date);
		map.put("p", person);
		return "index";
	}
	/**
	 * 
	 * desc:在参数列表中直接定义Model,model.addAttribute("p", person);把参数值放到request类里面去,建议使用
	 */
	@RequestMapping("/toPerson6.do")
	public String toPerson6(Model model) throws Exception{
		Person person = new Person();
		person.setName("james");
		person.setAge(28);
		person.setAddress("maami");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date date = format.parse("1985-04-22");
		person.setBirthday(date);
		//把参数值放到request类里面去
		model.addAttribute("p", person);
		return "index";
	}
	
	/**
	 * 
	 * desc:ajax的请求返回值类型应该是void,参数列表里直接定义HttpServletResponse,
	 * 获得PrintWriter的类,最后可把结果写到页面
	 * 不建议使用
	 */
	@RequestMapping("/ajax.do")
	public void ajax(String name, HttpServletResponse response){
		String result = "hello " +name;
		try {
			response.getWriter().write(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 
	 * desc:直接在参数的列表上定义PrintWriter,out.write(result);把结果写到页面,建议使用的
	 */
	@RequestMapping("/ajax1.do")
	public void ajax1(String name, PrintWriter out){
		String result = "hello " +name;
		out.write(result);
	}
	
	@RequestMapping("/toAjax.do")
	public String toAjax(){
		return "ajax";
	}
	@RequestMapping("/toForm.do")
	public String toForm(){
		return "form";
	}
	
	/**
	 * 
	 * desc:controller内部重定向,redirect:加上同一个controller中的requestMapping的值
	 */
	@RequestMapping("/redirectToForm.do")
	public String redirectToForm(){
		return "redirect:toForm.do";
	}
	
	/**
	 * 
	  * desc:controller之间的重定向:必须要指定好controller的命名空间再指定requestMapping的值,
	 * redirect:后必须要加/,是从根目录开始

	 */
	@RequestMapping("/redirectToForm1.do")
	public String redirectToForm1(){
		return "redirect:/test1/toForm.do";
	}
	
	
	
       /**
 	 * 
 	 * desc:@RequestMapping( method=RequestMethod.POST )可以指定请求方式,前台页面就必须要以它制定好的方式来访问,否则出现405错误
	 */
	@RequestMapping(value="/toPerson7.do", method=RequestMethod.POST )
	public String toPerson7(Person person){
		System.out.println(person);
		return "jsp1/index";
	}
	
	@RequestMapping(value="/toPerson8.do")
	public String toPerson8(Person person,HttpServletRequest request) throws Exception{
		 //第一步转化request
		MultipartHttpServletRequest rm = (MultipartHttpServletRequest) request;
		 //获得文件
		CommonsMultipartFile cfile = (CommonsMultipartFile) rm.getFile("pic");
		//获得文件的字节数组
		
		
		byte[] bfile = cfile.getBytes();
		String fileName = "";
		//获得当前时间的最小精度
		SimpleDateFormat format =  new SimpleDateFormat("yyyyMMddHHmmssSSS");
		fileName = format.format(new Date());
		//获得三位随机数
		Random random = new Random();
		for(int i = 0; i < 3; i++){
 			fileName = fileName + random.nextInt(9);
		}
		 //获得原始文件名
		String origFileName = cfile.getOriginalFilename();
		//XXX.jpg
		String suffix = origFileName.substring(origFileName.lastIndexOf("."));
		//拿到项目的部署路径
		String path = request.getSession().getServletContext().getRealPath("/");
		//定义文件的输出流
		OutputStream out = new FileOutputStream(new File(path+"/upload/"+fileName+suffix));
		out.write(bfile);
		out.flush();
		out.close();
		
		return "jsp1/index";
	 }
	
 	/**
	 * 
	 * desc:注册时间类型的属性编辑器
	 */
	@InitBinder
	public void initBinder(ServletRequestDataBinder binder){
		binder.registerCustomEditor(Date.class,
				new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
	}

}
MyIntercepor.java                                                                                                                                                                                        

public class MyIntercepor 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();
		System.out.println("================");
	}

	/**
	 * 执行时机:controller执行完,视图解析器没有把视图解析成页面,
	 * 对视图做统一的修改,主要体现在Model上
	 */
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView mv) throws Exception {
		System.out.println("postHandler...");
		Map<String, Object> map = mv.getModel();
		map.put("test", "append something");
	}

	/**
	 * 执行时机:在执行controller之前来执行
	 * 返回值类型:boolean:true代表放行可以访问controller,false不可以访问controller
	 */
	@Override
	public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2) throws Exception {
		System.out.println("preHander...");
		return true;
	}

}
实体类                                                                                                                                                                                                            

Person.java

public class Person {
	
	private String name;
	
	private Integer age;
	
	private String address;
	
	private Date birthday;
       //省略set/get
}

User.java

public class User {
	
	private String name;
	private Integer age;
       //省略get/set
 }
jsp页面                                                                                                                                                                                                              

form.jsp

<form action="test/toPerson8.do" method="post" enctype="multipart/form-data">
    	name:<input name="name" type="text"><br>
    	age:<input name="age" type="text"><br>
    	address:<input name="address" type="text"><br>
    	birthday:<input name="birthday" type="text"><br>
    	pic:<input type="file" name="pic"><br>
    	<input type="submit" value="submit"><br>
    </form>
ajax.jsp
	<script type="text/javascript" src="js/jquery-1.6.2.js"></script>
  	<script type="text/javascript">
  		$(function(){
  			$("#mybutton").click(function(){
  				$.ajax({
  					url:"test/ajax1.do",
  					type:"post",
  					dataType:"text",
  					data:{
  						name:"zhangsan"
  					},
  					success:function(responseText){
  						alert(responseText);
  					},
  					error:function(){
  						alert("system error");
  					}
  				});
  			});
  		});
  		
  	</script>
  </head>
  
  <body>
  	<input id="mybutton" type="button" value="click">
  </body>

springmvc的快速实例

标签:

原文地址:http://blog.csdn.net/qq_30641447/article/details/51495778

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!