您的位置:首页 > 编程语言 > Java开发

如何使用struts2+mybaties+freemarker实现web开发

2015-05-29 18:53 711 查看

welcome-file-list是一个配置在web.xml中的一个欢迎页,用于当用户在url中输入工程名称或者输入web容器url(如http://localhost:8080/)时直接跳转的页面.

 

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>,直接去找webcontent下的index.jsp
</welcome-file-list>

 这样直接就能去index.jsp页面了,但是若是首页需要经过一些数据处理才能显示的话只能这样,在webcontent下的index.jsp中写上这样的话

 

<%@ page language="java"  pageEncoding="UTF-8"%>
<jsp:forward page="/index.do"/>

 这样就去调用struts.xml中的

 

<action name="index" class="com.appsino.www.action.IndexProAction">
</action>

 在action中是这样子的

 

private String templetPath;
public IndexProAction(){}
public String execute(){
try {
String basePath="/www/templet/";
templetPath=basePath+"index.html";//index.html是freemarker生成的模板网页
Map<String, Object> data = new HashMap<String, Object>();
setData(data);
getHttpResponse().setCharacterEncoding("UTF-8");
FreeMarkerUtil.createWriter(getServletContext(), data, templetPath,getHttpResponse().getWriter());
} catch (Exception e) {
e.printStackTrace();
}

return null;
}

 

 所有的数据处理都放在setData(data);这个方法中进行处理,FreeMarkerUtil.createWriter()方法主要是生成静态模板

 

/**
* 设置静态化参数
*
* @param data
*/
public void setData(Map<String, Object> data) {
HttpServletRequest request=getHttpRequest();
data.put("contextPath", getContextPath());//主要是用于在html页面中的绝对路径,放在url前面的
String traAgId=String.valueOf(getTraAgId());
if(StringUtils.isNotEmpty(traAgId)){
data.put("traAgId", traAgId);//有这个id的话就是网店的数据
}
if(StringUtils.isNotEmpty(traAgCode)){
data.put("traAgCode", traAgCode);//有这个code的话就是网店的数据
}else{
//当地址栏没有cityCode参数则重新获取cityCode
if(StringUtils.isEmpty(cityCode)){//没有cityCode参数时
String c=readCityCookie();//主要是获取cookie
String[] city=c.split(";");
if(city.length>1){
data.put("cityCode", city[0]);
data.put("cityName", city[1]);
}else{
data.put("cityCode", "beijing");//要是没有cookie的话就放入默认的值
data.put("cityName", "北京");
}
}else{//有cityCode参数时则是自动放入当前的
data.put("cityCode", cityCode);
data.put("cityName", cityName);
}
}
// 获取参数并放入data
Enumeration<String> paramNames = getHttpRequest().getParameterNames();
if (paramNames != null && paramNames.hasMoreElements()) {
String name;
while (paramNames.hasMoreElements()) {
name = paramNames.nextElement();
if (name != null) {
data.put(name, getHttpRequest().getParameter(name));
}
}
}

//这个主要是当有游客登录时将登陆信息放在session中若是session不过期的话直接显示出游客的信息
Tourist tourist=null;

tourist=((Tourist)getHttpSession().getAttribute(TCConstant.LOGIN_TOURIST));

if(tourist==null){

String touristCookie=readTAccountCookie();//获取用户的cookie
if(touristCookie!=null){

tourist=getTourist(touristCookie);

getHttpSession().setAttribute(TCConstant.LOGIN_TOURIST, tourist);

}

}

if(tourist!=null){
data.put("touristName", tourist.getTouristName());//放入游客名
}

}

 涉及到两个方法readCityCookie()主要是获取到城市的cookie

 

private String cookieName="local_zone";
//读取cookie
private  String readCityCookie(){
String reCookie=null;
HttpServletRequest request=getHttpRequest();
Cookie[] cookies = request.getCookies();
if(null!=cookies){
/**
* 读取cookie
* if  cookie.getName.equals cityCode 则返回rcookie="";
* if  cookie 未找到  把cityCode cityName 写入 COOKIE
*/
for(Cookie cookie : cookies){
if(cookieName.equals(cookie.getName())){
try {
reCookie=URLDecoder.decode(cookie.getValue(), "UTF-8");
return reCookie;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

}else{
reCookie= "beijing;北京";

setCookie(reCookie);

return reCookie;
}
}
//如果没有cookie的话
}else{

AddressUtils addressUtils = new AddressUtils();//根据IP获取城市
String ip = getIpAddr();//正式环境使用
try {

cityName = addressUtils.getAddresses("ip=" + ip, "UTF-8");
if(StringUtil.isNotEmpty(cityName)){
if(cityName.contains("市")){
cityName=cityName.replaceAll("市", "").trim();
}
}
//addressUtils.getAddresses("ip=" + ip, "utf-8");//返回城市名
logger.info("根据ip地址获取的城市名"+cityName);
} catch (UnsupportedEncodingException e) {

e.printStackTrace();
}

cityCode=getDCityCode(cityName);
logger.info(cityCode+"code");
Cookie  cookie=null;

/**
* 根据IP地址找到DepartureCity表的 cityCode cityName
* 如果返回 unknown 则 此IP地址 所在城市 不在DepartureCity中
* 设置默认COOKIE为 “beijing;北京”
*/

if("unknown".equals(cityCode)){

reCookie= "beijing;北京";

setCookie(reCookie);

return reCookie;
}else{

reCookie=cityCode+";"+cityName;

setCookie(reCookie);

return reCookie;
}

}
return reCookie;
}
public void setCookie(String cookieCode){
HttpServletResponse response=getHttpResponse();

Cookie  cookie=null;
try {
logger.info("没找到匹配的时候:"+cookieCode);
cookie= new Cookie(cookieName,URLEncoder.encode(cookieCode,"UTF-8"));
logger.info("转化成UTF-8的时候:"+cookieName);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
cookie.setMaxAge(60*60*24*365);
response.addCookie(cookie);
}

public void rewriteCookie(String cityCode,String cityName){//重写cookie
HttpServletResponse response=getHttpResponse();
AddressUtils addressUtils = new AddressUtils();
Cookie  cookie=null;

try {

cookie= new Cookie(cookieName,cityCode+URLEncoder.encode(";"+cityName,"UTF-8"));

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

}

cookie.setMaxAge(60*60*24*365);
response.addCookie(cookie);
}
public String getDCityCode(String cityName){//根据城市获取cityCode
init("departureCityService");

DepartureCity dc=new DepartureCity();
dc.setCityName(cityName);

List<DepartureCity> dList=departureCityService.find(dc, "");

if(dList!=null && dList.size()>0){
logger.info("获得的城市还是code:"+dList.get(0).getCityName());
return dList.get(0).getCityCode();

}

return "unknown";
}

//获取IP地址
public String getIpAddr() {
HttpServletRequest request=getHttpRequest();

String ip = request.getHeader("X-Real-IP");

if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {

return ip;

}
ip = request.getHeader("X-Forwarded-For");

if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
// 多次反向代理后会有多个IP值,第一个为真实IP。
int index = ip.indexOf(',');

if (index != -1) {

return ip.substring(0, index);

} else {

return ip;

}
} else {

return request.getRemoteAddr();

}
}

 获取ip的工具类

 

package com.appsino.www.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
* 根据IP地址获取详细的地域信息
*
* @project:personGocheck
* @class:AddressUtils.java
* @author:heguanhua E-mail:37809893@qq.com
* @date:Nov 14, 2012 6:38:25 PM
*/
public class AddressUtils {
/**
*
* @param content
*            请求的参数 格式为:name=xxx&pwd=xxx
* @param encoding
*            服务器端请求编码。如GBK,UTF-8等
* @return
* @throws UnsupportedEncodingException
*/
public String getAddresses(String content, String encodingString)
throws UnsupportedEncodingException {
// 这里调用taobao的接口
String urlStr = "http://ip.taobao.com/service/getIpInfo.php";
// 从taobao取得IP所在的省市区信息
String returnStr = this.getResult(urlStr, content, encodingString);
if (returnStr != null) {
// 处理返回的省市区信息
System.out.println(returnStr);
//{"code":0,"data":{"country":"\u672a\u5206\u914d\u6216\u8005\u5185\u7f51IP","country_id":"IANA","area":"","area_id":"","region":"","region_id":"","city":"","city_id":"","county":"","county_id":"","isp":"","isp_id":"","ip":"127.0.0.1"}}
String[] temp = returnStr.split(",");
/*for (int i = 0; i < temp.length; i++) {
System.out.println(temp[i]);
}
结果
{"code":0
"data":{"country":"\u4e2d\u56fd"
"country_id":"CN"
"area":"\u534e\u5317"
"area_id":"100000"
"region":"\u5317\u4eac\u5e02"
"region_id":"110000"
"city":"\u5317\u4eac\u5e02"
"city_id":"110000"
"county":""
"county_id":"-1"
"isp":"\u6b4c\u534e\u7f51\u7edc"
"isp_id":"100080"
"ip":"58.30.15.255"}}
*/
if (temp.length < 3) {
return "0";// 无效IP,局域网测试
}
String region = (temp[7].split(":"))[1].replaceAll("\"", "");
region = decodeUnicode(region);// 省份
/**
* String country = ""; String area = ""; String region = ""; String
* city = ""; String county = ""; String isp = ""; for(int
* i=0;i<temp.length;i++){ switch(i){ case 1:country =
* (temp[i].split(":"))[2].replaceAll("\"", ""); country =
* decodeUnicode(country);//国家 break; case 3:area =
* (temp[i].split(":"))[1].replaceAll("\"", ""); area =
* decodeUnicode(area);//地区 break; case 5:region =
* (temp[i].split(":"))[1].replaceAll("\"", ""); region =
* decodeUnicode(region);//省份 break; case 7:city =
* (temp[i].split(":"))[1].replaceAll("\"", ""); city =
* decodeUnicode(city);//市区 break; case 9:county =
* (temp[i].split(":"))[1].replaceAll("\"", ""); county =
* decodeUnicode(county);//地区 break; case 11:isp =
* (temp[i].split(":"))[1].replaceAll("\"", ""); isp =
* decodeUnicode(isp);//ISP公司 break; } }
*/
// System.out.println(country+"="+area+"="+region+"="+city+"="+county+"="+isp);
return region;
}
return null;
}

/**
* @param urlStr
*            请求的地址
* @param content
*            请求的参数 格式为:name=xxx&pwd=xxx
* @param encoding
*            服务器端请求编码。如GBK,UTF-8等
* @return
*/
private String getResult(String urlStr, String content, String encoding) {
URL url = null;
HttpURLConnection connection = null;
try {
url = new URL(urlStr);
connection = (HttpURLConnection) url.openConnection();// 新建连接实例
connection.setConnectTimeout(2000);// 设置连接超时时间,单位毫秒
connection.setReadTimeout(2000);// 设置读取数据超时时间,单位毫秒
connection.setDoOutput(true);// 是否打开输出流 true|false
connection.setDoInput(true);// 是否打开输入流true|false
connection.setRequestMethod("POST");// 提交方法POST|GET
connection.setUseCaches(false);// 是否缓存true|false
connection.connect();// 打开连接端口
DataOutputStream out = new DataOutputStream(
connection.getOutputStream());// 打开输出流往对端服务器写数据
out.writeBytes(content);// 写数据,也就是提交你的表单 name=xxx&pwd=xxx
out.flush();// 刷新
out.close();// 关闭输出流
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream(), encoding));// 往对端写完数据对端服务器返回数据
// ,以BufferedReader流来读取
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
reader.close();
return buffer.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();// 关闭连接
}
}
return null;
}

