springMVC系列之(三) spring+springMVC集成(annotation方式)

  个人认为使用框架并不是很难,关键要理解其思想,这对于我们提高编程水平很有帮助。不过,如果用都不会,谈思想就变成纸上谈兵了!!!先技术,再思想。实践出真知。


1、基本概念


1.1、Spring


        Spring是一个开源框架,Spring是于2003 年兴起的一个轻量级的Java 开发框架,由Rod Johnson 在其著作Expert One-On-One J2EE Development and Design中阐述的部分理念和原型衍生而来。它是为了解决企业应用开发的复杂性而创建的。Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅限于服务器端的开发。从简单性、可测试性和松耦合的角度而言,任何Java应用都可以从Spring中受益。 简单来说,Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器框架。


1.2、SpringMVC

     

        Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面。Spring MVC 分离了控制器、模型对象、分派器以及处理程序对象的角色,这种分离让它们更容易进行定制。



2.环境搭建详解


2.1引入相应的包

        springMVC和spring包的结构发生了很大的变化,各个包都分开了,灵活,要求使用者更加深入的学习使用,当我们引入包的时候,以少为原则,少的话可以根据报错来找到相应的包,如果过多的话,包会报错异常的混乱,不容易分辨;sprinMVC和spring本身就是一家的,所以引入的包来说基本上和spring需要的架构包是一致的.



2.2  新建注解xml文件  :springAnnotation-servlet.xml


