SpringMVC简单小例子,没有使用到数据库

[b]SpringMVC小例子,没有使用到数据库,使用到了Freemarker和AJAX[/b]


[b]Controller层:[/b]

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.MapUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
* 〈一句话功能简述〉<br>
* 〈功能详细描述〉
*
* @see [相关类/方法](可选)
* @since [产品/模块版本] (可选)
*/
@Controller(value = "blogManagerController")
@RequestMapping(value = "/blog")
public class BlogManagerController {

/**
*
* 进入博客管理主页面 <br>
* 〈功能详细描述〉
*
* @param request
* @param reponse
* @return
* @see [相关类/方法](可选)
* @since [产品/模块版本](可选)
*/
@RequestMapping(value = "main.action")
public String blogMain(HttpServletRequest request, HttpServletResponse reponse) {
List<Map<String, Object>> blogList = getBlogList();
request.setAttribute("blogList", blogList);
return "blog/main";
}

/**
*
* 删除博客 <br>
* 〈功能详细描述〉
*
* @param request
* @param reponse
* @return
* @see [相关类/方法](可选)
* @since [产品/模块版本](可选)
*/
@RequestMapping(value = "deleteBlog.action")
@ResponseBody
public String deleteBlog(HttpServletRequest request, HttpServletResponse reponse) {
Map<String, Object> params = getRequestMap(request);

return MapUtils.getString(params, "id");
}

/**
*
* 查询博客列表 <br>
* 〈功能详细描述〉
*
* @param request
* @param reponse
* @return
* @see [相关类/方法](可选)
* @since [产品/模块版本](可选)
*/
@RequestMapping(value = "queryBlogList.action")
@ResponseBody
public List<Map<String, Object>> queryBlogList(HttpServletRequest request, HttpServletResponse reponse) {
List<Map<String, Object>> blogList = queryBlogList();
return blogList;
}

private List<Map<String, Object>> getBlogList() {
List<Map<String, Object>> blogList = new ArrayList<Map<String, Object>>();
Map<String, Object> blog = null;
for (int i = 0; i < 10; i++) {
blog = new HashMap<String, Object>();
blog.put("id", i);
blog.put("title", "从FTP下载文件到本地");
blog.put("createTime", "3 小时前");
blog.put("type", "Spring");
blog.put("readNum", i);
blog.put("replyNum", i);

blogList.add(blog);
}

return blogList;
}


private List<Map<String, Object>> queryBlogList() {
List<Map<String, Object>> blogList = new ArrayList<Map<String, Object>>();
Map<String, Object> blog = null;
for (int i = 0; i < 5; i++) {
blog = new HashMap<String, Object>();
blog.put("id", i);
blog.put("title", "从FTP下载文件到本地");
blog.put("createTime", "3 小时前");
blog.put("type", "Spring");
blog.put("readNum", i);
blog.put("replyNum", i);

blogList.add(blog);
}

return blogList;
}

/**
*
* 根据request将请求参数转化为Map<br>
* 〈功能详细描述〉
*
* @param request
* @return
* @see [相关类/方法](可选)
* @since [产品/模块版本](可选)
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
private Map<String, Object> getRequestMap(HttpServletRequest request) {
// 获取请求参数
Map parameterMap = request.getParameterMap();
Set<Map.Entry<String, String[]>> entrySet = parameterMap.entrySet();

// 定义转化后的请求Map
Map<String, Object> params = new HashMap<String, Object>();
for (Entry<String, String[]> entry : entrySet) {
// 如果请求的参数的值是数组
if (entry.getValue().length > 1) {
params.put(entry.getKey(), entry.getValue());
} else {
params.put(entry.getKey(), entry.getValue()[0]);
}
}

return params;
}
}




[b]FTL:main.ftl[/b]

<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>博客管理</title>
<#assign ctxPath=request.contextPath>
<#setting number_format="#">
<script language="javascript" src="${ctxPath}/staticfile/js/jquery.js"></script>
<script>
function deleteBlog(id){
//通过AJAX的Post请求来删除一条博客
var jsonData={"id":id};
var url="${ctxPath}/blog/deleteBlog.action";
$.post(url,jsonData,function(result){
alert(result);
});
}

//通过AJAX的Post请求查询博客列表
function queryBlogList(){
var url="${ctxPath}/blog/queryBlogList.action";
$.post(url,function(result){
var blogTbody=$("#blogTbody");
//清空表格体
blogTbody.empty();

//表格标题
var titleTr="<tr style='background-color:#F5F5F5'>"+
"<th>标题</th>"+
"<th>发表时间</th>"+
"<th>分类</th>"+
"<th>浏览</th>"+
"<th>回复</th>"+
"<th>管理</th>"+
"</tr>";
blogTbody.append(titleTr);

//遍历博客列表
$(result).each(function(i,blog){
var blogTr="<tr>"+
"<td>"+blog.title+"</td>"+
"<td>"+blog.createTime+"</td>"+
"<td>"+blog.type+"</td>"+
"<td>"+blog.readNum+"</td>"+
"<td>"+blog.replyNum+"</td>"+
"<td>"+
"<a href='javascript:void(0);' title='删除' onclick='deleteBlog("+blog.id+")>删除</a>"+
"</td>"+
"</tr>";
blogTbody.append(blogTr);
});
});
}
</script>
<style>
td{
text-align:center;
}
</style>
</head>

<body>
<a href="javascript:void(0);" title="查询" onclick="queryBlogList()">查询</a>
<table width="100%">
<colgroup>
<col width="50%">
<col width="10%">
<col width="10%">
<col width="10%">
<col width="10%">
<col width="10%">
</colgroup>
<tbody id="blogTbody">
<tr>
<th>标题</th>
<th>发表时间</th>
<th>分类</th>
<th>浏览</th>
<th>回复</th>
<th>管理</th>
</tr>
<#list blogList as blog>
<tr style='text-algin:center;'>
<td>${blog.title!''}</td>
<td>${blog.createTime!''}</td>
<td>${blog.type!''}</td>
<td>${blog.readNum!''}</td>
<td>${blog.replyNum!''}</td>
<td>
<a href="javascript:void(0);" title="删除" onclick="deleteBlog('${blog.id!''}')">删除</a>
</td>
</tr>
</#list>
</tbody>
</table>
</body>
</html>



[b]相关的配置文件:[/b]
web.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
version="2.4"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<!-- spring 监听-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- spring 字符集过滤 -->
<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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncoding</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>

<filter-mapping>
<filter-name>CharacterEncoding</filter-name>
<url-pattern>*.htm</url-pattern>
</filter-mapping>


<!-- spring mvc -->
<servlet>
<servlet-name>http</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:conf/freemarker-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>http</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>http</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>

<session-config>
<session-timeout>120</session-timeout>
</session-config>

<!-- welcome file -->
<welcome-file-list>
<welcome-file>homePage.htm</welcome-file>
</welcome-file-list>

<!-- error-page -->
<error-page>
<!-- 400错误 请求无效 -->
<error-code>400</error-code>
<location>/400.htm</location>
</error-page>
<error-page>
<!-- 404页面不存在 -->
<error-code>404</error-code>
<location>/404.htm</location>
</error-page>
<error-page>
<!-- 405无效链接 -->
<error-code>405</error-code>
<location>/405.htm</location>
</error-page>
<error-page>
<!-- 500 服务器内部错误 -->
<error-code>500</error-code>
<location>/500.htm</location>
</error-page>

</web-app>


applicationContext.xml配置文件:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/tx http://www.springframework.org/schema/tx/spring-tx-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/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd"
default-lazy-init="false">

<!-- 资源文件 -->
<context:property-placeholder location="classpath:/conf/setting-web.properties" />

<!-- DB2 dataSource-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>

<!-- 定义事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>

<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="insert*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" />
<tx:method name="save*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" />
<tx:method name="update*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" />
<tx:method name="modify*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" />
<tx:method name="delete*" propagation="REQUIRED" read-only="false"
rollback-for="java.lang.Exception" />
<tx:method name="find*" propagation="SUPPORTS" />
<tx:method name="get*" propagation="SUPPORTS" />
<tx:method name="select*" propagation="SUPPORTS" />
</tx:attributes>
</tx:advice>

<aop:config>
<aop:pointcut id="bizMethods"
expression="execution(* org.apache.ecity.*.service.*.*(..)) or execution(* org.apache.ecity.*.*.service.*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="bizMethods" />
</aop:config>

<!-- service 层Bean -->
<import resource="classpath*:/conf/bean/*-bean.xml" />

<context:annotation-config />
</beans>



freemarker-servlet.xml SpringMVC配置文件:

<?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:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<!-- 引入资源文件 -->
<context:property-placeholder location="classpath:/conf/setting-web.properties" />

<!-- Spring 扫描使用注解的包路径 -->
<context:component-scan
base-package="org.apache.remote.httpclient" />

<!-- 注解依赖的适配器 AnnotationMethodHandlerAdapter -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" />
</list>
</property>
</bean>

<!-- 注解依赖的适配器 DefaultAnnotationHandlerMapping -->
<bean
class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
</bean>

<!-- Spring @AutoWired 依赖自动注入,不需要setter方法 -->
<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />

<!-- FreeMarker模板配置 -->
<bean id="freemarkerConfig"
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<!-- FreeMarker模板路径前缀,Controller方法返回FTL文件路径是可以省略前缀,比如/WEB-INF/ftl/sys/province/main.ftl,只需要返回 sys/province/main-->
<property name="templateLoaderPath" value="/WEB-INF/ftl/" />
<property name="defaultEncoding" value="UTF-8" />
</bean>

<!-- FreeMarker视图解析器 -->
<bean
class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="cache" value="true" />
<property name="prefix" value="" />
<property name="suffix" value=".ftl" />
<property name="exposeSpringMacroHelpers" value="true" />
<property name="exposeRequestAttributes" value="true" />
<property name="exposeSessionAttributes" value="true" />
<property name="requestContextAttribute" value="request" />
<property name="contentType" value="text/html; charset=utf-8" />
</bean>

<!-- Spring JSON 格式转换依赖的Jar -->
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />

</beans>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值