/**
* unicode 转换成 中文
*
* @author fanhui 2007-3-15
* @param theString
* @return
*/
public static String decodeUnicode(String theString) {
char aChar;
int len = theString.length();
StringBuffer outBuffer = new StringBuffer(len);
for (int x = 0; x < len;) {
aChar = theString.charAt(x++);
if (aChar == '\\') {
aChar = theString.charAt(x++);
if (aChar == 'u') {
int value = 0;
for (int i = 0; i < 4; i++) {
aChar = theString.charAt(x++);
switch (aChar) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
value = (value << 4) + aChar - '0';
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
value = (value << 4) + 10 + aChar - 'a';
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
value = (value << 4) + 10 + aChar - 'A';
break;
default:
throw new IllegalArgumentException(
"Malformed      encoding.");
}
}
outBuffer.append((char) value);
} else {
if (aChar == 't') {
aChar = '\t';
} else if (aChar == 'r') {
aChar = '\r';
} else if (aChar == 'n') {
aChar = '\n';
} else if (aChar == 'f') {
aChar = '\f';
}
outBuffer.append(aChar);
}
} else {
outBuffer.append(aChar);
}
}
return outBuffer.toString();
}
/**
* 将字符串转成unicode
* @param str 待转字符串
* @return unicode字符串
*/
public static String unicode(String str) {
str = (str == null ? "" : str);
String tmp;
StringBuffer sb = new StringBuffer(1000);
char c;
int i, j;
sb.setLength(0);
for (i = 0; i < str.length(); i++) {
c = str.charAt(i);
sb.append("\\u");
j = (c >>> 8); // 取出高8位
tmp = Integer.toHexString(j);
if (tmp.length() == 1)
sb.append("0");
sb.append(tmp);
j = (c & 0xFF); // 取出低8位
tmp = Integer.toHexString(j);
if (tmp.length() == 1)
sb.append("0");
sb.append(tmp);

}
return (new String(sb));
}

