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 ...
随机推荐
- tomcat 项目发布方式
1.WEB应用的组成结构 开发web应用时,不同类型的文件有严格的存放规则,否则不仅会使web应用无法访问 还会导致web服务器自动报错. mail:web应用所在目录(该目录自定义) html,js ...
- 我与网站的日常-webshell命令执行
本文比较基础,其中有一个知识点关于php执行系统命令的函数 ,我们用最简单的webshell来说说传值问题的影响, 本文作者: i春秋签约作家——屌丝绅士 0×01前言: 小表弟又来写文章了,这 ...
- UINavigationBar 的视觉效果
有很多属性可以决定导航栏的视觉效果,下面做一下总结 barStyle 属性 白底黑字 default 黑底白字 black blackOpaque 和 blackTranslucent 已被 Depr ...
- 【LeetCode】462. 最少移动次数使数组元素相等 II
给定一个非空整数数组,找到使所有数组元素相等所需的最小移动数,其中每次移动可将选定的一个元素加1或减1. 您可以假设数组的长度最多为10000. 例如: 输入: [1,2,3] 输出: 2 说明: 只 ...
- vue-Treeselect 使用备注
<head> <!-- include Vue 2.x --> <script src="https://cdn.jsdelivr.net/npm/vue@@^ ...
- PHP基础记录
1. require和require_once的区别 require_once()包涵是绝对路径 include() 和require() :语句包括并运行指定文件. include() 产生一个警告 ...
- Linux的管道命令
Linux的管道命令 管道命令(Pipe) 管道命令用"|"来表示,管道命令需要接收前一个命令的输出来进行操作,但不能处理前一个命令的错误. //选取界面:cut,grep cut ...
- IE10以下优雅降级(作为范例)
扒下来一段 优雅降级的代码. <!--[if lt IE 10]> <style> .ie-tip{margin-top: 100px;font-size: 16px;text ...
- 理解Linux内核之中断控制
乍一看下边的Linux内核代码,貌似L3389有bug,于是我就绕有兴趣地阅读了一下local_irq_save/local_irq_restore的源代码. /* linux-4.14.12/mm/ ...
- XML 实体
实体可以简单的理解为引用数据项的方法,可以是普通的文本也可以是二进制数据. 实体可以分为通用实体和参数实体.通用实体用于XML当中,用于引用文本或者二进制数据,而参数实体只能在DTD中使用.通用实体与 ...