springMVC 简单应用

一,controller

FileController
package com.dkt.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;

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

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;


@Controller
@Scope(value="prototype")
@RequestMapping(value="/file")
public class FileController {
	//上传单个文件
	@RequestMapping(value="/uploadFile.do")
	public String uploadFile(@RequestParam(value="file")  MultipartFile file,HttpServletRequest request){
		String pathString = request.getSession().getServletContext().getRealPath("/")+"file/"+file.getOriginalFilename();
		File targfile = new File(pathString);
		try {
			file.transferTo(targfile);
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "redirect:/file/showFile.do";// 重定向到controller类的方法中
	}
	//上传多个文件
	@RequestMapping(value="/uploadFiles.do")
	public ModelAndView uploadFiles(HttpServletRequest request){
		MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest)request;
		Iterator<String> fileNames = mRequest.getFileNames();
		while (fileNames.hasNext()) {
			MultipartFile mf = mRequest.getFile(fileNames.next());
			String realPath = request.getSession().getServletContext().getRealPath("/")+"file/"+mf.getOriginalFilename();
			try {
				mf.transferTo(new File(realPath));
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return new ModelAndView("redirect:/file/showFile.do");
	}

	//下载文件
	@RequestMapping(value="downloadFile")
	public ModelAndView downloadFile(String filename,HttpServletRequest request,HttpServletResponse response) throws Exception{
		try {
			filename = new String(filename.getBytes("iso-8859-1"),"utf-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
			//设置乱码响应: Content-Disposition中指定的类型是文件的扩展名,
			//并且弹出的下载对话框中的文件类型图片是按照文件的扩展名显示的,点保存后,
			//文件以filename的值命名,保存类型以Content中设置的为准。
			response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(filename,"utf-8"));
		String realPath = request.getSession().getServletContext().getRealPath("/")+"file/"+filename;
		//输入流
		FileInputStream is = new FileInputStream(new File(realPath));
		// 输出流
		OutputStream os =response.getOutputStream();
		
		int length = 0;
		byte[] by = new byte[1024];
			while((length=is.read(by))>0){
				os.write(by,0,length);
			}
				os.close();
				is.close();
		return null;//不跳转页面
	}
	
	@RequestMapping(value="/showFile")
	public ModelAndView showlist(HttpServletRequest request){
		String path = request.getSession().getServletContext().getRealPath("/");
		File file = new File(path+"file/");
		File[] files = file.listFiles();
		ArrayList<String> listfile = new ArrayList<String>(); 
  		for (File f : files) {
			listfile.add(f.getName());//  存入文件名
		}
  		request.setAttribute("listfile", listfile);
  		return new ModelAndView("listfile");
	}
	
	@RequestMapping(value="ajaxTest")
	public void ajax(HttpServletRequest request ,HttpServletResponse response) throws IOException{
		String name = request.getParameter("name");
		response.setCharacterEncoding("utf-8");
		if (name!=null&&!("").equals(name)) {
			response.getWriter().print("姓名:"+name+"可用");
		}else {
			response.getWriter().print("姓名:"+name+"不可用");
		}
	}
	
	
}
UserController 
package com.dkt.controller;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.dkt.entity.Userinf;



@Controller
@RequestMapping(value="user")
public class UserController {
	
	@RequestMapping(value="quertuser")
	public String queryuser(){
		System.out.println("显示数据");
		return "Userinf";
	}

	@RequestMapping(value="param")//  手动得到传的参数
	public String param(HttpServletRequest request) throws UnsupportedEncodingException{
		String name = request.getParameter("name");
		name = new String(name.getBytes("iso-8859-1"), "utf-8");
		int age = Integer.parseInt(request.getParameter("age"));
		System.out.println(name+"----->"+age);
		return "redirect:../user/MyJsp.jsp";// 重定向,需想外跳一级
	}
	@RequestMapping(value="paramauto")//  自动传参数
	public String paramauto(String name,int age){
		System.out.println(name+"----->"+age);
		return "Userinf";
	}
	@InitBinder("userinf")  //  类名,首字母小写
	public void init(WebDataBinder binder){
		binder.setFieldDefaultPrefix("ui.");
	}
	
	@RequestMapping(value="obj")//  对象传参数
	public String paramauto(@ModelAttribute Userinf ui){
		System.out.println(ui.getName()+"----->"+ui.getAge()+"------>"+ui.getBirthday());
		return "Userinf";
	}
	@InitBinder  //  设定传入的字符串转为日期格式
	public void initBinder(WebDataBinder binder) {  
	    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");  
	    dateFormat.setLenient(false);  
	    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));  
	}
	@RequestMapping(value="mv")
	public ModelAndView saveModelandView(String name,int age){
		Userinf userinf = new Userinf(name, age, new Date());
		ModelAndView mv = new ModelAndView("user/MyJsp");//跳转页面
		mv.addObject("ui", userinf);//存入作用域,一次请求
		return mv;
	}
	@RequestMapping(value="/{name}/{age}/{path}")
	public String queryUi(@PathVariable String name,@PathVariable Integer age,@PathVariable String path){
		System.out.println(name+"-----"+age+"-----"+path);
		return "Userinf";
	}
}

二,applicationContext.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"
	xsi:schemaLocation="
	http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-3.0.xsd
	">

<context:component-scan base-package="com.dkt.controller"></context:component-scan>
<!-- controller 的前缀和后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	<property name="prefix" value="/" />
	<property name="suffix" value=".jsp"/>
</bean>
<!-- springMVC上传文件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"  p:defaultEncoding="utf-8"></bean>
</beans>  

三,web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- springMVC配置 -->
  <servlet>
  	<servlet-name>DispatherServlet</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	     <init-param>
            <!--设置spring.xml文件位置  现在设置的是在src下 -->
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
  </servlet>
  <servlet-mapping>
  	<servlet-name>DispatherServlet</servlet-name>
  	<url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <!-- 中文乱码解决 -->
  <filter>
  	<filter-name>characterEncoding</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>characterEncoding</filter-name>
  	<url-pattern>*.do</url-pattern>
  </filter-mapping>
  
  
</web-app>

