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;
} }
springMVC 简单应用的更多相关文章
- SpringMVC简单配置
SpringMVC简单配置 一.eclipse安装Spring插件 打开help下的Install New Software 点击add,location中输入http://dist.springso ...
- SpringMVC简单入门
SpringMVC简单入门 与大家分享一下最近对SpringMVC的学习,希望本文章能对大家有所帮助. 首先什么是SpringMVC? Spring 为展现层提供的基于MVC设计理念的优秀的Web框架 ...
- SpringMVC简单实例(看起来有用)
SpringMVC简单实例(看起来有用) 参考: SpringMVC 基础教程 简单入门实例 - CSDN博客http://blog.csdn.net/swingpyzf/article/detail ...
- SpringMVC简单使用教程
一.SpringMVC简单入门,创建一个HelloWorld程序 1.首先,导入SpringMVC需要的jar包. 2.添加Web.xml配置文件中关于SpringMVC的配置 <!--conf ...
- eclipse建立springMVC 简单项目
http://jinnianshilongnian.iteye.com/blog/1594806 如何通过eclipse建立springMVC的简单项目,现在简单介绍一下. 工具/原料 eclip ...
- 基于注解的SpringMVC简单介绍
SpringMVC是一个基于DispatcherServlet的MVC框架,每一个请求最先访问的都是DispatcherServlet,DispatcherServlet负责转发每一个Request请 ...
- Intellij IDEA +MAVEN+Jetty实现SpringMVC简单查询功能
利用 Intellij IDEA +MAVEN+Jetty实现SpringMVC读取数据库数据并显示在页面上的简单功能 1 新建maven项目,配置pom.xml <project xmlns= ...
- SpringMvc简单实例
Spring MVC应用一般包括4个步骤: (1)配置web.xml,指定业务层对应的spring配置文件,定义DispatcherServlet; (2)编写处理请求的控制器 (3)编写视图对象,例 ...
- springMVC 简单事例
本帖最后由 悲观主义者一枚 于 2015-1-31 17:55 编辑 使用SpringMvc开发Android WebService入门教程1.首先大家先创建一个JavaWeb项目2.然后加入Spri ...
- SpringMVC学习总结(四)——基于注解的SpringMVC简单介绍
SpringMVC是一个基于DispatcherServlet的MVC框架,每一个请求最先访问的都是 DispatcherServlet,DispatcherServlet负责转发每一个Request ...
随机推荐
- poj2506 Tiling
http://poj.org/problem?id=2506 题目大意:用多少种方法可以用2*1或2*2瓦片来铺一个2*n的矩形? 这是一个2*17长方形的样品. 输入是一行行的序列,每一行包含一个整 ...
- cms的使用与总结
1,把cms中的basecms复制进Wamp里面的www文件夹, 2,打开Wamp,打开网址http://localhost/basecms/core/admin/admin.php(该网址默认端口为 ...
- margin 和 padding
一图胜千言!!  参考 CSS padding margin border属性详解
- JavaScript把函数作为另一函数的参数
首先说一下这个问题是怎么产生的:今天看排序算法,想要比较不同的排序算法的时间花费. 最简单的时间统计方法是在程序块开始和结束时分别计时,求一下时间差就能得出该段代码的耗时. 如: var foo = ...
- 为什么程序员老在改 Bug,就不能一次改好吗?
程序员的日常三件事:写Bug.改Bug.背锅.连程序员都自我调侃道,为什么每天都在加班?因为我的眼里常含Bug. 但是真的有这么多Bug要改吗?就不能一次改完吗? 程序员听这问题后要拍键盘了,还!真! ...
- 【xsy1131】tortue FFT
题目大意: 一次游戏要按N个按键.每个按键阿米巴有P[i]的概率按错.对于一串x个连续按对的按键,阿米巴可以得分 $f(x)=tan(\dfrac{x}{N})\times e^{arcsin(0.8 ...
- 【xsy1058】 单词 乱搞
题目大意:给你$n$个长度为$m$的字符串,字符集仅为{x,y,z}三个字符,定义两个字符串$(s_i,s_j)$的相似度为$\sum_{k=1}^{m} [s_i[k]==s_j[k]]$. 从$0 ...
- cygwin 安装.
在线安装, http://www.cygwin.com/ 64位的,下载安装. 先装的低配的,只有几个组件装了,不然全部装太大,下次需要再装... binutils gcc gdb windows ...
- golang-利用反射给结构体赋值
由于想给一个结构体的部分成员赋值,但是有不知道具体名字,故将tag的json名字作为索引,按照json名字来一一赋值 1.通过tag反射//将结构体里的成员按照json名字来赋值 func SetSt ...
- 06-python中的装饰器
java类中, 有一系列的装饰器, 尤其对文件的操作, python的装饰器比较简单, 直接上代码 #!/usr/bin/env python3 #coding:utf- ''' python的装饰器 ...