参考:https://www.cnblogs.com/sunniest/p/4555801.html
1.导入JAR包
2.配置web.xml
3.配置springmvc.xml
4.创建controller层
5.创建JSP测试页面
6.测试
7.注意
工具:eclipse
JAR包版本:spring4.1.0和2.5.6
JQuery版本:jquery-3.3.1.js
创建个web项目
在spring的官网上下载4.1.0和2.5.6版本的spring-framework
然后分别在两个文件下找到以下的jar包,将其导入到项目中
在项目的WebContent/WEB-INF下生成web.xml文件
在web.xml中配置springmvc
springmvc1
index.html
index.htm
index.jsp
default.html
default.htm
default.jsp
springmvc
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:springmvc.xml
springmvc
/
然后在src下创建个springmvc(名字与web.xml中的servlet-name相同)
创建一个controller包,在其中创建一个TestController的控制器(注意不是servlet了,而是普通的class)
springmvc最为便捷的便是可以用注释替代大量的设置
package com.zy.springmvc1.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.zy.springmvc1.pojo.User;
//把类作为springmvc的控制器
@Controller //会自动创建控制器对象
@RequestMapping("/mvc") //类似于路径或文件夹
public class TestController {
//定义一个方法,返回到根目录下index.jsp页面
@RequestMapping("/toIndex")
public String toIndex(){
//现在看返回的页面名称,实际上是一个路径
//由于配置过了前缀和后缀,所以其表示的还是index.jsp页面
return "index";
}
//访问web-inf/jsp下的文件
@RequestMapping("/toIndex2")
public String toIndex2(){
//返回的是路径
return "WEB-INF/jsp/index";
}
//接受方法入参
@RequestMapping("revParm")
public void revParm(String name,Integer age,Double weight){
System.out.println(name+" "+age+" "+weight);
}
//注入对象属性值
@RequestMapping("/getUser")
public String toIndex3(User user){
System.out.println(user);
return "index";
}
//springmvc日期类型默认是以yyyy/MM/dd的格式,但咱们自己的习惯是yyyy-MM-dd的格式
//400 badrequest 参数格式有问题
@InitBinder
public void initBinder(ServletRequestDataBinder binder) {
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
}
//向前台页面发送数据展示
@RequestMapping("/showMsg")
public ModelAndView showMsg(Model model){
User user = new User(10, "lala", 22, null);
//把对象放入到作用域,model类似于request作用域
model.addAttribute("u",user);
return new ModelAndView("showMsg");
}
//向前台发送数据展示
@RequestMapping("/showMsg2")
public String showMsg2(HttpServletRequest request){
User user = new User(10, "lala", 22, null);
request.setAttribute("u", user);
return "showMsg";
}
//向前台发送数据展示map
@RequestMapping("/showMsg3")
public String showMsg3(Map map){
//放入到作用域
User user = new User(10, "lala", 22, null);
map.put("u",user);
return "showMsg";
}
//ajax的调用
@RequestMapping("/ajax")
public void ajax(String name,PrintWriter out){
System.out.println("name="+name);
out.print("hello "+name);
}
//解决中文乱码问题
@RequestMapping("/ajax1")
public void ajax1(String name,HttpServletResponse resp) throws IOException{
resp.setCharacterEncoding("utf-8");
resp.getWriter().write(name+"hello2");
}
//跳转到ajax.jsp
@RequestMapping("/toAjax")
public String toAjax(){
return "WEB-INF/jsp/ajax";
}
//在同一个控制器下实现跳转操作,从一个方法跳转到另外一个方法
@RequestMapping("/goTo")
public String goToIndex(){
return "redirect:toIndex";
}
//在同一个控制器下实现转发的操作
@RequestMapping("/goTo2")
public String goToIndex1(){
//转发跳转,地址栏不变化
return "forward:toIndex";
}
//实现不同控制器之间的跳转
@RequestMapping("goTo3")
public String goToController2(){
return "redirect:/mvc2/test";
}
@RequestMapping("goTo4")
public String goToController22(){
return "forward:/mvc2/test";
}
}
再创建一个TestController2为了实现不同控制器间的跳转
package com.zy.springmvc1.controller;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.zy.springmvc1.pojo.User;
@Controller
@RequestMapping("/mvc2")
public class TestController2 {
@InitBinder
public void initBinder(ServletRequestDataBinder binder) {
binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
}
//修饰的方法 --- 在执行控制中的其他方法之前会执行此方法
@ModelAttribute
public void test(){
System.out.println("000000000000");
}
@RequestMapping("/te")
public String test3(@ModelAttribute("u") User user){
System.out.println(user);
return "showMsg";
}
//定义一个方法
@RequestMapping("/test")
public void test2(){
System.out.println("successful");
}
//required默认为true 参数必须存在,false参数可以不传入
@RequestMapping(value="/reqParm",method=RequestMethod.GET)
public void reqParm(@RequestParam(value="no",required=false) Integer no,@RequestParam(value="sex") String sex){
//查看结果
System.out.println("no="+no +"\t sex="+sex);
}
}
还要创建一个测试的实体类,随便创建一个User
package com.zy.springmvc1.pojo;
import java.util.Date;
public class User {
private Integer no;
private String name;
private Integer age;
private Date birthDay;
public Integer getNo() {
return no;
}
public void setNo(Integer no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getBirthDay() {
return birthDay;
}
public void setBirthDay(Date birthDay) {
this.birthDay = birthDay;
}
public User() {
super();
// TODO Auto-generated constructor stub
}
public User(Integer no, String name, Integer age, Date birthDay) {
super();
this.no = no;
this.name = name;
this.age = age;
this.birthDay = birthDay;
}
@Override
public String toString() {
return "User [no=" + no + ", name=" + name + ", age=" + age + ", birthDay=" + birthDay + "]";
}
}
然后创建一个Upload的控制器,控制文件的上传
package com.zy.springmvc1.controller;
import java.io.FileOutputStream;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
@Controller
@RequestMapping("/upload")
public class UploadFile {
//跳转到upload.jsp页面
@RequestMapping("/toup")
public String toUp(){
return "/WEB-INF/jsp/upload";
}
//文件上传操作的方法
@RequestMapping("/up")
public String upload(HttpServletRequest req) throws Exception{
//强制类型转换
MultipartHttpServletRequest msr = (MultipartHttpServletRequest)req;
//获得上传的文件
MultipartFile file = msr.getFile("img");
//拿到文件的名称
String oriName = file.getOriginalFilename();
//文件名称需要处理
//System.out.println(oriName);
//得到文件的后缀名称
String ext = oriName.substring(oriName.lastIndexOf("."));
//System.out.println(ext);
//上传操作,知道上传的路径
String path = req.getServletContext().getRealPath("/upload");
//System.out.println("服务器的上传地址"+path);
//通过输出流直接写入文件到服务器端的绝对路径下
FileOutputStream fos = new FileOutputStream(path+"/"+UUID.randomUUID().toString()+ext);
//fos.write(file.getBytes());
IOUtils.copy(file.getInputStream(), fos);
//关闭流
fos.close();
return "success";
}
}
在Webcontent下创建index.jsp,showMsg.jsp,success.jsp
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Insert title here
hello world!!!
showMsg.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Insert title here
${u.no }--${u.name }--${u.age }
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Insert title here
success
再在WEB-INF下创建一个jsp的文件夹,在其中再创建ajax.jsp,index.jsp,upload.jsp
ajax.jsp
这里你需要导入JQuery的js
在Webcontent下创建个js文件夹,将JQuery放入进去这里使用的是jquery-3.3.1.js
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Insert title here
WEB-INF/jsp/index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Insert title here
hello world!!!222
upload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Insert title here
将项目布置到tomcat中,启动tomcat
打开浏览器在地址栏分别输入你要测试的方法的RequestMapping注释
然后查看jsp页面和控制台输出(有些是没有页面的所以会404,这是正常的,查看控制台有没有输出)
1.springmvc的默认路径不是src下[classpath],默认路径在web-inf下
2.springmvc默认名称有命名规则:web.xml中的servlet的[name-servlet.xml]
3.springmvc是面向方法编程的,定义方法实现跳转
4.springmvc的文件上传必须用post提交,还要有enctype属性 enctype:multipart/form-data
具体参考:https://www.cnblogs.com/sunniest/p/4555801.html
这里对springmvc的讲解十分详细,所以本文就拿来自己实验测试用下