SpringMVC的基本操作
项目结构
com.xin.config
用到的注解
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = “com.xin.web”)
@Configuration
@ComponentScan
@Import
@Controller
@RequestMapping("/auth")
@PostMapping("/doLogin.do")
@GetMapping("/dosth1")
@ResponseBody
@RequestBody
@RequestParam(name = “user_name”,required = false,defaultValue =“佚名” )
@PathVariable(“user_code”)
@SessionAttributes(names = { “SuperKey1”, “SuperKey3” }, types = { User.class })
@SessionAttribute(“SuperKey1”)
@RequestPart MultipartFile myfile
AppRootConfig.java
package com.xin.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
/*
* 作用:加载Spring容器(Root WebApplicationContext)
*/
@Configuration
@ComponentScan(
//扫描com.xin包下的所有类
value = { "com.xin" },
// 排除过滤器
excludeFilters = {
@Filter(type = FilterType.ANNOTATION,classes = EnableWebMvc.class)
}
)
@Import(value = { MyBatisConfig.class})
public class AppRootConfig {
}
CommonDataListener.java
package com.xin.config;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.springframework.stereotype.Repository;
public class CommonDataListener implements ServletContextListener{
@Override
public void contextInitialized(ServletContextEvent sce) {
System.out.println("Spring服务器启动:加载通用数据!");
}
}
DispatcherServletConfig.java
- DispatcherServletConfig(WebApplicationInitializer接口实现类)
- 作用:配置SpringMVC核心控制器DispatcherServlet(等同于web.xml)
- Tomcat(Servlet3.0规范的web容器)启动时,会查找ServletContainerInitializer接口实现类
- => SpringServletContainerInitializer类(Spring提供)
- => WebApplicationInitializer接口实现类
- => DispatcherServletConfig(当前类),完成DispatcherServlet核心控制器的配置
package com.xin.config;
import java.util.EnumSet;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
/*
* DispatcherServletConfig(WebApplicationInitializer接口实现类)
* 作用:配置SpringMVC核心控制器DispatcherServlet(等同于web.xml)
*
* Tomcat(Servlet3.0规范的web容器)启动时,会查找ServletContainerInitializer接口实现类
* => SpringServletContainerInitializer类(Spring提供)
* => WebApplicationInitializer接口实现类
* => DispatcherServletConfig(当前类),完成DispatcherServlet核心控制器的配置
*/
public class DispatcherServletConfig
extends AbstractAnnotationConfigDispatcherServletInitializer{
//定制注册对DispatcherServlet进行额外的配置
//先加载springmvc中StandardServletMultipartResolver再执行customizeRegistration
@Override
protected void customizeRegistration(Dynamic registration) {
//定义了Http服务上传文件存储位置、最大文件大小、最大请求的长度,只要上传文件就会经过这里
MultipartConfigElement multipartConfigElement =
//MultipartConfigElement(java.lang.String location, long maxFileSize, long maxRequestSize, int fileSizeThreshold)
new MultipartConfigElement("c:/test/temp",1024*1024*2,1024*1024*4,2);
registration.setMultipartConfig(multipartConfigElement);
super.customizeRegistration(registration);
}
// 服务器启动时
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
// 添加过滤器
// 1.创建过滤器
CharacterEncodingFilter filter = new CharacterEncodingFilter();
// 2.设置字符编码集
filter.setEncoding("utf-8");
// 3.添加至SerfvletContext
servletContext.addFilter("CharacterEncodingFilter", filter) // 添加过滤器
.addMappingForUrlPatterns(
EnumSet.of(DispatcherType.REQUEST),
false,
"*.do"); // 设置Mapping映射
// 添加监听器
servletContext.addListener(CommonDataListener.class);
// 注意:必须调用父类的onStartup()方法
super.onStartup(servletContext);
}
// 加载Spring容器:Root WebApplicationContext(Spring)
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppRootConfig.class };
}
// 加载Spring容器:Serlvet WebApplicationContext(Spring MVC)
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { SpringMvcConfig.class };
}
// 设置DispatcherServlet映射路径为处理所有请求
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
MyBatisConfig.java在spring中使用Mybatis的配置
package com.xin.config;
import javax.sql.DataSource;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import com.alibaba.druid.pool.DruidDataSource;
public class MyBatisConfig {
// 数据源(数据库连接池)
@Bean
public DataSource druidDataSourceBean() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/my_db?charset=utf8mb4&useSSL=false&useTimezone=true&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true");
dataSource.setUsername("root");
dataSource.setPassword("a12345678900");
dataSource.setMaxActive(50);
// ....
return dataSource;
}
// SqlSessionFactory(注入DataSource数据源)
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
// 注入DataSource
sqlSessionFactoryBean.setDataSource(dataSource);
// 注入MyBatis配置文件路径
// ClassPathResource resource = new ClassPathResource("mybatis-config.xml");
// sqlSessionFactoryBean.setConfigLocation(resource);
// 开启日志
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBean.getObject();
Configuration config = sqlSessionFactory.getConfiguration();
config.setLogImpl(StdOutImpl.class);
return sqlSessionFactoryBean;
}
// 映射器扫描
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScanner = new MapperScannerConfigurer();
// 设置扫描包
mapperScanner.setBasePackage("com.xin.mapper");
//注入SqlSessionFactoryBean在容器中的名称
mapperScanner.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
return mapperScanner;
}
}
SpringMvcConfig.java实现了WebMvcConfigurer接口,进行Springmvc相关的配置
package com.xin.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
/*
* SpringMvcConfig
* 作用:进行SpringMVC相关的配置
*/
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.xin.web")
public class SpringMvcConfig implements WebMvcConfigurer{
// 2.创建Multipart解析器Bean用于文件上传的解析
// Bean的名称必须为"multipartResolver"
@Bean
public MultipartResolver multipartResolver() {
return new StandardServletMultipartResolver();
}
// 视图解析器
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
// 创建视图解析器:通过Handler请求将url地址到page路径下
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/page/");
viewResolver.setSuffix(".jsp");
// "注册"视图解析器
registry.viewResolver(viewResolver);
}
// View Controller
@Override
public void addViewControllers(ViewControllerRegistry registry) {
// 作用等同于:<mvc:view-controller path="/home" view-name="index"/>
registry.addViewController("/home").setViewName("index");
registry.addViewController("/login").setViewName("login");
registry.addViewController("/sessionInfo").setViewName("sessionInfo");
registry.addViewController("/download/imageList").setViewName("/download/imageList");
}
// 处理静态资源:当访问/WEB-INF/page/路径以外webapp以内的页面需要设置静态路径
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 作用等同于:<mvc:resources mapping="*.html" location="/" />
registry.addResourceHandler("*.html").addResourceLocations("/");
//当访问XXX.html时到webapp下寻找
//registry.addResourceHandler("/**").addResourceLocations("/");
}
// 重写该方法,用于配置请求路径匹配方式
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
// 关闭后缀名忽略:当文件下载的时候会自动移除请求文件名的后缀名因此设置为false就不会移除
configurer.setUseSuffixPatternMatch(false);
WebMvcConfigurer.super.configurePathMatch(configurer);
}
//注册拦截器:当访问到拦截请指定的路径我们就可以拦截下来做一些处理
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new TestInterceptor());
// .addPathPatterns("/demo/*","")//匹配路径
// .excludePathPatterns("","");//排除路径
}
}
TestInterceptor.java 创建一个拦截器需要实现HandlerInterceptor 接口再在springmvc配置中注册拦截器
package com.xin.config;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
//拦截器拦截每个Handler方法的执行
public class TestInterceptor implements HandlerInterceptor {
//Handler方法执行前
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
System.out.println("********************begin*******************");
return true;
}
//Handler方法执行后,视图执行前
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
System.out.println("********************post*******************");
}
Handler方法执行后,视图执行后
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("********************end*******************");
}
}
com.xin.entity
Book.java实体类
package com.xin.entity;
public class Book {
private String bookname;
private String zuozhe;
private double price;
public Book() {
super();
}
@Override
public String toString() {
return "Book [bookname=" + bookname + ", zuozhe=" + zuozhe + ", price=" + price + "]";
}
public Book(String bookname, String zuozhe, double price) {
super();
this.bookname = bookname;
this.zuozhe = zuozhe;
this.price = price;
}
public String getBookname() {
return bookname;
}
public void setBookname(String bookname) {
this.bookname = bookname;
}
public String getZuozhe() {
return zuozhe;
}
public void setZuozhe(String zuozhe) {
this.zuozhe = zuozhe;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
User .java实体类用于自动参数
package com.xin.entity;
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
public class User {
private int userId;
private String loginUserName;
private String loginUserPass;
private String[] loginOptions;
private int[] loginNumbers;
private int code;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date fromDate;
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date toDate;
public String getLoginUserName() {
return loginUserName;
}
public void setLoginUserName(String loginUserName) {
this.loginUserName = loginUserName;
}
public String getLoginUserPass() {
return loginUserPass;
}
public void setLoginUserPass(String loginUserPass) {
this.loginUserPass = loginUserPass;
}
public String[] getLoginOptions() {
return loginOptions;
}
public void setLoginOptions(String[] loginOptions) {
this.loginOptions = loginOptions;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int[] getLoginNumbers() {
return loginNumbers;
}
public void setLoginNumbers(int[] loginNumbers) {
this.loginNumbers = loginNumbers;
}
public Date getFromDate() {
return fromDate;
}
public void setFromDate(Date fromDate) {
this.fromDate = fromDate;
}
public Date getToDate() {
return toDate;
}
public void setToDate(Date toDate) {
this.toDate = toDate;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
com.xin.web.controller
AuthController .java
package com.xin.web.controller;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.xin.entity.User;
@Controller
@RequestMapping("/auth")
public class AuthController {
//当表单提交数据与参数对象属性名相同就会自动封装
@PostMapping("/doLogin.do")
public String executeLogin(User user) {
System.out.println("账号:" + user.getLoginUserName());
System.out.println("密码:" + user.getLoginUserPass());
System.out.println("选项:" + Arrays.toString(user.getLoginNumbers()));
System.out.println("日期1:" + user.getFromDate());
System.out.println("日期2:" + user.getToDate());
System.out.println("编码:" + user.getCode());
return "info";
}
//表单访问参数keyword时
@RequestMapping("/list.do")
public ModelAndView earthquakeList(@RequestParam("keyword") String value) {
System.out.println("keyword = " + value);
ModelAndView modelView = new ModelAndView();
modelView.addObject("list","");
modelView.setViewName("index");
// 请求转发
return modelView;
}
}
CookieController.java
package com.xin.web.controller;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/cookie")
public class CookieController {
// 创建Cookie
@RequestMapping("/create")
public String createCookie(HttpServletResponse response) {
Cookie cookie1 = new Cookie("name","tommy");
cookie1.setMaxAge(100000);
cookie1.setPath("/"); //设置项目根目录访问:这样每个应用程序都可以获得cookie的值,否则只能当前路径访问才可以
Cookie cookie2 = new Cookie("pass","9527");
cookie2.setMaxAge(100000);
cookie2.setPath("/"); //设置项目根目录访问
response.addCookie(cookie1);
response.addCookie(cookie2);
return "login";//请求转发
}
// 获取Cookie
@RequestMapping("/getAll")
public String getCookie(HttpServletRequest request) {
System.out.println("SESSION: " + request.getSession().getId());
Cookie[] cookies = request.getCookies();
if(cookies != null) {
for(Cookie ck : cookies) {
System.out.println(ck.getName()+":"+ck.getValue());
}
}
return "login";
}
// 获取指定名称的Cookie:会将浏览器的cookie值传给当前Handle的cookieValue参数
@RequestMapping("/get")
public String getCookie(@CookieValue("JSESSIONID" ) String jsessionId,
@CookieValue("name") String name) {
System.out.println("name = " + name);
System.out.println("jessionid = " + jsessionId);
return "login";
}
}
DemoController.java
package com.xin.web.controller;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/demo")
public class DemoController {
// 返回值:ModelAndView(数据模型+视图)
@GetMapping("/dosth1")
public ModelAndView dosth1() {
// ModelAndView使用方式1:分别添加数据和视图
ModelAndView modelView1 = new ModelAndView();
modelView1.addObject("track_no", UUID.randomUUID()); // 添加模型数据
modelView1.addObject("key1", UUID.randomUUID()); // 添加模型数据
modelView1.addObject("key2", UUID.randomUUID()); // 添加模型数据
modelView1.addObject("key3", UUID.randomUUID()); // 添加模型数据
modelView1.setViewName("info"); // 添加视图名称
// ModelAndView使用方式2:数据采用Map封装
Map<String, String> dataMap = new HashMap<>();
dataMap.put("track_no", UUID.randomUUID().toString()); // 添加模型数据
dataMap.put("key1", UUID.randomUUID().toString()); // 添加模型数据
dataMap.put("key2", UUID.randomUUID().toString()); // 添加模型数据
dataMap.put("key3", UUID.randomUUID().toString()); // 添加模型数据
// 创建ModelAndView,传入视图名称和Map数据模型
ModelAndView modelView2 = new ModelAndView("info", dataMap);
return modelView2;//请求转发
}
// 返回值:视图名称
// 参数:Model数据模型
@GetMapping("/dosth2")
public String dosth2(Model dataModel) {
// BindingAwareModelMap
System.out.println(dataModel.getClass());
// 添加1个KV键值对
dataModel.addAttribute("track_no", UUID.randomUUID());
// 添加1个Map集合
Map<String, String> dataMap = new HashMap<>();
dataMap.put("key1", UUID.randomUUID().toString()); // 添加模型数据
dataMap.put("key2", UUID.randomUUID().toString()); // 添加模型数据
dataMap.put("key3", UUID.randomUUID().toString()); // 添加模型数据
dataModel.addAllAttributes(dataMap);
return "info";
}
// 返回值:视图名称
// 参数:Map
@GetMapping("/dosth3")
public String dosth3(Map dataMap) {
// BindingAwareModelMap
System.out.println(dataMap.getClass());
// 添加N个KV键值对
dataMap.put("track_no", UUID.randomUUID());
dataMap.put("key1", UUID.randomUUID().toString()); // 添加模型数据
dataMap.put("key2", UUID.randomUUID().toString()); // 添加模型数据
dataMap.put("key3", UUID.randomUUID().toString()); // 添加模型数据
return "info";
}
// 返回值:数据模型
// 默认返回视图名称: "请求路径" = "/demo/context"(视图名称)
// 返回数据的key = 方法返回值类型
@GetMapping("/context")
public List<String> dosth4(HttpServletRequest request){
// 获取Root WebApplicationContext(Spring 父容器)
ServletContext application = request.getServletContext();
ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(application);
// 获取Spring父容器中的所有bean的名称
String[] names = context.getBeanDefinitionNames();
// 存入集合
ArrayList<String> resultList = new ArrayList<>();
resultList.addAll(Arrays.asList(names));
return resultList;//跳转到请求路径/demo/context.jsp页面通过stringList的EL表达式拿值,默认是stringList
}
}
DownloadController .java
package com.xin.web.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;
@Controller
@RequestMapping("/download")
public class DownloadController {
@RequestMapping("/list.do")//重定向方式跳转
public View executeImageFileList(RedirectAttributes model) {//保存到flash中,到重定向的地方把值给request
File dir=new File("e:/doubanJpg");
String[] list = dir.list();
model.addFlashAttribute("list", list);
return new RedirectView("imageList");//重定向方式
}
@SuppressWarnings("resource")
@RequestMapping("down.do/{fname}")
//文件下载在springmvc中创建解析器然后在DisparchServlet中注册解析器
public ResponseEntity<byte[]> executeDownload(@PathVariable("fname")String filename) throws IOException{
//通过文件名的形式访问就可以直接下载文件
String path="c:/test/temp/upload/"+filename;
File file = new File(path);
byte[] buff=null;
try {
FileInputStream fileInputStream = new FileInputStream(file);
buff=new byte[fileInputStream.available()];
fileInputStream.read(buff);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//创建响应头
HttpHeaders headers=new HttpHeaders();
//参数attachment+文件,名
headers.setContentDispositionFormData("attachment", filename);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//返回响应头实体(字节数组,响应头,状态码)//完成下载
return new ResponseEntity<byte[]>(buff,headers,HttpStatus.OK);
}
}
JsonController.java
package com.xin.web.controller;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.xin.entity.Book;
/*<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>*/
@Controller
@RequestMapping("/json")
public class JsonController {
@RequestMapping("/str.do")
@ResponseBody//将这个方法返回的字符串直接显示到浏览器页面
public String executeString() {
return System.currentTimeMillis()+"";
}
@RequestMapping("/list.do")
@ResponseBody//将这个方法返回的List封装成JSON格式显示
public List<String> executeList() {
return Arrays.asList("北京","天津","广州");
}
@RequestMapping("/map.do")
@ResponseBody//将这个方法返回的map封装成Json格式显示到页面
public Map<String,String> executeMap(String name,String age) {
Map<String,String> m=new HashMap<String, String>();
m.put("name", name);
m.put("age", age);
return m;
}
@RequestMapping("/book.do")
@ResponseBody//将这个方法返回的对象封装成JSON格式显示到页面
public Book executeBook() {
return new Book("北京遇上西雅图","aaa",19.2);
}
@RequestMapping("/booklist.do")
@ResponseBody//将这个方法返回的list集合转换成JSON格式
public List<Book> executeBooklist() {
List<Book> books=new ArrayList<>();
books.add(new Book("北京遇上西雅图","aaa",19.2));
books.add(new Book("北京遇上西雅图","aaa",19.2));
books.add(new Book("北京遇上西雅图","aaa",19.2));
books.add(new Book("北京遇上西雅图","aaa",19.2));
return books;
}
//produces指定这个方法返回字符串的字符格式 处理乱码
@RequestMapping(path="/getbook.do" ,produces = "text/html;charset=utf-8")
@ResponseBody//用来定义一个响应体
//@RequestBody注解用来声明接收一个参数为Json的请求一般是post请求,这里是一个JSON格式的book类型的数据,会自动将数据封装到Book对象中
//name正常参数?name=xxx
public String executeGetbook(@RequestBody Book book,String name) {
System.out.println(book);
String result=book.getBookname()+"被传入服务器! and name="+name;
return result;
}
}
ParamController .java
package com.xin.web.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping("/param")
public class ParamController {
//当请求页面以url传参的形式访问
@RequestMapping("/dosth1")
public String dosth1(@RequestParam(name = "user_name",required = false,defaultValue ="佚名" ) String name,
String code,
int id) {
System.out.println("name= " + name);
System.out.println("code= " + code);
System.out.println("id= " + id);
return "info";
}
//不需要?user_id=XXX直接/xxx
//www.aa.com/123
@RequestMapping("/dosth2/{user_id}/{user_code}")
public String dosth2(@PathVariable("user_id") int uid,
@PathVariable("user_code") String ucode) {
System.out.println("uid=" + uid);
System.out.println("ucode=" + ucode);
return "info";
}
}
SessionController .java
package com.xin.web.controller;
import java.util.UUID;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.xin.entity.User;
@Controller
@RequestMapping("/session")
// 设置当前Controller保存的模型数据,
// 自动同步至Session,按照names(value)和type类型:key为names中的,或value为types类型的
@SessionAttributes(names = { "SuperKey1", "SuperKey3" }, types = { User.class })
public class SessionController {
@RequestMapping("/save1")
public String saveValToSession1(HttpSession session) {
session.setAttribute("key1", UUID.randomUUID());
session.setAttribute("key2", UUID.randomUUID());
session.setAttribute("key3", UUID.randomUUID());
session.setAttribute("key4", new User());
// session.getAttribute("SuperKey2");
return "redirect:../sessionInfo";//重定向
}
@RequestMapping("/save2")
public String saveValToSession2(Model model) {
// 保存数据至Model模型,默认存储至request
// 如果当前Controller设置过@SessionAttributes,
// 将按照预设name和type,自动同步至session
model.addAttribute("SuperKey1",1024);
model.addAttribute("SuperKey2",Math.PI);
model.addAttribute("SuperKey3","Just do IT");
model.addAttribute("SuperKey4",new User());
return "redirect:../sessionInfo";
}
@RequestMapping("/get")
public String getValFromSession(@SessionAttribute(name = "SuperKey6",required = false) String val1,
@SessionAttribute("SuperKey1") String val2) {
System.out.println("val1:" + val1);
System.out.println("val2:" + val2);
return "redirect:../sessionInfo";
}
@RequestMapping("/flash")
//只在一次请求转发才有效
//保存到flash中,没有保存到session中,当重定向时,重定向到新页面就会把flash中的值给request,并且从flash中删除。
//将flash保存到session中,当重定向到新页面删除session中的flash赋值给request
public String flash(RedirectAttributes attributes) {
attributes.addFlashAttribute("flashkey1", UUID.randomUUID());
attributes.addFlashAttribute("flashkey2", UUID.randomUUID());
attributes.addFlashAttribute("flashkey3", UUID.randomUUID());
// session.getAttribute("SuperKey2");
return "redirect:../sessionInfo";
}
}
SpringContainerController .java
package com.xin.web.controller;
import java.util.Arrays;
import java.util.Enumeration;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
@Controller
@RequestMapping("/spring")
public class SpringContainerController {
@GetMapping("/info.do")
public String executeInfo(HttpServletRequest request) {
// 通过Spring容器注入的HttpServletRequest对象,获取ServletContext对象
ServletContext application = request.getServletContext();
System.out.println("Application应用范围内,保存的所有attribute名称:");
Enumeration<String> attributeNames = application.getAttributeNames();
//遍历打印
while(attributeNames.hasMoreElements()) {
String attribute = attributeNames.nextElement();
System.out.println(attribute);
}
System.out.println("Spring容器(Root)中的Bean名称:");
ApplicationContext context = (ApplicationContext) application
.getAttribute("org.springframework.web.context.WebApplicationContext.ROOT");
System.out.println(Arrays.toString(context.getBeanDefinitionNames()));
// 获取当前在Application范围中保存的Root Spring容器
WebApplicationContext rootWebApplicationContext =
WebApplicationContextUtils.findWebApplicationContext(application);
return "redirect:index";
}
}
UploadController .java
package com.xin.web.controller;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.xin.entity.User;
@Controller
@RequestMapping("/upload")
public class UploadController {
//通过表单的形式上传文件multipart:form-data
//在springmvc中创建解析器的Bean对象,再在DisparchServlet中创建MultipartConfigElement对象再注册
@PostMapping("/work.do")
public void upload(String title,String desc,@RequestPart MultipartFile myfile) {
System.out.println(""+title);
System.out.println(""+desc);
System.out.println();
System.out.println("表单元素名称:"+myfile.getName());
System.out.println("上传文件的内容类型:"+myfile.getContentType());
System.out.println("文件原始名称:"+myfile.getOriginalFilename());
System.out.println("文件原始大小:"+myfile.getSize());
try {
//可以将上传的文件转储
myfile.transferTo(new File("c:/test/temp/upload/"+myfile.getOriginalFilename()));
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
webapp/WEB-INF/page/demo关于页面的一些配置
context.jsp
<%@page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" isELIgnored="false"%>
<html>
<body>
<h2>Hello World!</h2>
<-- 获取返回List集合的信息-->
${stringList}
</body>
</html>
webapp/WEB-INF/page/download
imageList.jsp
<%@page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" isELIgnored="false"%>
//通过flash的形式获取
<%String[] listname=(String[])request.getAttribute("list"); %>
<html>
<body>
<ol>ddd
<%if(listname!=null) {%>
<% for(String name:listname){%>
<li>
<a href="/springmvc03/download/down.do/<%=name%>"><%=name %></a>
</li>
<%}%>
<%}%>
</ol>
</body>
</html>
webapp/WEB-INF/page
info.jsp
<%@page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" isELIgnored="false"%>
<html>
<body>
<h2>Hello World!</h2>
<h3>${track_no}</h3>
<li>${requestScope.key1}</li>
<li>${requestScope.key2}</li>
<li>${requestScope.key3}</li>
</body>
</html>
login.jsp
<%@page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" isELIgnored="false"%>
<!DOCTYPE html>
<html>
<body>
<h2>LOGIN</h2>
<form action="/springmvc03/auth/doLogin.do" method="post">
<p>
账号:<input name="loginUserName" value="${cookie.name.value}"/>
</p>
<p>
密码:<input name="loginUserPass" value="${cookie.pass.value}"/>
</p>
<p>
<input type="checkbox" name="loginNumbers" value="1"/>A
<input type="checkbox" name="loginNumbers" value="2"/>B
<input type="checkbox" name="loginNumbers" value="3"/>C
<input type="checkbox" name="loginNumbers" value="4"/>D
<input type="checkbox" name="loginNumbers" value="5"/>E
<input type="checkbox" name="loginNumbers" value="6"/>F
</p>
<p>
<input name="fromDate"/>
至
<input name="toDate"/>
</p>
<p>
<select name="code">
<option value="-1">请选择编码</option>
<option value="1">001A</option>
<option value="2">002B</option>
<option value="3">003C</option>
<option value="4">004D</option>
</select>
</p>
<p>
<button>登录</button>
</p>
</form>
</body>
</html>
sessionInfo.jsp
<%@page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" isELIgnored="false"%>
<!DOCTYPE html>
<html>
<body>
flashkey1=${flashkey1}<br>
flashkey2=${flashkey2}<br>
flashkey3=${sessionScope}<br><br><br><br>
${requestScope}
</body>
</html>
webapp/file.html静态页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="upload/work.do" method="post" enctype="multipart/form-data">
<p>
<input name="title"/>
</p>
<p>
<input name="desc"/>
</p>
<p>
<input type="file" name="myfile"/>
</p>
<p>
<button>提交</button>
</p>
</form>
</body>
</html>
项目需要的依赖
<?xml version="1.0" encoding="UTF-8"?>
<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>
<groupId>com.apesource</groupId>
<artifactId>springmvc03</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>springmvc03 Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- Spring依赖1:spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<!-- Spring依赖2:spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<!-- Spring依赖3:spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<!-- SpringMVC依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.1.RELEASE</version>
</dependency>
<!-- MySQL驱动依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
<!-- MyBatis依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<!-- 3.5.7版本解决JEP-290漏洞 -->
<version>3.5.7</version>
</dependency>
<!-- MyBatis-Spring 依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!-- alibaba数据库连接池druid依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.6</version>
</dependency>
<!-- JACKSON依赖 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.3</version>
</dependency>
</dependencies>
<build>
<finalName>springmvc03</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>