博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
springmvc,mybatis,freemarker,maven-基于注解的整合
阅读量:4567 次
发布时间:2019-06-08

本文共 12784 字,大约阅读时间需要 42 分钟。

概述:没有写技术博客的经验,看过的博客也不喜欢长篇大论,比较喜欢直观看代码,学习的习惯是行动中理解,如果需要深入了解我会看一些详解的文档,搜索XXX整合关键词的人,大部分应该是应急需求,或新手学习,更想看到的是可以运行注释详细的空框架模板,精简可运行的代码,至少我是这样的,故此书写风格就以此为主。

 

结构:

 

 

一:创建一个maven 项目,配置pom.xml

4.0.0
spring_v1
spring_v1
0.0.1-SNAPSHOT
war
UTF-8
4.0.2.RELEASE
1.6.6
5.1.34
org.springframework
spring-context
${springmvc.version}
org.springframework.webflow
spring-webflow
2.3.2.RELEASE
org.springframework
spring-jdbc
3.0.5.RELEASE
org.springframework
spring-context-support
${springmvc.version}
org.freemarker
freemarker
2.3.20
com.alibaba
druid
0.2.21
com.alibaba
fastjson
1.1.24
org.mybatis
mybatis
3.2.2
org.mybatis
mybatis-spring
1.2.2
org.mybatis.caches
mybatis-ehcache
1.0.2
mysql
mysql-connector-java
${mysql-connector-java.version}
org.codehaus.jackson
jackson-core-asl
1.9.13
org.codehaus.jackson
jackson-mapper-asl
1.9.13

 

 二:web.xml 配置

