一,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;
} }

springMVC 简单应用的更多相关文章

  1. SpringMVC简单配置

    SpringMVC简单配置 一.eclipse安装Spring插件 打开help下的Install New Software 点击add,location中输入http://dist.springso ...

  2. SpringMVC简单入门

    SpringMVC简单入门 与大家分享一下最近对SpringMVC的学习,希望本文章能对大家有所帮助. 首先什么是SpringMVC? Spring 为展现层提供的基于MVC设计理念的优秀的Web框架 ...

  3. SpringMVC简单实例(看起来有用)

    SpringMVC简单实例(看起来有用) 参考: SpringMVC 基础教程 简单入门实例 - CSDN博客http://blog.csdn.net/swingpyzf/article/detail ...

  4. SpringMVC简单使用教程

    一.SpringMVC简单入门,创建一个HelloWorld程序 1.首先,导入SpringMVC需要的jar包. 2.添加Web.xml配置文件中关于SpringMVC的配置 <!--conf ...

  5. eclipse建立springMVC 简单项目

    http://jinnianshilongnian.iteye.com/blog/1594806 如何通过eclipse建立springMVC的简单项目,现在简单介绍一下. 工具/原料   eclip ...

  6. 基于注解的SpringMVC简单介绍

    SpringMVC是一个基于DispatcherServlet的MVC框架,每一个请求最先访问的都是DispatcherServlet,DispatcherServlet负责转发每一个Request请 ...

  7. Intellij IDEA +MAVEN+Jetty实现SpringMVC简单查询功能

    利用 Intellij IDEA +MAVEN+Jetty实现SpringMVC读取数据库数据并显示在页面上的简单功能 1 新建maven项目,配置pom.xml <project xmlns= ...

  8. SpringMvc简单实例

    Spring MVC应用一般包括4个步骤: (1)配置web.xml,指定业务层对应的spring配置文件,定义DispatcherServlet; (2)编写处理请求的控制器 (3)编写视图对象,例 ...

  9. springMVC 简单事例

    本帖最后由 悲观主义者一枚 于 2015-1-31 17:55 编辑 使用SpringMvc开发Android WebService入门教程1.首先大家先创建一个JavaWeb项目2.然后加入Spri ...

  10. SpringMVC学习总结(四)——基于注解的SpringMVC简单介绍

    SpringMVC是一个基于DispatcherServlet的MVC框架,每一个请求最先访问的都是 DispatcherServlet,DispatcherServlet负责转发每一个Request ...

随机推荐

  1. 一个钓鱼WiFi的破解

    在开始前我们先安装下工具 git clone [url]https://github.com/P0cL4bs/WiFi-Pumpkin.git[/url] [/size] [size=4][size= ...

  2. centos6安装最新syslog-ng推送hdfs

    可参考以下网址: installhttps://www.syslog-ng.com/community/b/blog/posts/latest-syslog-ng-available-rhel-6-c ...

  3. [JavaScript] 将字符串数组转化为整型数组

    var dataStr="1,2,3,4,5";//原始字符串 var dataStrArr=dataStr.split(",");//分割成字符串数组 var ...

  4. Linux之开源软件移植

    移植环境 Utuntu 15.04 1.mplayer移植 版本:mplayer-export-snapshot.tar.bz2 /mplayer-export-2015-11-26 Linux PC ...

  5. iOS 设置textfield的最大文本长度

    //在现实开发中  需要控制文本输入长度 并实时做短信验证,代码如下 [self.textField addTarget:self action:@selector(codeChange:) forC ...

  6. Python中通过函数对象创建全局变量

    先看下面这段代码,显然无法work. 因为代码试图在TestVariableScope()中引用一个没有被定义的变量a.所以必须报错,如下图-1. 不过如果你将第2行代码注释掉.代码就能跑通了,如图- ...

  7. 科学经得起实践检验-python3.6通过决策树实战精准准确预测今日大盘走势(含代码)

    科学经得起实践检验-python3.6通过决策树实战精准准确预测今日大盘走势(含代码) 春有百花秋有月,夏有凉风冬有雪: 若无闲事挂心头,便是人间好时节. --宋.无门慧开 不废话了,以下训练模型数据 ...

  8. (转)Python 字符串

    原文:http://www.runoob.com/python/python-strings.html

  9. Java之IO(四)DataInputStream和DataOutputStream

    转载请注明源出处:http://www.cnblogs.com/lighten/p/6986155.html 1.前言 DataInputStream和DataOutputStream分别继承了Fil ...

  10. hive 0.12.0版本 问题及注意事项

    下载地址: http://archive.cloudera.com/cdh5/cdh/5/hive-0.12.0-cdh5.1.5.tar.gz 用远程mysql作为元数据存储 创建数据库,设置字符集 ...