返回值分类
@RequestMapping("/testString")
public String testString(Model model){
System.out.println("Hello SpringMVC");
return "success";
2.具体应用场景
@Controller
@RequestMapping("/User")
public class UserController {
@RequestMapping("/testString")
public String testString(Model model){
System.out.println("Hello SpringMVC");
User user = new User();
user.setUsername("宁宁");
user.setPassword("123");
user.setAge(24);
model.addAttribute("user",user);
return "success";
}
}
success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${user.username}
${user.password}
${user.age}
</body>
</html>
@RequestMapping("/testVoid")
public void testVoid(){
System.out.println("testVoid方法执行了");
}
所报异常:
HTTP Status 404 – 未找到
Type Status Report
消息 /springmvc02_war_exploded/WEB-INF/pages/User/testVoid.jsp
描述 源服务器未能找到目标资源的表示或者是不愿公开一个已经存在的资源表示。
2.可以使用请求转发或者重定向跳转到指定的页面
@RequestMapping("/testVoid")
public void testVoid(HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println("testVoid方法执行了");
//编写请求转发
// request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);
// 重定向
// response.sendRedirect(request.getContextPath()+"/response.jsp");
// 直接进行响应
// 设置中文乱码
response.setCharacterEncoding("UTF-8");
response.setContentType("test/html;charset=UTF-8");
response.getWriter().print("你好");
return;
}
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
ModelAndView mv = new ModelAndView();
User user = new User();
user.setAge(20);
user.setUsername("宁宁");
user.setPassword("345");
// 把user对象存储到mv对象中,也会把user对象存入到Request对象
mv.addObject("user",user);
// 跳转到哪个页面
mv.setViewName("success");
return mv;
}
success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${user.username}
${user.password}
${user.age}
<br><br>
${requestScope.user.username}
</body>
</html>
@RequestMapping("/testForwardOrRedirect")
public String testForwardOrRedirect(){
// 请求转发
// forward:转发的JSP路径,不走视图解析器,所以需要编写完整的路径
// return "forward:/WEB-INF/pages/success.jsp";
// 重定向
return "redirect:/response.jsp";
}
DispatchServlet会拦截到所有的资源,导致一个问题就是静态资源(img,css,js)也会被拦截,从而不能被使用,解决问题就是需要配置静态资源不进行拦截,再springMVC.xml配置文件添加如下的配置
<!--前段控制器,那些静态资源不拦截-->
<mvc:resources mapping="/css/" location="/css/**"></mvc:resources>
<mvc:resources mapping="/js/" location="/js/**"></mvc:resources>
<mvc:resources mapping="/images/" location="/images/**"></mvc:resources>
<!--json字符串和JavaBean对象互相转换的过程,需要使用jsonson的jar包-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
@RequestMapping("/testAjax")
public void testAjax(@RequestBody String body){
//返回参数体
System.out.println(body);
}
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<script>
$(function () {
$("#but").click(function () {
alert("hello button");
// $.ajax({
// url:"User/testAjax",
// contentType:"application/json;charset=UTF-8",
// data:'{"username":"hehe","password":"123","age":30}',
// dataType:"json",
// type:"post",
// success:function(data){
//
// }
// })
$.post("User/testAjax",{"username":"heihei","password":"1234"},
function (data,status) {
}
)
})
})
</script>
@RequestMapping(value = "/testAjax2" ,method = {RequestMethod.POST})
public void testAjax2(@RequestBody User user ){
System.out.println("testAjax");
System.out.println(user);
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<script>
$(function () {
$("#but").click(function () {
alert("hello button");
$.ajax({
url:"User/testAjax",
//Http请求头类型要添加,不然会出错
contentType:"application/json;charset=UTF-8",
data:'{"username":"hehe","password":"123","age":30}',
dataType:"json",
type:"post",
success:function(data){
//未有返回data,不会弹窗口
alert(data);
alert(data.username);
}
})
// $.post("User/testAjax2",{"username":"heihei","password":"1234","age":20},
// function (data) {
// alert(data);
// alert(data.username);
// alert(data.password);
// alert(data.age);
// }
// )
})
})
</script
@RequestMapping(value = "/testAjax" ,method = {RequestMethod.POST})
public @ResponseBody User testAjax(@RequestBody User user ){
System.out.println("testAjax");
System.out.println(user);
user.setUsername("enen");
user.setAge(30);
user.setPassword("678");
return user;
//将返回的user转换成json
}
@RequestMapping(value = "/fileupload" ,method = {RequestMethod.POST})
public String fileupload(HttpServletRequest request, MultipartFile upload) throws Exception {
// 上传的位置
String path= request.getSession().getServletContext().getRealPath("/upload/");
// 判断该路径是否存在
File file = new File(path);
if(!file.exists()){
// 不存在就创建一个
file.mkdirs();
}
// 获取上传文件的名称
String filename = upload.getOriginalFilename();
// 设置文件的名称为唯一值
String uuid = UUID.randomUUID().toString().replace("-", "");
filename = uuid + "_" + filename;
// 完成上传
upload.transferTo(new File(path, filename));
return "success";
}
配置文件解析器对象 springMVC.xml
<!--配置文件解析器对象-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760"></property>
</bean>
导入对应的jar包
<!--文件上传所需要的jar-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
<h3>文件上传</h3>
<form action="User/fileupload" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload"><br>
<input type="submit" value="上传">
</form>
<!--跨服务器上传文件,导入对应跨服务器的jar包-->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.19.4</version>
</dependency><dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.19.4</version>
</dependency>
@RequestMapping(value = "/fileupload1" ,method = {RequestMethod.POST})
public String fileupload1( MultipartFile upload) throws Exception {
// 上传的位置
String path= "http://localhost:9090/springmvc02fileserver_war_exploded/upload/";
// 获取上传文件的名称
String filename = upload.getOriginalFilename();
// 设置文件的名称为唯一值
String uuid = UUID.randomUUID().toString().replace("-", "");
filename = uuid + "_" + filename;
// 创建客户端的对象
Client client = Client.create();
// 与服务器进行连接
WebResource webResource = client.resource(path+filename);
webResource.put(upload.getBytes());
return "success";
}