SpringMVC简介 SpringMVC 是一种基于 Java 的实现 MVC 设计模型的请求驱动类型的轻量级 Web 框架,属于 SpringFrameWork 的后续产品,已经融合在 Spring Web Flow 里面。SpringMVC优势:1、清晰的角色划分:前端控制器(DispatcherServlet)请求到处理器映射(HandlerMapping)处理器适配器(HandlerAdapter)视图解析器(ViewResolver)处理器或页面控制器(Controller)验证器( Validator)命令对象(Command 请求参数绑定到的对象就叫命令对象)表单对象(Form Object 提供给表单展示和提交到的对象就叫表单对象)。2、分工明确,而且扩展点相当灵活,可以很容易扩展,虽然几乎不需要。3、由于命令对象就是一个 POJO,无需继承框架特定 API,可以使用命令对象直接作为业务对象。4、和 Spring 其他框架无缝集成,是其它 Web 框架所不具备的。5、可适配,通过 HandlerAdapter 可以支持任意的类作为处理器。6、可定制性,HandlerMapping、ViewResolver 等能够非常简单的定制。7、功能强大的数据验证、格式化、绑定机制。8、利用 Spring 提供的 Mock 对象能够非常简单的进行 Web 层单元测试。9、本地化、主题的解析的支持,使我们更容易进行国际化和主题的切换。10、强大的 JSP 标签库,使 JSP 编写更容易。………………还有比如RESTful风格的支持、简单的文件上传、约定大于配置的契约式编程支持、基于注解的零配置支持等等。SpringMVC配置坐标依赖 <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <spring.version>5.0.2.RELEASE</spring.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> </dependencies>web.xml<web-app> <display-name>Archetype Created Web Application</display-name> <!-- 配置前端控制器servlet跟mapping--> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置Servlet的初始化参数,读取springmvc的配置文件,创建spring容器 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <!-- 配置servlet启动时加载对象 而不是请求时候才加载 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <!-- /表示所有请求都经过它--> <url-pattern>/</url-pattern> </servlet-mapping>springmvc.xml配置文件该xml文件名称可自定义,需要在web.xml中指定,详见上方web.xml配置<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsd"> <!-- 配置所需要的名称空间后 配置注解扫描--> <context:component-scan base-package="com.cheng"></context:component-scan> <!-- 配置视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 配置视图解析器解析的前缀目录--> <property name="prefix" value="/WEB-INF/pages/"></property> <!-- 配置解析的后缀 下列也就是只解析到jsp文件--> <property name="suffix" value=".jsp"></property> </bean> <!-- 配置spring开启注解mvc的支持 该注解包含SpringMVC中的其他处理器--> <mvc:annotation-driven></mvc:annotation-driven></beans><mvc:annotation-driven />解析用 自动加载 RequestMappingHandlerMapping(处理映射器)和RequestMappingHandlerAdapter ( 处理适配器 ),如果不使用这种写法,可以使用下列配置,下载配置其实就是细化,可让你根据适合场景使用适合的处理器,而非全部加载。 <!-- Begin --> <!-- HandlerMapping --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean> <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean> <!-- HandlerAdapter --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean> <bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter"></bean> <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean> <!-- HadnlerExceptionResolvers --> <bean class="org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver"></bean> <bean class="org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver"></bean> <bean class="org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver"></bean> <!-- End -->小流程启动Tomcat->加载web.xml->由于配置load-on-startup启动即创建前端控制器->加载springmvc.xml->开启注解扫描->扫描@Controller注解的类创建对象前端jsp页面发请求->到前端控制器->根据@RequestMapping找具体方法执行->根据方法返回结果->根据视图解析器->查找指定的页面->Tomcat渲染页面->响应给页面常用注解@RequestMapping作用:建立请求URL与方法之间对应关系。写法:可以写在类与方法上,value值为 / 表示根目录属性:path/value 指定请求路径的url例:@RequestMapping(path ="/hello")、@RequestMapping(value="/hello")其中如果只有value一个属性的话可以省略不写,即@RequestMapping("/hello")mthod 指定该方法的请求方式@RequestMapping(value="/saveAccount",method=RequestMethod.POST)可以配置多种方式,在{}中写params 指定限制请求参数的条件RequestMapping(value="/remove",params= {"accountName","money>100"})//限制传来参数中必须有accountName、money参数,money还需要>100headers 发送的请求中必须包含的请求头RequestMapping(value="/remove",header= {"Accept"})//限制header中必须有Accept在jsp中可以采用绝对与相对URL访问mapping<a href="${pageContext.request.contextPath}/account/findAccount">绝对</a><a href="account/findAccount">相对</a>${pageContext.request.contextPath}取的是虚拟目录的名称@RequestParam与前台传递参数不一致,用它进行与形参关联,例如下列前台传的参数username,但后台必须用name时public String sayHello(@RequestParam(value="username",required=false)String name) {}@RequestBody用于获取请求体的内容(注意:get方法不适用,适用于post或ajax异步请求)required:是否必须有请求体,默认值是truepublic String sayHello(@RequestBody String body) {}@PathVariable拥有绑定url中的占位符的。例如:url中有/delete/{id},{id}就是占位符<a href="user/hello/1">入门案例</a>/*** 接收请求* @return*/@RequestMapping(path="/hello/{id}")public String sayHello(@PathVariable(value="id") String id) { System.out.println(id); return "success";}Restful风格的URL请求路径一样,可以根据不同的请求方式去执行后台的不同方法restful风格的URL优点结构清晰符合标准易于理解扩展方便@RequestHeader获取指定请求头的值public String sayHello(@RequestHeader(value="Accept") String header) {}@CookieValue获取指定cookie的名称的值@RequestMapping(path="/hello")public String sayHello(@CookieValue(value="JSESSIONID") String cookieValue) { System.out.println(cookieValue); return "success";}@ModelAttribute出现在方法上:表示当前方法会在控制器方法执行前线执行。出现在参数上:获取指定的数据给参数赋值。应用场景:当提交表单数据不是完整的实体数据时,保证没有提交的字段使用数据库原来的数据。 /** *假设User对象中有name跟password字段,前端只传了name * 要知道password 第一种在该Controller中写读数据库操作 * 第二种在@ModelAttribute修饰的方法中写数据库操作 因为它优先执行 */ @RequestMapping(path = "/updateUser") public String updateUser(User user) { System.out.println(user); return "success"; } /** * 作用在方法,先执行 * 通过前端传的name查询password并返回给user */ @ModelAttribute public User showUser(String name) { System.out.println("showUser执行了...");// 模拟从数据库中查询对象,此处为演示直接设置对象属性 User user = new User(); user.setName("哈哈"); user.setPassword("123"); return user; }假设@ModelAttribute修饰的先行方法没返回值怎么办?可在方法参数中加合适类型Map,然后将数据库查询的对象put进去,在需要的Controller方法的参数上再加@ModelAttribute注解把值再赋给user @RequestMapping(path = "/updateUser") public String updateUser(@ModelAttribute(value = "abc") User user) { System.out.println(user); return "success"; } @ModelAttribute public void showUser(String name, Map<String, User> map) { System.out.println("showUser执行了...");// 模拟从数据库中查询对象 User user = new User(); user.setName("哈哈"); user.setPassword("123"); map.put("abc", user); }@SessionAttributes用于多次执行控制器方法间的参数共享。只能写在类上。@Controller@RequestMapping(path = "/user")@SessionAttributes(value = {"username", "password", "age"}, types = {String.class, Integer.class}) // 把数据存入到session域对象中public class HelloController { /** * 向session中存入值 * * @return */ @RequestMapping(path = "/save") public String save(Model model) { System.out.println("向session域中保存数据");// 会向Request域中添加数据// 加SessionAttributes注解会再次向Session域中 model.addAttribute("username", "root"); model.addAttribute("password", "123"); model.addAttribute("age", 20); return "success"; } /** * 从session中获取值 * * @return */ @RequestMapping(path = "/find") public String find(ModelMap modelMap) {// ModelMap是Model的实现类,可以取数据 String username = (String) modelMap.get("username"); String password = (String) modelMap.get("password"); Integer age = (Integer) modelMap.get("age"); System.out.println(username + " : " + password + " : " + age); return "success"; } /** * 清除值 * * @return */ @RequestMapping(path = "/delete") public String delete(SessionStatus status) {// 将session状态设置为完成则清除session status.setComplete(); return "success"; }}参数绑定1、传什么接收什么<a href="account/findAccount?accountId=10">查询账户</a>后端:public String findAccount(Integer accountId){}2、实体类User实体类中有name跟age属性,前台传uname、age,后台用实体类直接接收后台:public String findAccount(User user){}3、关联实体类(类中有类),例如Account类中含User类:public class Account implements Serializable{ private String username; private String password; private Double money; private User user; ... } 那它前端就是:<form action="param/saveAccount" method="post"> 姓名:<input type="text" name="username" /><br/> 密码:<input type="text" name="password" /><br/> 金额:<input type="text" name="money" /><br/> 用户姓名:<input type="text" name="user.uname" /><br/> 用户年龄:<input type="text" name="user.age" /><br/> <input type="submit" value="提交" /> </form>4、数组和集合类型参数,实体类中包含List于Map <form action="param/saveAccount" method="post"> 姓名:<input type="text" name="username" /><br/> 密码:<input type="text" name="password" /><br/> 金额:<input type="text" name="money" /><br/> 用户姓名:<input type="text" name="list[0].uname" /><br/> 用户年龄:<input type="text" name="list[0].age" /><br/> 用户姓名:<input type="text" name="map['one'].uname" /><br/> 用户年龄:<input type="text" name="map['one'].age" /><br/> <input type="submit" value="提交" /> </form>过滤器解决中文乱码Get情况下乱码web.xml中加入: <!-- 配置过滤器,解决中文乱码的问题 --> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <!-- 启动过滤器 可不加--> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>在springmvc.xml中可以配置静态资源不过滤<!-- location 表示路径,mapping 表示文件,**表示该目录下的文件以及子目录的文件 --><mvc:resources location="/css/" mapping="/css/**"/><mvc:resources location="/images/" mapping="/images/**"/><mvc:resources location="/scripts/" mapping="/javascript/**"/>Post情况下乱码tomacat 对 GET 和 POST 请求处理方式是不同的,GET 请求的编码问题,要改 tomcat 的 server.xml配置文件,如下:<Connector connectionTimeout="20000" port="8080"protocol="HTTP/1.1" redirectPort="8443"/>改为:<Connector connectionTimeout="20000" port="8080"protocol="HTTP/1.1" redirectPort="8443"useBodyEncodingForURI="true"/>如果遇到 ajax 请求仍然乱码,请把:useBodyEncodingForURI="true"改为 URIEncoding="UTF-8"HiddentHttpMethodFilter由于浏览器 form 表单只支持 GET 与 POST 请求,而 DELETE、PUT 等 method 并不支持,Spring3.0 添加了一个过滤器,可以将浏览器请求改为指定的请求方式,发送给我们的控制器方法,使得支持 GET、POST、PUT 与 DELETE 请求。使用方法:第一步:在 web.xml 中配置该过滤器。第二步:请求方式必须使用 post 请求。第三步:按照要求提供_method 请求参数,该参数的取值就是我们需要的请求方式。 <filter> <filter-name>hiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>hiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>此时,前端就要改成如下: <!-- 保存 --> <form action="springmvc/testRestPOST" method="post"> 用户名称:<input type="text" name="username"><br /> <!-- <input type="hidden" name="_method" value="POST"> --> <input type="submit" value="保存"> </form> <hr /> <!-- 更新 --> <form action="springmvc/testRestPUT/1" method="post"> 用户名称:<input type="text" name="username"><br /> <input type="hidden" name="_method" value="PUT"> <input type="submit" value="更新"> </form>说白了就是在表单中加入了<input type="hidden" name="_method" value="PUT">持续更新中……
坐标:https://mvnrepository.com/artifact/commons-io/commons-io说明: 1.由于是一个工具类使用都非常的简单 所以本文只是将其分类,展示它能够提供给我们什么。 2.习惯看api的可以直接看官方的api 传送门 3.可以看一看官方的指引 指引传送门 4.FileUtils只是commons-io的其中一个工具类分类说明演示: 1.写 文件/文件夹/* 写文件 * 1.这里只列出3种方式全参数形式,api提供部分参数的方法重载 * 2.最后一个布尔参数都是是否是追加模式 * 3.如果目标文件不存在,FileUtils会自动创建 * */ //static void:write(File file, CharSequence data, String encoding, boolean append) FileUtils.write(new File("D:/a/b/cxyapi.txt"), "程序换api","UTF-8",true); //static void:writeLines(File file, Collection<?> lines, boolean append) List<String> lines=new ArrayList<String>(); lines.add("欢迎访问:");lines.add("www.cxyapi.com"); FileUtils.writeLines(new File("D:/a/b/cxyapi.txt"),lines,true); //static void:writeStringToFile(File file, String data, String encoding, boolean append) FileUtils.writeStringToFile(new File("D:/a/b/cxyapi.txt"), "作者:cxy", "UTF-8",true); 2.读 文件/文件夹//读文件 //static String:readFileToString(File file, String encoding) System.out.println(FileUtils.readFileToString(new File("D:/a/b/cxyapi.txt"), "UTF-8")); //static List<String>:readLines(File file, String encoding) System.out.println(FileUtils.readLines(new File("D:/a/b/cxyapi.txt"), "UTF-8")); //返回一个list 3.删除 文件/文件夹//删除目录 //static void:deleteDirectory(File directory) FileUtils.deleteDirectory(new File("D:/not/cxyapi")); //static boolean:deleteQuietly(File file) FileUtils.deleteQuietly(new File("D:/not/cxyapi")); //文件夹不是空任然可以被删除,永远不会抛出异常移动 文件/文件夹//移动文件 或 文件夹 //static void:moveDirectory(File srcDir, File destDir) FileUtils.moveDirectory(new File("D:/cxyapi1"), new File("D:/cxyapi2")); //注意这里 第二个参数文件不存在会引发异常 //static void:moveDirectoryToDirectory(File src, File destDir, boolean createDestDir) FileUtils.moveDirectoryToDirectory(new File("D:/cxyapi2"), new File("D:/cxyapi3"), true); /* 上面两个方法的不同是: * moveDirectory:D:/cxyapi2里的内容是D:/cxyapi1的内容。 * moveDirectoryToDirectory:D:/cxyapi2文件夹移动到到D:/cxyapi3里 * * 下面的3个都比较简单没提供示例,只提供了api * 其中moveToDirectory和其他的区别是 它能自动识别操作文件还是文件夹 */ //static void:moveFileToDirectory(srcFile, destDir, createDestDir) //static void:moveFile(File srcFile, File destFile) //static void:moveToDirectory(File src, File destDir, boolean createDestDir)5.copy//结果是cxyapi和cxyapi1在同一目录 FileUtils.copyDirectory(new File("D:/cxyapi"), new File("D:/cxyapi1")); //结果是将cxyapi拷贝到cxyapi2下 FileUtils.copyDirectoryToDirectory(new File("D:/cxyapi"), new File("D:/cxyapi2")); //拷贝文件 FileUtils.copyFile(new File("d:/cxyapi.xml"), new File("d:/cxyapi.xml.bak")); //拷贝文件到目录中 FileUtils.copyFileToDirectory(new File("d:/cxyapi.xml"), new File("d:/cxyapi")); //拷贝url到文件 FileUtils.copyURLToFile(new URL("http://www.cxyapi.com/rss/cxyapi.xml"), new File("d:/cxyapi.xml")); 6.其他//判断是否包含文件或者文件夹 boolean b=FileUtils.directoryContains(new File("D:/cxyapi"), new File("D:/cxyapi/cxyapi.txt")); System.out.println(b); //获得临时目录 和 用户目录 System.out.println(FileUtils.getTempDirectoryPath()); System.out.println(FileUtils.getUserDirectoryPath()); //打开流,如果不存在创建文件及其目录结构 //第二个参数表示 文件流是否是追加方式 FileOutputStream fos=FileUtils.openOutputStream(new File("D:/cxyapi/cxyapi.txt"),true); fos.write(new String("欢迎访问:www.cxyapi.com\r\n").getBytes()); fos.close(); //文件 或 文件夹大小 System.out.println(FileUtils.sizeOf(new File("D:/cxyapi"))); System.out.println(FileUtils.sizeOfDirectory(new File("D:/cxyapi")));原文:http://snkcxy.iteye.com/blog/1845862
刚开始使用idea,发现工程每次修改JS或者是JSP页面后,并没有生效,每次修改都需要重启一次Tomcat这样的确不方便。我想Idea肯定有设置的方法,不可能有这么不方便的功能存在。需要在Tomcat的设置中为:on ‘update‘ action:当用户主动执行更新的时候更新 快捷键:Ctrl + F9on frame deactication:在编辑窗口失去焦点的时候更新你可以根据自己的需求进行设置,我这里两个都有设置。如果你的工程中没有 Update classes and resources 这个选项,只有如下选项那么请接着往下看,因为我开始也是这样的,在这种情况下你更新后只能更新classes文件中的变动,并不能更新静态文件中的变动。出现这种选项情况的原因是因为你在Deployment的选项中使用的是先将工程打成war包然后再去运行的。修改方式:先remove当前工程,再次添加,添加的时候选择Artiface然后选择工程名称后面有 exploded的选项注意: 选择后记的填写Application context 然后在Server中更改为:Update classes and resources ___:war exploded 展开部署(相当于将资源文件进行展开后进行部署)___:war 发布模式,这是先打成war包,再部署
原因IDEA根据maven archetype的本质,其实是执行mvn archetype:generate命令,该命令执行时,需要指定一个archetype-catalog.xml文件。该命令的参数-DarchetypeCatalog,可选值为:remote,internal ,local等,用来指定archetype-catalog.xml文件从哪里获取。默认为remote,即从 http://repo1.maven.org/maven2/archetype-catalog.xml路径下载archetype-catalog.xml文件。http://repo1.maven.org/maven2/archetype-catalog.xml 文件约为3-4M,下载速度很慢,导致创建过程卡住。解决方法1.新建项目时候在下面界面添加一个属性,archetypeCatalog = internalarchetypeCataloginternal如果项目已经建好了,在maven的VM Options加上-DarchetypeCatalog=internal参数,如下:也可以在启动界面打开设置,启动界面设置是全局设置参考:https://www.cnblogs.com/del88/p/6286887.html