springMVC与jsp整合的例子和项目比较多,但是与html5整合的资料较少,对jsp不太熟,准备用springMVC +html5,想用html作视图,springMVC做后端接口,AJAX与后端交互,经过资料检索和整合,实践成功,下面附一下有用的 配置。
首先是web.xml的配置:
1、静态资源不过滤
如果只配置拦截类似于*.do格式的url,则对静态资源的访问是没有问题的,但是如果配置拦截了所有的请求(如我们上面配置的“/”),就会造成js文件、css文件、图片文件等静态资源无法访问。
一般实现拦截器主要是为了权限管理,主要是拦截一些url请求,所以不对静态资源进行拦截。要过滤掉静态资源一般有两种方式,
第一种是采用<mvc:default-servlet-handler />,(一般Web应用服务器默认的Servlet名称是"default",所以这里我们激活Tomcat的defaultServlet来处理静态文件,在web.xml里配置如下代码即可:)
Tomcat, Jetty, JBoss, and GlassFish 默认 Servlet的名字 -- "default"
Resin 默认 Servlet的名字 -- "resin-file"
WebLogic 默认 Servlet的名字 -- "FileServlet"
WebSphere 默认 Servlet的名字 -- "SimpleFileServlet"
如果你所有的Web应用服务器的默认Servlet名称不是"default",则需要通过default-servlet-name属性显示指定:
第二种是采用<mvc:resources />,在springmvc的配置文件中加入以下代码:
2、自定义拦截器
SpringMVC的拦截器HandlerInterceptorAdapter对应提供了三个preHandle,postHandle,afterCompletion方法。preHandle在业务处理器处理请求之前被调用,postHandle在业务处理器处理请求执行完成后,生成视图之前执行,afterCompletion在DispatcherServlet完全处理完请求后被调用,可用于清理资源等 。所以要想实现自己的权限管理逻辑,需要继承HandlerInterceptorAdapter并重写其三个方法。
首先在springmvc.xml中加入自己定义的拦截器我的实现逻辑CommonInterceptor,
我的拦截逻辑是“在未登录前,任何访问url都跳转到login页面;登录成功后跳转至先前的url”,具体代码如下:
注:上述代码里我写了一个RequestUtil,主要实现获取当前Request、Session对象,保存和加密页面,取出等功能。
至此,拦截器已经实现了,效果如图:
我直接访问/test/hello,会被拦截
登录成功后会跳转至/test/hello对应的页面
3、配置html视图
接下来是springMVC-servlet文件:
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:context="http://www.springframework.org/schema/context"
- xmlns:p="http://www.springframework.org/schema/p"
- xmlns:mvc="http://www.springframework.org/schema/mvc"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:task="http://www.springframework.org/schema/task"
- xsi:schemaLocation="http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context.xsd
- http://www.springframework.org/schema/mvc
- http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
- http://www.springframework.org/schema/task
- http://www.springframework.org/schema/task/spring-task.xsd">
- <!--<task:executor id="executor" pool-size="5" />
- <task:scheduler id="scheduler" pool-size="10" />
- <task:annotation-driven executor="executor" scheduler="scheduler" />
- -->
- <context:component-scan base-package="com.qingshuang.circ"/>
- <!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
- <property name="prefix" value="/"/>
- <property name="suffix" value=".jsp"/>
- </bean>
- -->
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="order" value="10"></property>
- <property name="prefix" value="/"></property>
- <property name="contentType" value="text/html"></property>
- </bean>
- </beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd">
<!--<task:executor id="executor" pool-size="5" />
<task:scheduler id="scheduler" pool-size="10" />
<task:annotation-driven executor="executor" scheduler="scheduler" />
-->
<context:component-scan base-package="com.qingshuang.circ"/>
<!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="order" value="10"></property>
<property name="prefix" value="/"></property>
<property name="contentType" value="text/html"></property>
</bean>
</beans>
当然springMVC也支持多视图,比如json、pdf、jsp等等,具体配置大家可以看一下这篇文章:http://loushi135.iteye.com/blog/1676280
以下是控制器代码:
- @Controller
- @RequestMapping(value="/test")
- public class TestController {
- /**
- * 测试请求是否成功
- * @author
- * @version
- * @since V0.1
- */
- @RequestMapping(value="{testAdmin}", method=RequestMethod.GET)
- public String testRequest(){
- System.out.println("----------------请求成功----------------");
- return "admin/login.<span style="font-family:Helvetica, Tahoma, Arial, sans-serif;">html</span>";
- }
- }
@Controller
@RequestMapping(value="/test")
public class TestController {
/**
* 测试请求是否成功
* @author
* @version
* @since V0.1
*/
@RequestMapping(value="{testAdmin}", method=RequestMethod.GET)
public String testRequest(){
System.out.println("----------------请求成功----------------");
return "admin/login.<span style="font-family:Helvetica, Tahoma, Arial, sans-serif;">html</span>";
}
}
html目录:
4、通过@ResponseBody 配置后端接口
- @ResponseBody 将内容或对象作为 HTTP 响应正文返回,并调用适合HttpMessageConverter的Adapter转换对象,写入输出流。
- 通过此注解可以将后端接口的返回数据作为http响应返回到前端。
- Spring默认的json协议解析由Jackson完成。
servlet.xml配置
Spring的配置文件,简洁到了极致,对于当前这个需求只需要三行核心配置:
- <context:component-scan base-package="org.zlex.json.controller" />
- <context:annotation-config />
- <mvc:annotation-driven />
pom.xml配置或依赖包
先说依赖配置,这里以Json+Spring为参考:
pom.xml
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-webmvc</artifactId>
- <version>3.1.2.RELEASE</version>
- <type>jar</type>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>org.codehaus.jackson</groupId>
- <artifactId>jackson-mapper-asl</artifactId>
- <version>1.9.8</version>
- <type>jar</type>
- <scope>compile</scope>
- </dependency>
- <dependency>
- <groupId>log4j</groupId>
- <artifactId>log4j</artifactId>
- <version>1.2.17</version>
- <scope>compile</scope>
- </dependency>
主要需要spring-webmvc、jackson-mapper-asl两个包,其余依赖包Maven会帮你完成。至于log4j,我还是需要看日志嘛。
包依赖图:
<h2>1、生成随机字符串长度</h2>
<input id="a" placeholder="请输入长度" type="text" ></input>
<button id=abc class="btn1" >生成</button>
<p id=result></p>
js
$(".btn1").click(function(){
//alert("a");
var length= $("#a").val();
$.ajax({
type: "POST",
url: "/SpringDemo/getMixstr.do?",
async:false,
data:"length="+length,
// dataType: "text",
success: function(msg) { //数据提交成功时返回数据
// alert(msg);
//$(this).parent.append("<div id='result'>"+data+"<div>");
$("#result").html(msg);
}
});
});
后端
@Controller
public class strCtrol {
@RequestMapping(value="/getMixstr",method=RequestMethod.POST) //此处控制浏览器里访问路径 具体为:/SpringDemo/helloworld
public @ResponseBody String getMixstr(HttpServletRequest request ,HttpServletResponse response) throws IOException{
String length=request.getParameter("length");
String str=RandomUtil.genMixStr(Integer.valueOf(length));
return str;
}
@RequestMapping(value="/genTimeStr",method=RequestMethod.POST,produces="application/json") //此处控制浏览器里访问路径 具体为:/SpringDemo/helloworld
public @ResponseBody long genTimeStr(HttpServletRequest request ,HttpServletResponse response) throws IOException{
String length=request.getParameter("length");
long str=RandomUtil.genTimeStr(Integer.valueOf(length));
return str;
}
效果图