web配置:
<?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"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
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>temp</display-name>
<!-- spring mvc -->
<servlet>
<servlet-name> temp</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name> temp</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 编码UTF8 -->
<filter>
<filter-name>setEncoding</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>setEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 使用了REST风格的URL,过滤掉常规文件名 -->
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.gif</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.png</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.flv</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.swf</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.gzjs</url-pattern>
</servlet-mapping>
<!--
浏览器不支持put,delete等method,由该filter将/blog?_method=delete转换为标准的http
delete方法
-->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<servlet-name>temp</servlet-name>
</filter-mapping>
<!-- jsp去空行 -->
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<trim-directive-whitespaces>true</trim-directive-whitespaces>
</jsp-property-group>
<!--解决html页面显示中文乱码问题 -->
<jsp-property-group>
<description>HTML Encoding</description>
<display-name>HTML Encoding Config</display-name>
<url-pattern>*.html</url-pattern>
<el-ignored>true</el-ignored>
<page-encoding>gbk</page-encoding>
<scripting-invalid>true</scripting-invalid>
</jsp-property-group>
</jsp-config>
<!-- 会话超时时间 -->
<session-config>
<session-timeout>60</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
spring Controller类配置,这里主要是使用了注解,(注意文件名为xx-servlet.xml,xx对映web.xml中spring servlet-name值,上面代码红色部分)
temp-servlet.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:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util"
xmlns:task="http://www.springframework.org/schema/task"
xmlns:aop="http://www.springframework.org/schema/aop"
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-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<!-- 基于注解的根包扫描路径 -->
<context:component-scan base-package=".........crm.*" />
<!-- Spring默认的MVC基于注解风格定义的拦截器 -->
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<list>
<!-- <bean class=".........interceptor.SessionInterceptor"/> -->
</list>
</property>
</bean>
<!-- 基于注解风格的JSON配置 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<util:list id="beanList">
<ref bean="mappingJacksonHttpMessageConverter" />
</util:list>
</property>
</bean>
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
<!-- SimpleJdbcTemplate的DataSource数据源配置 -->
<bean id="simpleJdbcTemplate" class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
<constructor-arg>
<ref bean="dataSource" />
</constructor-arg>
</bean>
<!-- 事务控制器 -->
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource">
<ref local="dataSource" />
</property>
</bean>
<!-- 实现基于注解的事务管理 -->
<tx:annotation-driven transaction-manager="txManager" />
<!-- 实例化全局DAO,注入内容 -->
<bean id="dao" class=".........dao.MysqlDBDaoImpl">
<property name="sjt" ref="simpleJdbcTemplate" />
<property name="isDebug" value="true"></property>
</bean>
<!-- Default ViewResolver -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 缺省异常页面配置-->
<bean id="exceptionResolver"
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!-- to /commons/error.jsp -->
<property name="defaultErrorView" value="/error" />
<property name="exceptionMappings">
<props>
<prop key="java.sql.SQLException">errorDB</prop>
<prop key="java.lang.Exception">exception</prop>
</props>
</property>
</bean>
<aop:aspectj-autoproxy/>
</beans>
(注意,这里的配置只是部分,不是全部,jdbc部分我去掉了,仅供参考)
这里的配置使用了spring的注解,也就是以后编写controller类时不用再更改这个配置文件
现在来看看controller类的写法;
package ........controller;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.gangyi.crm.servce.ITestServce;
import com.gangyi.crm.vo.TestBean;
/**
* 该控制器有保存数据和查询分页数据
*
* @author yangkun
*
*/
@Controller //这个配置很关键,这个注解说明这是一个controller类。在前面的temp-servlet.xml中配置了包扫描,
@RequestMapping("/springMVCtest.do")
public class SpringMVCtest {
@Resource
private ITestServce testServceImpl;
public SpringMVCtest(){
}
/**
*将用户的注册信息保存到数据库中,成功保存则返回数据,否则转向index页面
*@param request 页面请求
*@param modelMap 向页面响应的参数
*@return
* */
@RequestMapping(params = "method=regist")
public String regist(HttpServletRequest request, ModelMap modelMap) throws UnsupportedEncodingException{
//获取页面注册参数
String name = request.getParameter("name");
String age = request.getParameter("age");
String sex = request.getParameter("sex");
//vo存储参数
TestBean tb=new TestBean();
tb.setName(name);
tb.setAge(age);
tb.setSex(sex);
try{
//保存注册参数的业务代码
testServceImpl.regist(tb);
//保存成功则向页面显示注册数据
modelMap.put("name", name);
modelMap.put("age", age);
modelMap.put("sex", sex);
}catch(Exception e){
e.printStackTrace();
return "index";
}
return "login";
}
/**
* 分页数据的获取
* @param request 获取页面的pages参数
* @param modelMap 向页面传递分页数据
* @return string
* @throws UnsupportedEncodingException
* */
@RequestMapping(params = "method=showinfo")
@SuppressWarnings("unchecked")
public String showinfo(HttpServletRequest request, ModelMap modelMap) throws UnsupportedEncodingException{
//获取请求参数
String pages=(request.getParameter("pages")==null)?"0":request.getParameter("pages");
//vo存储请求参数
TestBean tb=new TestBean();
tb.setPages(Integer.valueOf(pages));
//执行获取分页数据的业务逻辑
List<TestBean> list = null;
try{
list= (List<TestBean>)testServceImpl.showinfo(tb);
//如果没有分页数据记录,则向页面传递总数据记录数为0
if(list.size()==0){
modelMap.put("count","0");
}
else{
modelMap.put("count", list.get(0).getCount());
}
modelMap.put("listinfo", list);
modelMap.put("pages", pages);
}catch (Exception e){
}
return "infolist";
}
/**
* 测试动态树的加载,使用Json传递参数
* @param request 获取页面参数
* @param response 向页面传递json数据
* @return string
* @throws IOException
*
* */
@RequestMapping(params = "method=getTreeNodeByJson")
public String getTreeNodeByJson(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setCharacterEncoding("UTF-8");
response.getWriter().write("[{text:'用户注册',id:1,leaf:true}," +
"{text:'注册成功',id:2,leaf:true}," +
"{{text:'用户注册',id:4,leaf:true}," +
"{text:'注册成功',id:5,leaf:true}," +
"{text:'用户列表',id:3,leaf:true}}]");
return null;
}
/**
* 根据树的菜单id来返回要显示在tabpanel的页面参数
* @param request
* @param response
* @return string
* @throws IOException
*
* */
@RequestMapping(params = "method=getPageItem")
public String getPageItem(HttpServletRequest request, HttpServletResponse response) throws IOException {
String pageid=request.getParameter("pageid");
String result="";
if(pageid.equals("1")){result="info";}
if(pageid.equals("2")){result="login";}
if(pageid.equals("3")){result="infolist";}
return result;
}
@RequestMapping(params = "method=get")
public String get(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.getWriter().write("<script language=\"javascript\">alert(\"请求的页面无法显示。\");"+"<"+"/script"+">");
return null;
}
@ResponseBody
@RequestMapping(params = "method=show")
@SuppressWarnings("unchecked")
public List<TestBean> show(HttpServletRequest request, ModelMap modelMap) throws UnsupportedEncodingException{
//获取请求参数
String pages=(request.getParameter("pages")==null)?"0":request.getParameter("pages");
//vo存储请求参数
TestBean tb=new TestBean();
tb.setPages(Integer.valueOf(pages));
//执行获取分页数据的业务逻辑
List<TestBean> list = null;
try{
list= (List<TestBean>)testServceImpl.showinfo(tb);
//如果没有分页数据记录,则向页面传递总数据记录数为0
if(list.size()==0){
modelMap.put("count","0");
}
else{
modelMap.put("count", list.get(0).getCount());
}
modelMap.put("listinfo", list);
modelMap.put("pages", pages);
}catch (Exception e){
}
return list;
}
}
页面代码:
<%@ 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>
<meta name="keywords" content="电子商务">
<meta name="description" content="用户注册成功,显示相关的信息">
</head>
<body>
<center>
注册成功! 欢迎使用`````<br>
您的注册信息如下<br>
姓名:<%=request.getAttribute("name") %><br>
年龄:<%=request.getAttribute("age") %><br>
性别:<%=request.getAttribute("sex") %><br>
<input type="button" οnclick="window.location.href='<%=request.getContextPath()%>/springMVCtest.do?method=showinfo'" value="显示所有用户列表"/>
</center>
</body>
</html>