// 测试
public static void main(String[] args) throws UnsupportedEncodingException {
/*AddressUtils addressUtils = new AddressUtils();
// 测试ip 219.136.134.157 中国=华南=广东省=广州市=越秀区=电信
String ip = "58.30.15.255";//北京市歌华有线的ip
String address = "";
try {
address = addressUtils.getAddresses("ip=" + ip, "utf-8").replaceAll("市", "").trim();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
//System.out.println(address);//通过ip查到是北京
//System.out.println(decodeUnicode("北京"));
//System.out.println(unicode("北京"));//把北京换成unicode吗\u5317\u4eac
/*
gb2312的操作
System.out.println(URLEncoder.encode("beijing;北京","gb2312"));//把字符串转化成gb2312编码:beijing%3B%B1%B1%BE%A9
System.out.println(URLEncoder.encode("|","gb2312"));//|的unicode编码是%7C
System.out.println(URLEncoder.encode(";","gb2312"));//;的unicode编码是%3B
System.out.println(URLDecoder.decode("beijing%3B%B1%B1%BE%A9", "gb2312"));//把gb2312编码的字符串转化为中文
*/
//utf-8的操作
System.out.println(URLEncoder.encode("beijing;北京","UTF-8"));//把字符串转化成UTF-8编码:beijing%3B%E5%8C%97%E4%BA%AC
System.out.println(URLEncoder.encode(";","UTF-8"));//;的unicode编码是%3B
System.out.println(URLDecoder.decode("beijing%3B%E5%8C%97%E4%BA%AC", "UTF-8"));//把UTF-8编码的字符串转化为中文

}

 最后是freemarkerUtil

 

