springMVC 注解方式实现全程+文件上传

这几天有点忙,总结都没有写。

今天搭建框架基本有了点成效。现在还剩下两个问题:第一、springmvc 上传文件;第二、mongodb上传文件。这两个部分是本次系统的核心部分,而这两个部分却还是零工作状态,心里还是有点小着急。不知道这个项目能不能按期完成,因为时间只剩下十天了(包括周末)。

还是总结一下springmvc的注解框架的实现吧:

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>dispatcher</servlet-name>  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  </servlet>
  <!-- 配置spring 配置文件    -->
  <context-param>
  	<param-name>contextConfigLocation</param-name>
		<param-value>
			classpath:config/applicationContext-base.xml,			
			classpath:config/applicationContext*.xml
		</param-value>
  </context-param>
   
  <!-- 配置控制器映射 -->
  <servlet-mapping>
  	<servlet-name>dispatcher</servlet-name>
  	<url-pattern>*.do</url-pattern>
  </servlet-mapping>
  
  <listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
</web-app>

dispatcher-servlet.xml(注意:这个xml文件是springmvc的核心配置文件,实际上是一个applicationContext.xml文件,默认为WEB-INF路径下,若有另外的配置,需要在web.xml文件中配置:另外,该xml文件命名规范为web.xml文件中<servlet-name>dispatcher</servlet-name>配置的名字加上”-servlet.xml”,本例中为dispatcher-servlet.xml)

<servlet>
  	<servlet-name>dispatcher</servlet-name>  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>  
            <param-name>contextConfigLocation</param-name>             
            <!--    
              指定XML文件位置   
              <param-value>/WEB-INF/classes/springmvc.xml              
              <param-value>classpath*:springmvc.xml   
             -->  
             <!-- 在classpath路径下去寻找springmvc.xml文件 -->             
             <param-value>classpath:springmvc.xml   
            </param-value>  
        </init-param>  
  </servlet>

dispatcher-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:p="http://www.springframework.org/schema/p"     
       xmlns:context="http://www.springframework.org/schema/context" 
       xmlns:mvc="http://www.springframework.org/schema/mvc"    
  	   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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   
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"
        default-autowire="byName">   

    <!-- SpringMVC相关Bean配置 -->
	
	
	<bean id="localeResolver" class="org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver">
	</bean>
	<!-- 配置视图 -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
		p:prefix="/WEB-INF/view/" p:suffix=".jsp">
		<property name="viewClass">			
			<value>org.springframework.web.servlet.view.JstlView</value>			
		</property>
	</bean>
	
	<context:annotation-config />   
       <!-- 把标记了@Controller注解的类转换为bean -->     
      <context:component-scan base-package="test.controller" /> 
	<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->     
      <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />     
        
	<bean id="multipartResolver"     
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver"     
          p:defaultEncoding="utf-8" />     
	
	
</beans>

定义一个jsp页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Insert title here</title>

</head>

<body>

    <form action="login.do" method="post">

        <input type="hidden" name="method" value="pageQuery"/>

<input type="hidden" name="pageNo" value="1"/>

        userName:<input type="text" name="userName"/><br>

        password:<input type="password" name="password"/><br>

        <input type="submit" value="submit"/>

    </form>

 

   <hr>

    <h1>test file upload</h1>

    <form action="login.do" method="post" enctype="multipart/form-data">

        <input type="hidden" name="method" value="upload"/>

        <input type="file" name="file"/>

        <input type="submit" value="upload"/>

    </form>

    

</body>

</html>

Form表单映射类:Login:

package test.entity;

public class Login {

	private String userName; //从页面获取的值
	private String password; //从页面获取的值
	
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}

}

编写Controller:

package test.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

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

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import test.entity.Login;

import com.zhjy.core.util.Page;

@Controller
@RequestMapping("/login.do")
public class CopyOfTestController {

	@RequestMapping
	public String login(HttpServletRequest request, HttpServletResponse response, Login login) {
		
		System.out.println(request.getParameter("userName"));
		System.out.println(login.getUserName());
		return "success";
	}
	