[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;"><span style="font-size:18px;"><span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"    
  3.  xmlns:context="http://www.springframework.org/schema/context"    
  4.  xmlns:p="http://www.springframework.org/schema/p"    
  5.  xmlns:mvc="http://www.springframework.org/schema/mvc"    
  6.  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
  7.  xsi:schemaLocation="http://www.springframework.org/schema/beans    
  8.       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    
  9.       http://www.springframework.org/schema/context    
  10.       http://www.springframework.org/schema/context/spring-context.xsd    
  11.       http://www.springframework.org/schema/mvc    
  12.       http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">  
  13.      <!-- 注解扫描包 -->  
  14.     <context:component-scan base-package="com.tgb.web.controller.annotation" />  
  15.     <!-- 开启注解 -->  
  16.       
  17.     <mvc:annotation-driven/>  
  18.       
  19.     <!-- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />  
  20.     <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean> -->  
  21.     <!-- 静态资源访问 -->  
  22.      <mvc:resources location="/img/" mapping="/img/**"/>    
  23.      <mvc:resources location="/js/" mapping="/js/**"/>     
  24.       
  25.   
  26.     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  27.         <property name="prefix" value="/"></property>  
  28.         <property name="suffix" value=".jsp"></property>  
  29.     </bean>  
  30.       
  31.     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
  32.           <property name="defaultEncoding" value="utf-8" />  
  33.           <property name="maxUploadSize" value="10485760000" />  
  34.           <property name="maxInMemorySize" value="40960" />  
  35.     </bean>  
  36.  </beans>  </span></span></span>  

2.3 建springxml文件 springAnnotation-core.xml

      通过bean注入要调用的接口实现类

[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;"><span style="font-size:18px;"><span style="font-size:18px;"><beans>  
  2.     <bean id="springManager" class="com.tgb.web.controller.annotation.SpringManager"></bean>  
  3. </beans></span></span></span>  





2.3.1  ISpring接口
[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;"><span style="font-size:18px;"><span style="font-size:18px;">public interface ISpring {  
  2.   
  3.     public String get();  
  4. }</span></span></span>  

2.3.2  ISpring实现类
[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;"><span style="font-size:18px;"><span style="font-size:18px;">public class SpringManager implements ISpring {  
  2.   
  3.     @Override  
  4.     public String get() {  
  5.         //判定是否调用了  
  6.         System.out.println("------I am springManager----");  
  7.           
  8.         return "I am getMethod";  
  9.     }  
  10.   
  11. }</span></span></span>  



2.3.3  SpringController类

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;"><span style="font-size:18px;"><span style="font-size:18px;">public class SpringController {  
  2. //这样代替了再xml中配置属性的过程  
  3.     @Resource(name="springManager")  
  4.     private ISpring springManager;//注入springManager  
  5.       
  6.       
  7.     @RequestMapping("/spring/get")  
  8.     public String get(){  
  9.         System.out.println(springManager.get());  
  10.         return "/success";  
  11.     }  
  12. }</span></span></span>  


一个项目的全局配置点在web.xml,一个项目需要使用了多少框架,通过xml可以查看.



[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. <span style="font-size:18px;"><span style="font-size:18px;"><span style="font-size:18px;"><?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">  
  3.   <display-name>springMVC8</display-name>  
  4.   <welcome-file-list>  
  5.     <welcome-file>index.html</welcome-file>  
  6.     <welcome-file>index.htm</welcome-file>  
  7.     <welcome-file>index.jsp</welcome-file>  
  8.     <welcome-file>default.html</welcome-file>  
  9.     <welcome-file>default.htm</welcome-file>  
  10.     <welcome-file>default.jsp</welcome-file>  
  11.   </welcome-file-list>  
  12.     
  13.   <context-param>  
  14.         <param-name>contextConfigLocation</param-name>  
  15.         <param-value>classpath*:config/springAnnotation-core.xml</param-value>  
  16.         <!-- <param-value>classpath*:config/springAnnotation-servlet.xml</param-value> -->  
  17.   </context-param>  
  18.     
  19. <!--   配置spring启动listener入口 -->  
  20.   <listener>  
  21.      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  22.   </listener>  
  23.   <!-- 配置springMVC启动DispatcherServlete入口 -->  
  24.   <servlet>  
  25.     <servlet-name>springMVC</servlet-name>  
  26.     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  27.         <init-param>  
  28.             <param-name>contextConfigLocation</param-name>  
  29.             <!-- <param-value>classpath*:config/springAnnotation-core.xml</param-value> -->  
  30.              <param-value>classpath*:config/springAnnotation-servlet.xml</param-value>   
  31.         </init-param>  
  32.     <load-on-startup>1</load-on-startup>  
  33.   </servlet>  
  34.     
  35.     <filter>  
  36.         <filter-name>encodingFilter</filter-name>  
  37.         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  38.         <init-param>  
  39.             <param-name>encoding</param-name>  
  40.             <param-value>UTF-8</param-value>  
  41.         </init-param>  
  42.         <init-param>  
  43.             <param-name>forceEncoding</param-name>  
  44.             <param-value>true</param-value>  
  45.         </init-param>  
  46.     </filter>  
  47.     <!-- encoding filter for jsp page -->  
  48.     <filter-mapping>  
  49.         <filter-name>encodingFilter</filter-name>  
  50.         <url-pattern>/*</url-pattern>  
  51.     </filter-mapping>  
  52.    
  53.    
  54.     
  55.   <servlet-mapping>  
  56.     <servlet-name>springMVC</servlet-name>  
  57.     <url-pattern>/</url-pattern>  
  58.   </servlet-mapping>  
  59. </web-app></span></span></span>  



注解:springMVC是通过dispastservlet来监听的,spring使用linstener监听的,他们之间的启动顺序,web容器有又一个即,

第一:context-param

第二:Listerer

第三:Filter

第四:servlet

这样的启动顺序是有一定联系的







总结

                 一张图胜过千言万语哈!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个Spring+SpringMVC+Mybatis的SSM中使用Shiro进行登陆验证的完整程序示例: 1. 添加依赖 在pom.xml文件中添加Shiro的依赖: ```xml <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.7.1</version> </dependency> ``` 2. 配置Shiro 在Spring的配置文件中添加Shiro的配置,例如在applicationContext.xml中添加如下配置: ```xml <!-- Shiro配置 --> <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm" ref="myRealm" /> </bean> <bean id="myRealm" class="com.example.shiro.MyRealm"> <property name="credentialsMatcher"> <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher"> <property name="hashAlgorithmName" value="SHA-256" /> </bean> </property> </bean> <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager" ref="securityManager" /> <property name="loginUrl" value="/login.jsp" /> <property name="successUrl" value="/index.jsp" /> <property name="unauthorizedUrl" value="/unauthorized.jsp" /> <property name="filterChainDefinitions"> <value> /login.jsp = anon /login.do = anon /logout.do = logout /** = authc </value> </property> </bean> ``` 其中,securityManager配置了SecurityManager实现类;myRealm配置了自定义的Realm实现类;shiroFilter配置了ShiroFilter的相关设置。 3. 编写Realm实现类 创建一个自定义的Realm实现类,用于验证用户的账号和密码。具体代码如下: ```java import java.util.HashSet; import java.util.Set; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authc.credential.HashedCredentialsMatcher; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; public class MyRealm extends AuthorizingRealm { //模拟数据库中的用户信息 private static final String USERNAME = "admin"; private static final String PASSWORD = "admin"; private static final String SALT = "123456"; @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { //授权 Set<String> roles = new HashSet<>(); roles.add("admin"); SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(roles); return authorizationInfo; } @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { //认证 UsernamePasswordToken upToken = (UsernamePasswordToken) token; String username = upToken.getUsername(); if (!USERNAME.equals(username)) { return null; } String password = PASSWORD; String salt = SALT; HashedCredentialsMatcher matcher = new HashedCredentialsMatcher("SHA-256"); matcher.setHashIterations(1024); SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username, password, matcher); authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(salt)); return authenticationInfo; } } ``` 其中,doGetAuthorizationInfo方法用于授权,可以设置用户的角色和权限;doGetAuthenticationInfo方法用于认证,可以验证用户的账号和密码。 4. 编写登陆验证代码 在Java代码中创建一个Shiro的工具类,用于登陆验证和权限控制。具体代码如下: ```java import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; public class ShiroUtils { @Autowired private SecurityManager securityManager; public boolean login(String username, String password) { //1.将SecurityManager设置到运行环境中 SecurityUtils.setSecurityManager(securityManager); //2.创建Subject Subject subject = SecurityUtils.getSubject(); //3.创建Token UsernamePasswordToken token = new UsernamePasswordToken(username, password); try { //4.登陆 subject.login(token); return true; } catch (UnknownAccountException e) { //用户名不存在 System.out.println("用户名不存在"); } catch (IncorrectCredentialsException e) { //密码错误 System.out.println("密码错误"); } catch (LockedAccountException e) { //账户被锁定 System.out.println("账户被锁定"); } catch (AuthenticationException e) { //认证失败 System.out.println("认证失败"); } return false; } public void logout() { //1.获取Subject Subject subject = SecurityUtils.getSubject(); //2.登出 subject.logout(); } } ``` 5. 在Controller中使用Shiro进行登陆验证 在需要进行登陆验证的Controller中,引入ShiroUtils,并调用其login方法进行验证。具体代码如下: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class LoginController { @Autowired private ShiroUtils shiroUtils; @RequestMapping("/login.do") public String login(String username, String password) { if (shiroUtils.login(username, password)) { return "redirect:/index.jsp"; } else { return "redirect:/login.jsp"; } } } ``` 以上就是一个简单的Spring+SpringMVC+Mybatis的SSM中使用Shiro进行登陆验证的完整程序示例。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值