spring 3.1 mvc 例子浅谈(1)

来源:互联网 发布:手写软件吧 编辑:程序博客网 时间:2024/04/29 22:58

以前都是用struts2+spring来做项目,遇到了两次struts2的安全漏洞升级感觉很烦,也许spring mvc也没有那么安全,但是还是学习了一下.

(基于注解)


web.xml

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext.xml</param-value>
</context-param>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 设置dispatcher-servlet.xml位置,这里没有放到WEB-INF下 -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param> 
           <param-name>contextConfigLocation</param-name> 
           <param-value>classpath:dispatcher-servlet.xml</param-value> 
  </init-param> 
<load-on-startup>2</load-on-startup>
</servlet>
<!-- 设置请求的后缀 -->
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>



 applicationContext.xml 中做了一些ibatis 和数据源的的常规配置

<!-- properties file -->
<bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
    <list>
  <value>classpath:conf.properties</value>
  <value>classpath:database.properties</value>
    </list>
  </property>
  </bean>  


<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass">
<value>${database.driverClass}</value>   
</property>
<property name="jdbcUrl">
<value>${database.jdbcUrl}</value>
</property>
<property name="user">
<value>${database.user}</value>
</property>
<property name="password">
<value>${database.password}</value>
</property>
<property name="initialPoolSize">
<value>${c3p0.initialPoolSize}</value>
</property>
<property name="minPoolSize">
<value>${c3p0.minPoolSize}</value>
</property>
<property name="maxPoolSize">
<value>${c3p0.maxPoolSize}</value>
</property>
<property name="idleConnectionTestPeriod">
<value>${c3p0.idleConnectionTestPeriod}</value>
</property>
</bean>   

<!-- iBatis 模板-->
<bean id="sqlMapClientTemplate" class="org.springframework.orm.ibatis.SqlMapClientTemplate" >
<property name="sqlMapClient" ref="sqlMapClient" />
</bean>

<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
  <property name="configLocation" value="classpath:SqlMapConfig.xml"/>
<property name="dataSource" ref="dataSource"></property>
</bean>

<bean id="jdbc_TransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>


dispatcher-servlet.xml配置

关于使用拦截器的方法我使用了<mvc:interceptor> 原因是其他方式我不知道该如何控制具体的拦截路径

如果有更好的方法希望看到的朋友提出来

    <context:component-scan base-package="com.show" />    
    <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->  
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> 


    <!-- 指定了表现层资源的前缀和后缀 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
       p:prefix="/" p:suffix=".jsp" />


<!-- 使用拦截器 -->     
<mvc:interceptors>
   <mvc:interceptor>
    <!-- 需要拦截的路径,这样就会默认admin目录下的所有请求都拦截 -->
       <mvc:mapping path="/admin/**"/> 
       <bean class="com.show.oper.interceptor.AdminInterceptor"/>
   </mvc:interceptor>
</mvc:interceptors>


简单的用户登录Controller

package com.show.oper.controller.admin.impl;


import java.util.Map;


import javax.annotation.Resource;
import javax.servlet.http.HttpSession;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;


import com.show.oper.controller.admin.IUserController;
import com.show.oper.service.admin.IUserService;
import com.show.oper.vo.SessionAdminUser;
import com.show.oper.vo.User;


@Controller 
@RequestMapping("admin")
public class UserController implements IUserController {

@Resource(name="userService")
private IUserService userService;

/**
* 用户登录
*/
@RequestMapping("userLogin")           //如果请求连接为 xxx/admin/userLogin.action
public String userLogin(HttpSession session,User user) {

if(("".equals(user.getUserId()) || null==user.getUserId()) || ("".equals(user.getPassWord()) || null==user.getPassWord())){
return "admin/error";
}
Map<String,Object> map = userService.userLogin(user.getUserId(), user.getPassWord());


if(null == map){
return "admin/error";
}
SessionAdminUser saUser = new SessionAdminUser();
saUser.setUserId(String.valueOf(map.get("userId")));
saUser.setPassWord(String.valueOf(map.get("passWord")));
saUser.setNickName(String.valueOf(map.get("nickName")));

session.setAttribute("COMMON_USER_SESSION_KEY", saUser);

return "redirect:index.jsp";
}
}


拦截器


public class AdminInterceptor implements HandlerInterceptor {
private static HashSet<String> escapeResource = null;
/**
* 在DispatcherServlet完全处理完请求后被调用
*/
public void afterCompletion(HttpServletRequest arg0,HttpServletResponse arg1, Object arg2, Exception arg3)throws Exception {

}
/**
* controller方法执行完后被调用
*/
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,Object arg2, ModelAndView arg3) throws Exception {

}
/**
* 在需要拦截的请求controller前执行
*/
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,Object arg2) throws Exception {
//创建不需要验证的请求
if(escapeResource == null) {
escapeResource = new HashSet<String>();
escapeResource.add("/admin/login.action");  //进入登录页面
escapeResource.add("/admin/logout.action");  //登出
escapeResource.add("/admin/userLogin.action");
}
String resourceUrl = arg0.getServletPath();
String contextPath = arg0.getContextPath();
if(escapeResource.contains(resourceUrl)){
return true;
}else{
SessionAdminUser sessionUser = (SessionAdminUser) arg0.getSession().getAttribute("COMMON_USER_SESSION_KEY");
//验证用户是否已经登录
if(sessionUser == null) {
arg1.sendRedirect(contextPath+"/admin/jumpPage.jsp");
return false;
}else{
if(sessionUser.getUserId() == null){
arg1.sendRedirect(contextPath+"/admin/jumpPage.jsp");//跳转到jumpPage.jsp页面
return false;
}
}
}



return true;
}

原创粉丝点击