 四,jsp

listfile.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'listfile.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    This is my JSP page. <br>
        显示下载的文件名:<br/>
    <c:forEach items="${listfile}" var="item">
    <a href="file/downloadFile.do?filename=${item}" >${item }</a><br/>
    </c:forEach>
    <hr/>
  </body>
</html>

  index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  <script type="text/javascript" src="js/jquery.js"></script>
  <script type="text/javascript">
  $(function(){
  	$("input:button").click(function(){
  	$.ajax({
  		url:"file/ajaxTest.do",
  		type:"post",
  		data:"name="+$("#nameid").val(),
  		dataType:"text",
  		success:function(data){
  		alert(data)}
  	})
  	})
  })
  
  </script>
  </head>
  
  <body>
    <a href="user/quertuser.do">哈哈</a>    <br/>
    <a href="user/param.do?name=小白&age=18">手动传参数</a>    <br/>
    <a href="user/paramauto.do?name=小白&age=18">自动传参数</a>    <br/>
    <br/>
    <form action="user/obj.do" method="post">
   姓名: <input type="text" name="ui.name"><br/>
    年龄:<input type="text" name="ui.age"/><br/>
    生日:<input name="ui.birthday" type="text"/>
    <input type="submit" value="提交">
    </form><br/>
    
        <a href="user/小白/18/query.do">/{}/{}/</a>    <br/>
    <a href="user/mv.do?name=小白&age=18">ModelAndView</a>    <br/>
    
    <hr/>
  上传单个文件:<br/>
  <form   action="file/uploadFile.do" enctype="multipart/form-data" method="post"> 
  	文件一:<input type="file" name="file" /><br/>
 <input type="submit" value="提交"/>
  </form>
      <hr/>
  上传多个文件:<br/>
  <form   action="file/uploadFiles.do" enctype="multipart/form-data" method="post"> 
  	文件一:<input type="file" name="files1" /><br/>
  	文件二:<input type="file" name="files2" /><br/>
  		文件三:<input type="file" name="files3" /><br/>
 <input type="submit" value="提交"/>
  </form>
  
  <hr/>
  <input type="text" name="name" id="nameid">
  <input type="button" value="ajax">
  </body>
</html>

  五,实体类

package com.dkt.entity;

import java.util.Date;

public class Userinf {
	private String name;
	private int age;
	private Date birthday;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public Userinf() {
		super();
		// TODO Auto-generated constructor stub
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public Userinf(String name, int age, Date birthday) {
		super();
		this.name = name;
		this.age = age;
		this.birthday = birthday;
	}
	
}
原文地址:https://www.cnblogs.com/nn369/p/8058590.html