spring_v1
contextConfigLocation
classpath*:/spring-application.xml
org.springframework.web.context.ContextLoaderListener
spring-mvc
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath*:/spring-mvc.xml
1
spring-mvc
/
CharacterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
utf-8
CharacterEncodingFilter
/*

三:spring-application.xml 配置

UTF-8
UTF-8
1
auto_detect
true
true
0.##########
yyyy-MM-dd HH:mm:ss
ignore
freemarker.ext.beans.BeansWrapper

四:app.properties 配置

database.url=jdbc:mysql://localhost:3306/springv?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8 database.driver=com.mysql.jdbc.Driverdatabase.user=rootdatabase.password=root

 

以上四步配置后,创建controller进行测试。

五:创建Controller

package com.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.servlet.ModelAndView;@Controller //控制器(注入服务)@RequestMapping(value="") //访问地址,value="index" 则访问地址为:XXXX/indexpublic class IndexAction {        /**     * @param value :值同上用于访问命名     */    @RequestMapping(value = "" ,method = RequestMethod.GET)    public ModelAndView initLoad() throws Exception {        //值为视图文件所在位置。        ModelAndView mav = new ModelAndView("index");                return mav;    }}

运行。。。。。。。

输入自己的地址+项目名:http://localhsot:8080/spring_v1

完成!

 

下面使用service从数据库调用数据试试看。

这里使用mybatis的自动生成工具 mybatis-generator

下载地址:

 

如果是初学者,提供下教程:

1解压后,打开lib/generatorConfig.xml

配置如下:

 

根据自己数据库情况,配置好后 按shift+右键-在此处打开命令窗口:

输入:java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -overwrite    

回车OK。最后把生成好的文件放入项目中,可以开始写service了。

 

数据库随便写了个,来测试。

 

六:创建service 类

package com.service;import java.util.List;import com.entity.User;public interface UserService {            public abstract User findByKey(int userId)throws Exception;}

 

七:创建serviceImpl 实现类

package com.serviceImpl;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.common.orm.mapper.UserMapper;import com.entity.User;import com.service.UserService;@Service("userService")public class UserServiceImpl implements UserService {    @Autowired    private UserMapper usermapper;    @Override    public User findByKey(int userId) {                return usermapper.selectByPrimaryKey(userId);    }}

注意:springmvc的@注解,要填写上。

 

八:创建UserAction 

package com.controller;import java.util.HashMap;import java.util.Map;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.ResponseBody;import com.entity.User;import com.service.UserService;@Controller@RequestMapping(value="user")public class UserAction {        @Autowired    private UserService userService;        @RequestMapping(value = "" ,method = RequestMethod.POST)    @ResponseBody    public Map
findUser(String userId) throws Exception { User user = userService.findByKey(Integer.parseInt(userId)); Map
map = new HashMap
(); map.put("userName", user.getUserName()); return map; }}

 

九:JSP

页面就用index.jsp 写吧。

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%>
Insert title here
---

这里 include了common.jsp,用来引用js,css等作用,方便以后拓展。

common.jsp 如下:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%    String path = request.getContextPath();    String basePath = request.getScheme() +"://" + request.getServerName() + ":" +  request.getServerPort() +  path;%> 

 完成以上,

URL地址访问:localhost:8080/spring_v1

 

 

OK!

 

下面配置freemarker自定义模板。

还记得在spring-application.xml中的这一段代码。

十:创建自定义模板

package com.freemarker;import java.io.IOException;import java.io.StringReader;import java.io.Writer;import java.util.ArrayList;import java.util.HashMap;import java.util.Map;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;import com.entity.User;import com.service.UserService;import freemarker.core.Environment;import freemarker.template.ObjectWrapper;import freemarker.template.Template;import freemarker.template.TemplateDirectiveBody;import freemarker.template.TemplateDirectiveModel;import freemarker.template.TemplateException;import freemarker.template.TemplateModel;@Component("indexLinkTag")public class IndexLinkTag implements TemplateDirectiveModel {    @Autowired    private FreeMarkerConfigurer freeMarkerConfigurer;    @Autowired    private UserService userService;      /*     *@param env 系统环境变量,通常用它来输出相关内容,如Writer out = env.getOut();     *@param loopVars  循环替代变量     *@param body 用于处理自定义标签中的内容,如<@myDirective>将要被处理的内容
;当标签是<@myDirective />格式时,body=null */ @Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { try { String countval = String.valueOf(params.get("userId")); int userId = Integer.parseInt(countval); User user =userService.findByKey(userId); ArrayList
list = new ArrayList
(); list.add(user.getUserName()); if (body != null) { TemplateModel sourceVariable = env.getVariable("indexLinkTagList"); env.setVariable("indexLinkTagList", ObjectWrapper.BEANS_WRAPPER.wrap(list)); body.render(env.getOut()); env.setVariable("indexLinkTagList", sourceVariable); } } catch (Exception e) { e.printStackTrace(); } }}

十一:创建ftl(index.ftl)

    [@index_Link userId =5 ]                
    [#list indexLinkTagList as indexLink]
  • ${indexLink}
  • [/#list]
[/@index_Link]

 

在Action添加进去

package com.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.servlet.ModelAndView;@Controller //控制器(注入服务)@RequestMapping(value="") //访问地址,value="index" 则访问地址为:XXXX/indexpublic class IndexAction {        /**     * @param value :值同上用于访问命名     */    @RequestMapping(value = "" ,method = RequestMethod.GET)    public ModelAndView initLoad() throws Exception {        //值为视图文件所在位置。        ModelAndView mav = new ModelAndView("index");                return mav;    }    @RequestMapping(value = "ftl" ,method = RequestMethod.GET)    public ModelAndView initFltLoad() throws Exception {        ModelAndView mav = new ModelAndView("ftl/index");                return mav;    }}

 

访问 localhost:8080/spring_v1/ftl

搞定!

转载于:https://www.cnblogs.com/mangyang/p/5168291.html

你可能感兴趣的文章
数据结构之最大不重复串
查看>>
为什么要配置sdk-tools/platform-toools?
查看>>
自己动手开发更好用的markdown编辑器-07(扩展语法)
查看>>
maven dependency:tree中反斜杠的含义
查看>>
队列的循环队列
查看>>
程序中的日期格式
查看>>
大众点评CAT错误总结以及解决思路
查看>>
从0开始学爬虫3之xpath的介绍和使用
查看>>
Shell成长之路
查看>>
vim下正则表达式的非贪婪匹配
查看>>
一个python的计算熵(entropy)的函数
查看>>
spring源码学习——spring整体架构和设计理念
查看>>
模拟window系统的“回收站”
查看>>
OpenCV中的split函数
查看>>
MongoDB divide 使用之mongotempalte divide
查看>>
SSH不允许进行DNS解析
查看>>
Git(介绍和安装)
查看>>
磁盘管理
查看>>
重写与重载
查看>>
Python 爬取qqmusic音乐url并批量下载
查看>>