传参

在地址栏?代表开始传参,用&来分隔变量

/**
  * 请求参数-简单传参
  * @param name
  * @param age
  * @return
  */
 @RequestMapping("t2")
 @ResponseBody
 public String test2(String name, int age){
  //地址栏:http://127.0.0.1:8080/t2?name=Tom&age=20
  //form表单中的name是啥就会传过来啥,所以这个name和表单的name要一致
  //省去了request.getParameter("name")这句话
  return "Request参数是:name="+name+",age="+age;
 }
 
 /**
  * 请求传参-数组
  * @param hobby
  * @return
  */
 @RequestMapping("t3")
 @ResponseBody
 public String test3(String[] hobby){
  //地址栏:http://127.0.0.1:8080/t3?hobby=eat&hobby=sleep&hobby=dadoudou
  //用于多选
  return "Request参数是:"+Arrays.toString(hobby);
 }
 
 /**
  * 请求传参-实体
  * @param user
  * @return
  */
 @RequestMapping("t4")
 @ResponseBody
 public User test4(User user){
  //地址栏:http://127.0.0.1:8080/t4?username=tom&age=19
  //若传来的信息足够一个实体的所需的所有信息(可以多出来别的实体没有的信息),则可以自动变成实体传进来
  return user; 
 }

修改端口

在resources包下新建一个File文件,取名Application.properties

server.port=8090

spring yml配置端口号 spring修改端口_java


spring yml配置端口号 spring修改端口_spring boot_02

请求转发、重定向

传入HttpServletRequest参数,请求转发是return “forward:”,重定向是return “redirect”

package demo.boot.controller;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("test")
public class testController {
	
	@RequestMapping("hello")
	@ResponseBody
	public String helloworld() {
		return "hello SpringBoot";
	}
	
	
	//测试请求转发
	@RequestMapping("t1")
	//不用在页面显示,所以不用加@ResponseBody
	public String test1(HttpServletRequest request) {
		request.setAttribute("str", "请求转发");
		return "forward:/test/result";
	}
	
	//测试重定向
	@RequestMapping("t2")
	//不用在页面显示,所以不用加@ResponseBody
	public String test2(HttpServletRequest request) {
		request.setAttribute("str", "重定向");
		return "redirect:/test/result";
	}
	
	//接收转发和重定向的结果
	@RequestMapping("result")
	@ResponseBody
	public String result(HttpServletRequest request) {
		String result=(String) request.getAttribute("str");
		return "Request域中str的值:"+result;
	}
}

spring yml配置端口号 spring修改端口_spring_03


spring yml配置端口号 spring修改端口_spring boot_04

跨服务器文件上传

1.添加依赖

不使用maven的话要导3个jar包
使用Maven的话添加依赖即可

<project xmlns="http://maven.apache.org/POM/4.0.0"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <!-- Begin##01、添加SpringBoot的parent支持##Begin -->
 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>1.5.2.RELEASE</version>
 </parent>
 
 <!-- End##01、添加SpringBoot的parent支持##End -->

	
 <groupId>cn.personal.qin.demos</groupId>
 <artifactId>hello-boot</artifactId>
 <version>1.0.0-SNAPSHOT</version>
 <packaging>war</packaging>

 <dependencies>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
  </dependency>
  <!-- 连接池 -->
  <dependency>
   <groupId>com.jolbox</groupId>
   <artifactId>bonecp-spring</artifactId>
   <version>0.8.0.RELEASE</version>
  </dependency>
  <!-- Begin##02、添加SpringBoot的Web支持##Begin -->
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <!-- End##02、添加SpringBoot的Web支持##End -->
  <!-- Begin##添加JSP支持##Begin -->
  <dependency>
   <groupId>org.apache.tomcat.embed</groupId>
   <artifactId>tomcat-embed-jasper</artifactId>
   <scope>provided</scope>
  </dependency>
  <!-- End##添加JSP支持##Begin -->

  <!-- 文件上传 -->
  <dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.3.1</version>
  </dependency>
  <!--跨服务器上传 -->
  <dependency>
   <groupId>com.sun.jersey</groupId>
   <artifactId>jersey-client</artifactId>
   <version>1.19</version>
  </dependency>

  <dependency>
   <groupId>com.sun.jersey</groupId>
   <artifactId>jersey-core</artifactId>
   <version>1.19</version>
  </dependency>
 </dependencies>
 <build>
  <finalName>${project.artifactId}</finalName>
  <plugins>
   <!-- 资源文件拷贝插件 -->
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-resources-plugin</artifactId>
    <configuration>
     <encoding>UTF-8</encoding>
    </configuration>
   </plugin>
   <!-- 设置jdk版本 -->
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
     <source>1.8</source>
     <target>1.8</target>
     <encoding>UTF-8</encoding>
    </configuration>
   </plugin>
   <!-- Begin##03、添加SpringBoot的插件支持##Begin -->
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>3.3.1</version>
      </plugin>

   
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
   <!-- End##03、添加SpringBoot的插件支持##End -->
  </plugins>
 </build>