package com.appsino.www.util;
public class FreeMarkerUtil {

/**
* 生成静态页面主方法     默认编码为UTF-8
* @param context ServletContext
* @param data 一个Map的数据结果集
* @param templatePath ftl模版路径
* @param htmlPath 生成静态页面的路径
* @throws TemplateException
* @throws IOException
*/
public static void createHTML(ServletContext context,Map<String,Object> data,String templatePath,String htmlPath) throws IOException, TemplateException{
createHTML(context, data, "UTF-8", templatePath, "UTF-8", htmlPath);
}
/**
* 生成静态页面主方法
* @param context ServletContext
* @param data 一个Map的数据结果集
* @param templatePath ftl模版路径
* @param templateEncode ftl模版编码
* @param htmlPath 生成静态页面的路径
* @param htmlEncode 生成静态页面的编码
* @throws IOException
* @throws TemplateException
*/
public static void createHTML(ServletContext context,Map<String,Object> data,String templetEncode,String templatePath,String htmlEncode,String htmlPath) throws IOException, TemplateException{

Configuration freemarkerCfg=initCfg(context, templetEncode);

//指定模版路径
Template template = freemarkerCfg.getTemplate(templatePath,templetEncode);
template.setEncoding(templetEncode);
//静态页面路径
File htmlFile = new File(htmlPath);
if (!htmlFile.getParentFile().exists()) {
htmlFile.getParentFile().mkdirs();
}
Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), htmlEncode));

