spring MVC的一些小技巧
1,在controller中获取指定name的bean
/***
*
* @param request
* @param beanName : 例如 userDao ,adminDao
* @return
*/
public Object getBean(HttpServletRequest request,String beanName){
WebApplicationContext webApp=RequestContextUtils.getWebApplicationContext(request, request.getSession().getServletContext());
return webApp.getBean(beanName);
}
2,在controller中根据实体类自动注入dao
/***
* 从WebApplicationContext 获取dao
* @param request
* @return
*/
private GenericDao<T> getDaoByWebApp(HttpServletRequest request){
if(ValueWidget.isNullOrEmpty(dao)){
WebApplicationContext webApp=RequestContextUtils.getWebApplicationContext(request , request.getSession().getServletContext());
try {
dao=(GenericDao<T>)webApp.getBean(ValueWidget.title(SystemHWUtil.getFileSuffixName(clz.getName()+"Dao")));//返回的是同一个对象
} catch (NoSuchBeanDefinitionException e) {
// e.printStackTrace();
dao=(GenericDao<T>)webApp.getBean(SystemHWUtil.getFileSuffixName(clz.getName()+"Dao"));//返回的是同一个对象
}
System.out.println("dao:"+dao);
}
return dao;
}
那么clz 是如何获取的呢?
protected final Class<T> clz = SystemHWUtil.getGenricClassType(getClass());
/***
* 获取实际的子类的class
*
* @param clz
* @return
*/
public static <T> Class<T> getGenricClassType(
@SuppressWarnings("rawtypes") Class clz) {
Type type = clz.getGenericSuperclass();
if (type instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) type;
Type[] types = pt.getActualTypeArguments();
if (types.length > 0 && types[0] instanceof Class) {
// System.out.println("class:"+types[0]);
return (Class) types[0];
}
}
return (Class) Object.class;
}
3,在controller的action中指定response 的content type
使用produces
/***
* 登录
* @param model
* @param status
* @param view
* @param session
* @param request
* @param callback
* @return
* @throws IOException
*/
@ResponseBody
@RequestMapping(value = "/login", produces = SystemHWUtil.RESPONSE_CONTENTTYPE_JSON_UTF)
public String login(Model model, Integer status, UserView view,Integer issavePasswd,
HttpSession session, HttpServletRequest request,HttpServletResponse response, String callback)
throws IOException {
init(request);
String content = null;
UserDao userDao = (UserDao) getDao();
User user2 = null;
Map map = new HashMap();
int login_result = 0;
AccessLog accessLog=logInto(request);
accessLog.setDescription("会员登录");
if (ValueWidget.isNullOrEmpty(view.getUsername())) {
login_result = Constant2.LOGIN_RESULT_USERNAME_EMPTY;//用户名不能为空
accessLog.setOperateResult("用户名不能为空");
} else if (ValueWidget.isNullOrEmpty(view.getPassword())) {
login_result = Constant2.LOGIN_RESULT_PASSWORD_EMPTY;//密码不能为空
accessLog.setOperateResult("密码不能为空");
} else if (ValueWidget.isNullOrEmpty(user2 = userDao.getByUsername(view
.getUsername()))) {
login_result = Constant2.LOGIN_RESULT_USERNAME_INVALID;//用户名不存在
accessLog.setOperateResult("用户名不存在");
} else if (!user2.getPassword().equals(view.getPassword())) {
login_result = Constant2.LOGIN_RESULT_FAILED;//登录失败(用户名和密码不匹配)
accessLog.setOperateResult("登录失败(用户名和密码不匹配)");
} else {
login_result = Constant2.LOGIN_RESULT_SUCCESS;
session.setAttribute(Constant2.SESSION_KEY_LOGINED_USER, user2);
map.put("session", session.getId());// 下载session id到客户端
map.put("userId", user2.getId());// 下载session id到客户端
System.out.println("session id:" + session.getId());
Map mapCookie=new HashMap();
if(issavePasswd/*包装类型*/!=null&&issavePasswd==1) {//记住密码
mapCookie.put(Constant2.COOKIE_KEY_USERNAME, user2.getUsername());
mapCookie.put(Constant2.COOKIE_KEY_PASSWORD, user2.getPassword());
}else{
mapCookie.put(Constant2.COOKIE_KEY_USERNAME, false);
mapCookie.put(Constant2.COOKIE_KEY_PASSWORD, false);
}
WebServletUtil.rememberMe(request,response,mapCookie);
accessLog.setOperateResult("登录成功,session id:"+session.getId());
}
// boolean isExist = userDao.isExist(view.getUsername(),
// view.getPassword());
map.put(Constant2.LOGIN_RESULT_KEY, login_result);
logSave(accessLog, request);
content = JSONPUtil.getJsonP(map, callback);
return content;
}
4,使用eclipse开发Java web项目时获取指定目录的真实绝对路径
String realpath =WebServletUtil.getUploadPath(request, "upload/download/apk", request
.getSession().getServletContext(), Constant2.SRC_MAIN_WEBAPP);
/***
*
* @param request
* @param uploadFolderName
* @return
*/
public static final String getUploadPath(HttpServletRequest request,
String uploadFolderName, ServletContext sContext, String webappPath/*src\main\webapp
*/) {
// project name:"/demo_channel_terminal"
String projectName = request.getContextPath();// value:/shop_goods or
// "/springMVC_upload"
String uploadPath = WebServletUtil.getUploadedPath(
uploadFolderName/* "upload\" */, projectName, sContext,
webappPath/* "src\main\webapp\" */);
return uploadPath;
}
/***
* java web //
* D:\xxx\eclipse\workspace\.metadata\.plugins\org.eclipse.wst.server
* .core\tmp0\wtpwebapps\shop_goods\images //
* D:\xxx\eclipse\workspace\shop_goods\ upload
*
* @param uploadFolderName
* @param projectName
* @param sContext
* @return
*/
public static String getUploadedPath(String uploadFolderName,
String projectName, ServletContext sContext,String webappPath/*src\main\webapp*/ ) {
String uploadFolder_tmp = null;
if (uploadFolderName.startsWith(File.separator)) {
uploadFolder_tmp = uploadFolderName;
} else {
uploadFolder_tmp = File.separator + uploadFolderName;// "/upload"
}
String realpath = sContext.getRealPath(uploadFolder_tmp);//D:\software\eclipse\workspace2\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\springMVC_upload\attached
//区别在于是否是使用eclipse 来启动http服务(tomcat)
String reg=".metadata\\.plugins";
boolean isContain=realpath.contains(reg);
System.out.println("[getUploadedPath]isContain:"+isContain);
if(!isContain){
webappPath=null;
}
// project name ,eg.shop_goods
projectName = SystemHWUtil.deleteFrontSlash(projectName);
realpath = SystemHWUtil.getRealPath(realpath, projectName);
String result=null;//D:\software\eclipse\workspace2\springMVC_upload\src\main\webapp\attached
if(!ValueWidget.isNullOrEmpty(webappPath)){
//目的:把"http://localhost:8080/springMVC_upload/upload/image/"变为:
//"http://localhost:8080/springMVC_upload/src/main/webapp/upload/image/"
result=realpath.replaceAll("("+SystemHWUtil.deleteAfterSlash(uploadFolderName).replaceAll(File.separator.replace("\\", "\\\\")/* 因为\需要转义 */+"$", "") +"[\\/]?)$", webappPath.replace("\\", "\\\\")+"$1");
}else{
result=realpath;
}
System.out.println("[WebServletUtil.getUploadedPath]result:"+result);
return result;
}
相关常量
public static final String SRC_MAIN_WEBAPP="src\\main\\webapp\\";
5,spring MVC接收 jsonp 跨域请求
/***
* 登录
* @param model
* @param status
* @param view
* @param session
* @param request
* @param callback
* @return
* @throws IOException
*/
@ResponseBody
@RequestMapping(value = "/login", produces = SystemHWUtil.RESPONSE_CONTENTTYPE_JSON_UTF)
public String login(Model model, Integer status, UserView view,Integer issavePasswd,
HttpSession session, HttpServletRequest request,HttpServletResponse response, String callback)
throws IOException {
init(request);
String content = null;
UserDao userDao = (UserDao) getDao();
User user2 = null;
Map map = new HashMap();
int login_result = 0;
AccessLog accessLog=logInto(request);
accessLog.setDescription("会员登录");
if (ValueWidget.isNullOrEmpty(view.getUsername())) {
login_result = Constant2.LOGIN_RESULT_USERNAME_EMPTY;//用户名不能为空
accessLog.setOperateResult("用户名不能为空");
} else if (ValueWidget.isNullOrEmpty(view.getPassword())) {
login_result = Constant2.LOGIN_RESULT_PASSWORD_EMPTY;//密码不能为空
accessLog.setOperateResult("密码不能为空");
} else if (ValueWidget.isNullOrEmpty(user2 = userDao.getByUsername(view
.getUsername()))) {
login_result = Constant2.LOGIN_RESULT_USERNAME_INVALID;//用户名不存在
accessLog.setOperateResult("用户名不存在");
} else if (!user2.getPassword().equals(view.getPassword())) {
login_result = Constant2.LOGIN_RESULT_FAILED;//登录失败(用户名和密码不匹配)
accessLog.setOperateResult("登录失败(用户名和密码不匹配)");
} else {
login_result = Constant2.LOGIN_RESULT_SUCCESS;
session.setAttribute(Constant2.SESSION_KEY_LOGINED_USER, user2);
map.put("session", session.getId());// 下载session id到客户端
map.put("userId", user2.getId());// 下载session id到客户端
System.out.println("session id:" + session.getId());
Map mapCookie=new HashMap();
if(issavePasswd/*包装类型*/!=null&&issavePasswd==1) {//记住密码
mapCookie.put(Constant2.COOKIE_KEY_USERNAME, user2.getUsername());
mapCookie.put(Constant2.COOKIE_KEY_PASSWORD, user2.getPassword());
}else{
mapCookie.put(Constant2.COOKIE_KEY_USERNAME, false);
mapCookie.put(Constant2.COOKIE_KEY_PASSWORD, false);
}
WebServletUtil.rememberMe(request,response,mapCookie);
accessLog.setOperateResult("登录成功,session id:"+session.getId());
}
// boolean isExist = userDao.isExist(view.getUsername(),
// view.getPassword());
map.put(Constant2.LOGIN_RESULT_KEY, login_result);
logSave(accessLog, request);
content = JSONPUtil.getJsonP(map, callback);
return content;
}
/***
* 用于jsonp调用
* @param map : 用于构造json数据
* @param callback : 回调的javascript方法名
* @param filters : <code>SimpleBeanPropertyFilter theFilter = SimpleBeanPropertyFilter
.serializeAllExcept("content");
FilterProvider filters = new SimpleFilterProvider().addFilter(
Constant2.SIMPLEFILTER_JACKSON_PAPERNEWS, theFilter);</code>
* @return : js函数名(json字符串)
*/
public static String getJsonP(Object map,String callback,FilterProvider filters)
{
ObjectMapper mapper = getObjectMapper();
String content = null;
ObjectWriter writer=null;
try {
if(filters!=null){
// content = mapper.writer(filters).writeValueAsString(map);
writer=mapper.writer(filters);
}else{
// content = mapper.writeValueAsString(map);
writer=mapper.writer();
}
content=writer.writeValueAsString(map);
System.out.println(content);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(ValueWidget.isNullOrEmpty(callback)){
return content;
}
return callback+"("+content+")";
}
/***
* jackson没有过滤
* @param map
* @param callback
* @return
*/
public static String getJsonP(Object map,String callback)
{
return getJsonP(map, callback, null);
}
public static String getJsonP(Object map)
{
return getJsonP(map, null, null);
}
/***
*
* @param key
* @param value2
* @param callback
* @return : js函数名(json字符串)
*/
public static String getJsonP(String key ,Object value2,String callback){
Map map = new HashMap();
map.put(key, value2);
return getJsonP(map, callback);
}
前端代码:
/***
* 会员登录
* @param username
* @param password
*/
var user_login=function(username,password){
// alert(username+","+password);
if(isHasLogin())
{
alert(LOGIN_MSG_HAVE_LOGINED_ALREADY);
//Toast.showShortCenter(LOGIN_MSG_HAVE_LOGINED_ALREADY);
return;
}
showMask2();
$.jsonP({url:'http://'+server_url+'/user/login?callback=?&username='+username+"&password="+password,success:function(data){
var result=data.result;
hideMask2();
switch (result)
{
case 1:
window.user={};
window.sessionId=data.session;
user.username=username;
user.password=password;
user.userId=data.userId;
settings_before(document.getElementById("settings"));
alert("登录成功");
//plugins.toast.showShortCenter("登录成功");
$.ui.goBack();
break;
case 3:
alert("用户名不能为空");
break;
case 4:
alert("密码不能为空");
break;
case 5:
alert("用户名或密码错误");
break;
case 2:
alert("用户名不存在");
break;
}
}});
}