	/**
	 * 参数注入测试 @RequestParam("pageNo") int pageNo
	 * 页面请求需要带参数pageNo
	 * @param pageNo
	 * @param request
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(params = "method=pageQuery")
	public String pageQuery(@RequestParam("pageNo") int pageNo,
			HttpServletRequest request,ModelMap model) throws Exception{
		System.out.println(pageNo);
		String putModel="test put model string";
		model.put("model", putModel);
		
		return "/test/success";//页面跳转到WEB-INF/view/test/success.jsp页面
//注释:WEB-INF/view是配置文件中的前缀,.jsp 是配置文件中的后缀
//<bean id="viewResolver" //class="org.springframework.web.servlet.view.InternalResourceViewResolver"
//		p:prefix="/WEB-INF/view/" p:suffix=".jsp">

	}
	
	/**
	 * 不同请求方式POST GET
	 * @param login
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(method=RequestMethod.POST, params = "method=save")
	public String login(Login login, HttpServletRequest request, 
			HttpServletResponse response, ModelMap model) {		
		System.out.println(request.getParameter("userName"));
		System.out.println(login.getUserName());
		model.addAttribute("user", "user");
		this.getOracleService().test();
		return "/test/success";
	}
	
	/**
	 * 上传文件测试
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(method=RequestMethod.POST, params = "method=upload")
	public String upload(HttpServletRequest request,ModelMap model) {
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;   
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd/HH");   
        /**构建图片保存的目录**/  
        String logoPathDir = "/files"+ dateformat.format(new Date());   
        /**得到图片保存目录的真实路径**/  
        String logoRealPathDir = request.getSession().getServletContext().getRealPath(logoPathDir);   
        /**根据真实路径创建目录**/  
        File logoSaveFile = new File(logoRealPathDir);   
        if(!logoSaveFile.exists())   
            logoSaveFile.mkdirs();         
        /**页面控件的文件流**/  
        MultipartFile multipartFile = multipartRequest.getFile("file");    
        /**获取文件的后缀**/  
        String suffix = multipartFile.getOriginalFilename().substring
        				(multipartFile.getOriginalFilename().lastIndexOf("."));   
//        /**使用UUID生成文件名称**/  
//        String logImageName = UUID.randomUUID().toString()+ suffix;//构建文件名称   
        String logImageName = multipartFile.getOriginalFilename();
        /**拼成完整的文件保存路径加文件**/  
        String fileName = logoRealPathDir + File.separator   + logImageName;              
        File file = new File(fileName);        
      
        try {   
            multipartFile.transferTo(file);   
        } catch (IllegalStateException e) {   
            e.printStackTrace();   
        } catch (IOException e) {          
            e.printStackTrace();   
        }   
        model.put("fileName", fileName);
        return "/test/success";
        
	}
	
}

在WEB-INF/view/test下建立success.jsp页面:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>login success</title>
</head>
<body>
<hr>
<h1>view/test/success.jsp</h1>
<h1>login success</h1>
success<br/>
userName:${userName }<br/>
success<br/>
login.userName :${login.userName }<br/>
success<br/>
user:${user }<br/>
<hr>
<h1>test file upload</h1>
fileName:${fileName } 
</body>
</html>


 

  • 12
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 26
    评论
要使用Spring MVC上传文件,您可以遵循以下步骤: 1. 创建一个包含上传表单的JSP页面。 2. 创建一个Spring MVC控制器,它将处理上传请求。 3. 在控制器中,使用MultipartFile对象来接收上传的文件。 4. 使用Java IO API来将文件保存到服务器文件系统中。 下面是一个简单的示例代码,可以用来实现文件上传: 在JSP页面中,您需要创建一个包含文件上传表单的HTML表单。请注意,表单的enctype属性必须设置为“multipart/form-data”,以便能够上传文件。 ```html <form method="POST" action="/upload" enctype="multipart/form-data"> <input type="file" name="file" /><br/><br/> <input type="submit" value="Upload" /> </form> ``` 在Spring MVC控制器中,您需要创建一个方法来处理文件上传请求。该方法应该使用@RequestParam注释来接收上传的文件,并使用Java IO API将文件保存到服务器文件系统中。 ```java @Controller public class FileUploadController { @RequestMapping(value="/upload", method=RequestMethod.POST) public String handleFileUpload(@RequestParam("file") MultipartFile file, Model model){ if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); // 文件存储路径 String rootPath = System.getProperty("catalina.home"); File dir = new File(rootPath + File.separator + "tmpFiles"); if (!dir.exists()) dir.mkdirs(); // 创建文件在服务器文件系统中的存储位置 File serverFile = new File(dir.getAbsolutePath() + File.separator + file.getOriginalFilename()); BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream(serverFile)); stream.write(bytes); stream.close(); // 在页面上显示上传文件的信息 model.addAttribute("message", "You successfully uploaded file=" + file.getOriginalFilename()); } catch (Exception e) { model.addAttribute("message", "Failed to upload file=" + file.getOriginalFilename() + " " + e.getMessage()); } } else { model.addAttribute("message", "Failed to upload empty file."); } return "uploadResult"; } } ``` 在上面的代码中,我们使用MultipartFile对象接收上传的文件,并使用Java IO API将文件保存到服务器文件系统中。最后,我们将上传文件的信息添加到模型中,以便在页面上显示。 请注意,上面的示例代码中的文件保存路径为Tomcat服务器的根目录下的“tmpFiles”文件夹。您可以根据需要更改文件保存路径。 希望这可以帮助您开始使用Spring MVC上传文件

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 26
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值