//处理模版
template.process(data, writer);
writer.flush();
writer.close();
}
/**
* 处理页面后,装处理结果放入指定Out
* @param context
* @param data
* @param templatePath
* @throws TemplateModelException
*/
public static void createWriter(ServletContext context,Map<String,Object> data,String templatePath,Writer writer) throws TemplateModelException{
createWriter(context, data, "UTF-8", templatePath, "UTF-8",writer);
}
public static void createWriter(ServletContext context,Map<String,Object> data,String templetEncode,String templatePath,String htmlEncode,Writer writer) throws TemplateModelException{

Configuration freemarkerCfg=initCfg(context, templetEncode);

try {
//指定模版路径
Template template = freemarkerCfg.getTemplate(templatePath,templetEncode);
template.setEncoding(templetEncode);
//处理模版

template.process(data, writer);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 初始化freemarker配置
* @return
* @throws TemplateModelException
*/
public static Configuration initCfg(ServletContext context,String templetEncode) throws TemplateModelException{

Configuration freemarkerCfg=null;
//判断context中是否有freemarkerCfg属性
if (context.getAttribute("freemarkerCfg")!=null) {
freemarkerCfg=(Configuration)context.getAttribute("freemarkerCfg");
}else {
freemarkerCfg = new Configuration();
//加载模版
freemarkerCfg.setServletContextForTemplateLoading(context, "/");
freemarkerCfg.setEncoding(Locale.getDefault(), templetEncode);

//加载并设置freemarker.properties
Properties p = new Properties();
try {
p.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("freemarker.properties"));
} catch (IOException e) {
e.printStackTrace();
}
try {
freemarkerCfg.setSettings(p);
} catch (TemplateException e) {
e.printStackTrace();
}

//加载自定义标签
//demo
freemarkerCfg.setSharedVariable("demo", new DemoDirective());
//首页布局
freemarkerCfg.setSharedVariable("storeLayout", new LayoutDirective());
//导航菜单
freemarkerCfg.setSharedVariable("productCategoryList", new StoreProductCategoryDirective());
//首页栏目
freemarkerCfg.setSharedVariable("productCategoryMenuList", new StoreProductCategoryMenuDirective());
freemarkerCfg.setSharedVariable("proCatMap", new StoreProductCategoryLineDirective());

//客服
freemarkerCfg.setSharedVariable("custList", new CustServiceDirective());
//友情链接
freemarkerCfg.setSharedVariable("blogList", new BlogDirective());
//最新预订
freemarkerCfg.setSharedVariable("reservationList", new NewBookDirective());

}
return freemarkerCfg;
}
}

在struts.xml中需要配置

 

<!-- freemarker管理器 -->
<constant name="struts.freemarker.manager.classname"  value ="com.appsino.www.freemarker.manager.TravelFreemarkerMannger" />

 TravelFreemarkerMannger类

 

public class TravelFreemarkerMannger extends FreemarkerManager {
protected Configuration createConfiguration(ServletContext servletContext)
throws TemplateException {
// Configuration configuration =
// super.createConfiguration(servletContext);

Configuration configuration = FreeMarkerUtil.initCfg(servletContext,
"utf-8");

// configuration
// .setTemplateExceptionHandler(new FreemarkerExceptionHandler());

return configuration;
}
}

 这就是整个的web流程

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