标签:jquery ret 图片 loading classname ase http请求 https ebean
目录:
model 1
model 2
Springmvc是一个web层mvc框架,类似struts2。Springmvc是spring的一部分
具体流程步骤如下:
1、首先用户发送请求——>DispatcherServlet,前端控制器收到请求后自己不进行处理,而是委托给其他的解析器进行处理,作为统一访问点,进行全局的流程控制; 2、DispatcherServlet——>HandlerMapping,HandlerMapping将会把请求映射为HandlerExecutionChain对象(包含一个Handler处理器(页面控制器)对象、
多个HandlerInterceptor拦截器)对象,通过这种策略模式,很容易添加新的映射策略; 3、DispatcherServlet——>HandlerAdapter,HandlerAdapter将会把处理器包装为适配器,从而支持多种类型的处理器,即适配器设计模式的应用,
从而很容易支持很多类型的处理器; 4、HandlerAdapter——>处理器功能处理方法的调用,HandlerAdapter将会根据适配的结果调用真正的处理器的功能处理方法,完成功能处理;
并返回一个ModelAndView对象(包含模型数据、逻辑视图名); 5、ModelAndView的逻辑视图名——> ViewResolver, ViewResolver将把逻辑视图名解析为具体的View,通过这种策略模式,很容易更换其他视图技术; 6、View——>渲染,View会根据传进来的Model模型数据进行渲染,此处的Model实际是一个Map数据结构,因此很容易支持其他视图技术; 7、返回控制权给DispatcherServlet,由DispatcherServlet返回响应给用户,到此一个流程结束。
web.xm配置
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>helloworld</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- post请求编码过滤器 --> <filter> <filter-name>characterEncoding</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> </filter> <filter-mapping> <filter-name>characterEncoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 前端控制器DispatcherServlet --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 默认加载方式 默认加载必须规范: * 文件命名:servlet-name-servlet.xml====springmvc-servlet.xml * 路径规范:必须在WEB-INF目录下面 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
另外,前端控制器添加 <load-on-startup>2</load-on-startup>使得前端控制器在服务器启动就初始化。
springmvc.xml 配置三大组件:处理器映射器、处理器适配器、视图解析器
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"> <!-- 配置处理器映射器,springmvc默认的处理器映射器 BeanNameUrlHandlerMapping:根据bean(自定义Controler)的name属性的url去寻找hanler(Controller) --> <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean> <!-- 配置处理器适配器执行Controlelr ,springmvc默认的 SimpleControllerHandlerAdapter:执行Controller --> <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean> <!-- 配置自定义Controler --> <bean id="myController" name="/hello.do" class="com.oy.controller.MyController"></bean> <!-- 配置sprigmvc视图解析器:解析逻辑试图 后台返回逻辑试图:index 视图解析器解析出真正物理视图:前缀+逻辑试图+后缀====/WEB-INF/jsps/index.jsp --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsps/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
hello.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>主页</title> </head> <body> <h2>hello页面</h2><br/> ${msg} </body> </html>
MyController
package com.oy.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; public class MyController implements Controller { @Override public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse res) throws Exception { //接受请求,接受参数,验证参数 //封装参数,调用业务方法 //返回视图 ModelAndView mv = new ModelAndView(); //设置页面回显数据 mv.addObject("msg", "欢迎学习springmvc!"); //指定跳转的视图 //返回物理视图 //mv.setViewName("/WEB-INF/jsps/hello.jsp"); //返回逻辑视图 mv.setViewName("hello"); return mv; } }
根据web.xml 欢迎页配置
<welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list>
当访问:http://localhost:8080/helloworld/时,访问项目根路径下的index.jsp
当访问 http://localhost:8080/helloworld/hello.do,通过配置的BeanNameUrlHandlerMapping,根据bean(自定义Controler)的name属性的url去寻找hanler
4、三种处理器映射器
BeanNameUrlHandlerMapping
SimpleUrlHandlerMaping:功能寻找Controller。根据浏览器url匹配简单url的key,key又Controller的id找到Controller。
ControllerClassNameHandlerMapping:功能寻找Controller。根据类名(MyController)类名.do来访问,类名首字母小写。
映射器之间能不能共存?
3个处理器映射器可以共存。
SimpleControllerHandlerAdapter:功能执行controller,调用controller里面方法,返回modelAndView。
HttpRequestHandlerAdapter
2个处理器适配器能共存?
可以共存
Springmvc通过命令设计模式接受页面参数。
自定义命令控制器
自定义javabean
封装页面参数
跳转到add页面:由于add页面在WEB-INF下面不能直接访问,需要通过Controller来访问。
在springmvc.xml配置bean
get请求乱码解决
post请求乱码解决
在web.xml配置
public class CommandController extends AbstractCommandController{ //指定参数绑定到那个javaBean public CommandController(){ this.setCommandClass(User.class); } @Override protected ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { //把命令对象强转成User对象 User user = (User) command; ModelAndView mv = new ModelAndView(); mv.addObject("user", user); mv.setViewName("index"); return mv; } @Override protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception { String str = request.getParameter("birthday"); if(str.contains("/")){ binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy/MM/dd"), true)); }else{ binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true)); } } }
jdk1.7+tomcat8.5。
搭建项目出现:org.springframework.beans.factory.BeanDefinitionStoreException: Failed to read candidate component class
20:22:19,028 DEBUG PathMatchingResourcePatternResolver:351 - Resolved location pattern [classpath*:com/oy/**/*.class] to resources [file [D:\oy_workspace\eclipse_javaee_win64_workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\helloworld\WEB-INF\classes\com\oy\controller\UserController.class]] 20:22:19,043 ERROR DispatcherServlet:466 - Context initialization failed org.springframework.beans.factory.BeanDefinitionStoreException: Failed to read candidate component class: file [D:\oy_workspace\eclipse_javaee_win64_workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\helloworld\WEB-INF\classes\com\oy\controller\UserController.class]; nested exception is java.lang.IllegalArgumentException at org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.findCandidateComponents(ClassPathScanningCandidateComponentProvider.java:281) at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.doScan(ClassPathBeanDefinitionScanner.java:242) at org.springframework.context.annotation.ComponentScanBeanDefinitionParser.parse(ComponentScanBeanDefinitionParser.java:84) at org.springframework.beans.factory.xml.NamespaceHandlerSupport.parse(NamespaceHandlerSupport.java:73)
由于之前使用的jdk1.8+tomcat9,现在改为jdk1.7+tomcat8.5。
eclipse添加一个tomcat server
将项目添加进tomca提示Project facet Java version 1.8 is not supported.
首先改变项目jdk
然后修改项目Java Compiler 和 project facet, 选中项目右键-->Properties-->Java Compiler 或 Project Facets
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>helloworld</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- post请求编码过滤器 --> <filter> <filter-name>characterEncoding</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> </filter> <filter-mapping> <filter-name>characterEncoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 前端控制器DispatcherServlet --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 默认加载方式 默认加载必须规范: * 文件命名:servlet-name-servlet.xml====springmvc-servlet.xml * 路径规范:必须在WEB-INF目录下面 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>2</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
springmvc.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"> <context:component-scan base-package="com.oy"></context:component-scan> <!-- 配置注解处理器映射器 功能:寻找执行类Controller --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean> <!-- 配置注解处理器适配器 功能:调用controller方法,执行controller --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean> <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean> <!-- 配置sprigmvc视图解析器:解析逻辑试图 后台返回逻辑试图:index 视图解析器解析出真正物理视图:前缀+逻辑试图+后缀====/WEB-INF/jsps/index.jsp --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsps/"></property> <property name="suffix" value=".jsp"></property> </bean> </beans>
log4j.properties
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c:/mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change ‘info‘ to ‘debug‘ ###
log4j.rootLogger=debug, stdout
UserController
package com.oy.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping("/user") public class UserController { @RequestMapping(value="/hello.do",method={RequestMethod.GET,RequestMethod.POST}) public String hello(){ return "hello"; } }
http://localhost:8080/helloworld/user/hello.do
Contrller方法返回结果重定向到一个url地址,如果方式:
return "redirect:/user/userlist.do";
注意:
? redirect:add.do 与 redirect:/user/add.do" 同一个类
在同一个类里面进行跳转。上面2个都可以实现跳转。但是有区别:
第一个是同一个根路径下面跳转。第二个是在项目路径下进行跳转。
? 不同的类进行跳转
不同的类进行跳转只能使用:redirect:/user/add.do进行跳转。即是从项目路径下来查询。
redirect方式相当于“response.sendRedirect()”,转发后浏览器的地址栏变为转发后的地址,因为转发即执行了一个新的request和response。
由于新发起一个request原来的参数在转发时就不能传递到下一个url,如果要传参数可以/user/userlist.do后边加参数,如下:
/user/userlist.action?groupid=2&...
controller方法执行后继续执行另一个controller方法。
return "forward:/user/userlist.action";
forward方式相当于“request.getRequestDispatcher().forward(request,response)”,转发后浏览器地址栏还是原来的地址。转发并没有执行新的request和response,而是和转发前的请求共用一个request和response。所以转发前请求的参数在转发后仍然可以读取到。
@RequestBody注解用于读取http请求的内容(字符串),通过springmvc提供的HttpMessageConverter接口将读到的内容转换为json、xml等格式的数据并绑定到controller方法的参数上。
添加处理json数据配置(测试时配置下面的json转换器仍然报415)
<!-- 注解适配器 :添加json转换器--> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean> </list> </property> </bean>
23:27:15,966 DEBUG DispatcherServlet:823 - DispatcherServlet with name ‘springmvc‘ processing POST request for [/helloworld/json1.do] 23:27:15,970 DEBUG RequestMappingHandlerMapping:209 - Looking up handler method for path /json1.do 23:27:15,973 DEBUG RequestMappingHandlerMapping:216 - Returning handler method [public com.oy.controller.User com.oy.controller.MyJsonController.requestJson(org.springframework.ui.Model,com.oy.controller.User)] 23:27:15,973 DEBUG DefaultListableBeanFactory:246 - Returning cached instance of singleton bean ‘myJsonController‘ 23:27:15,997 DEBUG AnnotationMethodHandlerExceptionResolver:132 - Resolving exception from handler [public com.oy.controller.User com.oy.controller.MyJsonController.requestJson(org.springframework.ui.Model,com.oy.controller.User)]: org.springframework.web.HttpMediaTypeNotSupportedException: Content type ‘application/json;charset=utf-8‘ not supported 23:27:15,998 DEBUG ResponseStatusExceptionResolver:132 - Resolving exception from handler [public com.oy.controller.User com.oy.controller.MyJsonController.requestJson(org.springframework.ui.Model,com.oy.controller.User)]: org.springframework.web.HttpMediaTypeNotSupportedException: Content type ‘application/json;charset=utf-8‘ not supported 23:27:15,999 DEBUG DefaultHandlerExceptionResolver:132 - Resolving exception from handler [public com.oy.controller.User com.oy.controller.MyJsonController.requestJson(org.springframework.ui.Model,com.oy.controller.User)]: org.springframework.web.HttpMediaTypeNotSupportedException: Content type ‘application/json;charset=utf-8‘ not supported 23:27:15,999 DEBUG DispatcherServlet:999 - Null ModelAndView returned to DispatcherServlet with name ‘springmvc‘: assuming HandlerAdapter completed request handling 23:27:15,999 DEBUG DispatcherServlet:946 - Successfully completed request
使用<mvc:annotation-driven/>就没有问题
<!-- annotation-driven:默认创建了多个对象:RequestMappingHandlerMapping,RequestMappingHandlerAdapter 也就提供对json格式支持 --> <mvc:annotation-driven/>
测试页面(发送ajax请求)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.8.3.js"></script> <script type="text/javascript"> //请求json,返回json function request_json(){ //JSON.stringify() 方法是将一个JavaScript值(对象或者数组)转换为一个 JSON字符串 var user = JSON.stringify({name:"张三",age:20}); $.ajax({ type:‘POST‘, url: ‘${pageContext.request.contextPath}/json1.do‘, contentType:‘application/json;charset=utf-8‘, data:user, success : function(data){ alert(data.name+":"+data.age); } }) } </script> </head> <body> <input type="button" onclick="request_json()" value="请求json,返回json"> </body> </html>
controller
@Controller public class MyJsonController { @RequestMapping("/json1.do") @ResponseBody public User requestJson(Model model, @RequestBody User user){ System.out.println("用户信息:" + user); return user; } }
标签:jquery ret 图片 loading classname ase http请求 https ebean
原文地址:https://www.cnblogs.com/xy-ouyang/p/14224456.html