</project>

2.写工具类

package util;

import java.io.IOException;
import java.util.Date;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;


/**
 * @author Vincent_lz
 * 跨服务器上传工具类
 */
public class JesyFileUploadUtil {
	/**
	 * 
	 * @param request 从request对象中获取上传的文件
	 * @param fileName 文件名
	 * @param serverUrl 服务器路径
	 * @return
	 * @throws IOException 
	 */
	public static String  uploadFile(HttpServletRequest request,String fileName,String serverUrl) throws IOException {
		//把request对象转换成多媒体的请求对象
		MultipartHttpServletRequest mr=(MultipartHttpServletRequest) request;
		//根据文件名获取文件对象
		MultipartFile mf=mr.getFile(fileName);
		//获取文件的上传流
		byte[] b=mf.getBytes();
		
		//重新设置文件名
		String newFileName="";
		newFileName += new Date().getTime()+"";//将当前时间获得的毫秒数拼接
		Random r=new Random();
		for(int i=0;i<3;i++) {
			newFileName += r.nextInt(10);//生成一个0-10之间的随机整数
		}
		
		//获取文件扩展名
		String orginalFileName=mf.getOriginalFilename();
		String suffix=orginalFileName.substring(orginalFileName.indexOf("."));
		
		//创建jesy服务器,进行跨服务器上传
		Client client=Client.create();
		//把文件关联到远程服务器
		WebResource resource=client.resource(serverUrl+"/upload/"+newFileName+suffix);
		//上传
		resource.put(String.class,b);
		
		//图片上传成功后
		//1.ajax回调函数做图片回显(需要图片完整路径)
		//2.将图片路径保存到数据库(图片的相对路径)
		
		String fullPath=serverUrl+"/upload/"+newFileName+suffix;
		String relativePath="/upload/"+newFileName+suffix;
		
		//生成一个JSON响应给客户端
		String resultJson="{\"fullPath\":\""+fullPath+"\", \"relativePath\":\""+relativePath+"\"}";
		return resultJson;
	}
}

3.写控制层

package demo.boot.controller;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import util.JesyFileUploadUtil;

@Controller

public class uploadController {
	private final String PIC_URL="http://localhost:8081/ssm_img";
	@RequestMapping(value="uploadPic",method=RequestMethod.POST)
	@ResponseBody
	public String uploadPic(HttpServletRequest request,String fileName) {
		//调用服务器上传文件的工具类方法上传文件
		String result="";
		try {
			result = JesyFileUploadUtil.uploadFile(request,fileName,PIC_URL);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}
}

要在创建一个名为ssm_img的工程,并且要修改一下Tomcat的端口号

4.修改Tomcat权限

此时进行上传文件会报错

spring yml配置端口号 spring修改端口_spring yml配置端口号_05


Tomcat默认不许修改内容,所以要修改一下权限

首先关闭Tomcat,找到Service工程,点击要修改的Tomcat,进入web.xml,点击source查看源码,ctrl+f调出搜索框,搜索readonly,向下找到代码,赋值init-param那一块,name改成readonly,value是false

spring yml配置端口号 spring修改端口_maven_06

5.测试

spring yml配置端口号 spring修改端口_spring_07

6.jsp代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello SpringMVC</title>
<script type="text/javascript"
	src="${pageContext.request.contextPath }/js/jquery.js"></script>
<script type="text/javascript"
	src="${pageContext.request.contextPath }/js/jquery.form.js"></script>
<script type="text/javascript">
	function submitImgSize1Upload() {
		var option = {
			type : 'POST',
			url : '${pageContext.request.contextPath }/uploadPic',
			dataType : 'text',
			data : {
				fileName : 'imgSize1File'
			},
			success : function(data) {
				console.log(data);
				//把json格式的字符串转换成json对象
				var jsonObj = $.parseJSON(data);

				//返回服务器图片路径,把图片路径设置给img标签
				$("#imgSize1ImgSrc").attr("src", jsonObj.fullPath);
				//数据库保存相对路径
				$("#imgSize1").val(jsonObj.relativePath);
			}
		};
		$("#itemForm").ajaxSubmit(option);
	}
</script>
</head>
<body>
	<h3>图片上传及回显</h3>
	<form id="itemForm" method="post">
		<img id='imgSize1ImgSrc' src='${picPath }${item.pic }' height="100"
			width="100" />
		<input type='file' name='imgSize1File' class="file" onchange='submitImgSize1Upload()' />
	</form>
</body>
</html>