如何通过SpringMVC注解轻松实现用户登录功能?

2026-05-24 01:501阅读0评论SEO问题
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计2128个文字,预计阅读时间需要9分钟。

如何通过SpringMVC注解轻松实现用户登录功能?

原文示例:本文实例为大家分享了SpringMVC使用注解实现登录的具体代码,供大家参考。具体内容如下:

一、使用Component、Controller四大注解:① @Component:通用注解② @Controller:控制层注解③ @Service:业务层注解④ @Repository:数据访问层注解

二、@Component注解:@Component是通用注解,用于标注类,Spring会自动扫描并注册到Bean容器中。

三、@Controller注解:@Controller注解用于标注控制层,是SpringMVC中的核心注解,用于处理HTTP请求。

四、@Service注解:@Service注解用于标注业务层,用于封装业务逻辑。

五、@Repository注解:@Repository注解用于标注数据访问层,用于操作数据库。

本文实例为大家分享了SpringMVC使用注解实现登录的具体代码,供大家参考,具体内容如下

一、使用Component\Controller\Service\Repository四大注解类:

  • @Component 是通用标注
  • @Controller 标注 web 控制器
  • @Service 标注 Servicec 层的服务
  • @Respository 标注 DAO层的数据访问

这些注解都是类级别的,可以不带任何参数,也可以带一个参数,代表bean名字,在进行注入的时候就可以通过名字进行注入了。

二、@Resource和@Autowired注解的异同

  • @Autowired默认按类型装配,默认情况下必须要求依赖对象必须存在,如果要允许null值,可以设置它的required属性为false

例如:@Autowired(required=false),如果我们想使用名称装配可以结合@Qualifier注解进行使用

  • @Resource,默认安装名称进行装配,名称可以通过name属性进行指定,如果没有指定name属性,当注解写在字段上时,默认取字段名进行安装名称查找 ,如果注解写在setter方法上默认取属性名进行装配 。当找不到与名称匹配的bean时才按照类型进行装配。但是需要注意的是,如果name属性一旦指定,就只会按照名称进行装配。

三、其他注解类

(1) PathVariable注解类

@RequestMapping注解中使用占位符的情况下,需要使用@PathVariable注解指定占位符参数

(2) RequestParam注解类

表单提交数据时,可以通过这个注解来解决request.getParameter("uname")

(3) CookieValue注解类

如果要保存字符串数据,可以使用这个注解

(4) SessionAttributes注解类

如果希望在多个请求之间公用某个模型属性数据,则可以在控制器类标注一个@SessionAttributes,SpringMVC会将模型中对应的属性暂存到HttpSerssion中除了SessionAttributes,还可以直接用原生态的request.getSession()来处理

(5) ResponseBody注解类

如何通过SpringMVC注解轻松实现用户登录功能?

用于将Controller的方法返回的对象,通过适当的HttpMessageConverter(转换器)转换为指定格式后,写入到Response对象的body数据区; 返回如json、xml等时使用

(6)RequestHeader注解类

@RequestHeader注解,可以把Request请求header部分的值绑定到方法的参数上

四、应用注解来实现登录

(1)、创建工程如下:

(2)、配置文件pom.xml(主要是修改:dependencies的内容)

<project xmlns="maven.apache.org/POM/4.0.0" xmlns:xsi="www.w3.org/2001/XMLSchema-instance"     xsi:schemaLocation="maven.apache.org/POM/4.0.0 maven.apache.org/xsd/maven-4.0.0.xsd">     <modelVersion>4.0.0</modelVersion>     <groupId>springmvc</groupId>     <artifactId>springmvc</artifactId>     <version>0.0.1-SNAPSHOT</version>     <packaging>war</packaging>     <name />     <description />     <properties>         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>     </properties>     <dependencies>           <dependency>             <groupId>org.springframework</groupId>             <artifactId>spring-webmvc</artifactId>             <version>4.1.6.RELEASE</version>         </dependency>           <dependency>             <groupId>org.springframework</groupId>             <artifactId>spring-tx</artifactId>             <version>4.1.6.RELEASE</version>         </dependency>         <dependency>             <groupId>javax.servlet</groupId>             <artifactId>javax.servlet-api</artifactId>             <version>3.1-b05</version>         </dependency>           <!-- jackson start -->           <dependency>             <groupId>com.fasterxml.jackson.core</groupId>             <artifactId>jackson-core</artifactId>             <version>2.1.0</version>         </dependency>         <dependency>             <groupId>com.fasterxml.jackson.core</groupId>             <artifactId>jackson-databind</artifactId>             <version>2.1.0</version>         </dependency>         <dependency>             <groupId>com.fasterxml.jackson.core</groupId>             <artifactId>jackson-annotations</artifactId>             <version>2.1.0</version>         </dependency>         <!-- jackson end -->     </dependencies>     <build>         <finalName>springmvc</finalName>         <sourceDirectory>${basedir}/src</sourceDirectory>         <outputDirectory>${basedir}/WebRoot/WEB-INF/classes</outputDirectory>         <resources>             <resource>                 <directory>${basedir}/src</directory>                 <excludes>                     <exclude>**/*.java</exclude>                 </excludes>             </resource>         </resources>         <plugins>             <plugin>                 <artifactId>maven-war-plugin</artifactId>                 <configuration>                     <webappDirectory>${basedir}/WebRoot</webappDirectory>                     <warSourceDirectory>${basedir}/WebRoot</warSourceDirectory>                 </configuration>             </plugin>             <plugin>                 <artifactId>maven-compiler-plugin</artifactId>                 <configuration>                     <source>1.6</source>                     <target>1.6</target>                 </configuration>             </plugin>         </plugins>     </build> </project>

(3)spring-mvc.xml文件

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="www.springframework.org/schema/beans" xmlns:p="www.springframework.org/schema/p" xmlns:xsi="www.w3.org/2001/XMLSchema-instance"     xmlns:context="www.springframework.org/schema/context" xmlns:mvc="www.springframework.org/schema/mvc"     xmlns:util="www.springframework.org/schema/util"     xsi:schemaLocation="www.springframework.org/schema/mvc www.springframework.org/schema/mvc/spring-mvc-4.0.xsd         www.springframework.org/schema/beans www.springframework.org/schema/beans/spring-beans-4.0.xsd         www.springframework.org/schema/context www.springframework.org/schema/context/spring-context-4.0.xsd         www.springframework.org/schema/util  www.springframework.org/schema/util/spring-util-3.0.xsd         ">     <!-- 自动扫描 com.hlx 包下面的所有组件(使用了springmvc注解)-->     <context:component-scan base-package="com.hlx.*" />      <bean         class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">         <property name="messageConverters">             <util:list >                 <!-- 配置处理JSON数据 -->                 <ref bean="mappingJackson2HttpMessageConverter" />             </util:list>           </property>     </bean>    <!-- 读写JSON对象 -->   <bean id="mappingJackson2HttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">     <property name="supportedMediaTypes">      <list>       <value>text/html;charset=UTF-8</value>      </list>     </property>   </bean>    </beans>

(4)web.xml文件同前一个springmvc中的文件相同

(5)JSP页面(省略)

(6)创建src/main/java 下 bean,dao.service,controller

package com.hlx.bean;   public class User {     private String uname;     private String upass;       public String getUname() {         return uname;     }       public void setUname(String uname) {         this.uname = uname;     }       public String getUpass() {         return upass;     }       public void setUpass(String upass) {         this.upass = upass;     }      public User() {         super();     }       public User(String uname, String upass) {         super();         this.uname = uname;         this.upass = upass;     }       @Override     public String toString() {         return "User [uname=" + uname + ", upass=" + upass + "]";     }        }

package com.hlx.dao;   import org.springframework.stereotype.Repository;   import com.hlx.bean.User;   @Repository public class UserDao {       /**      * 根据用户名来查询      * @param uname      * @return      */     public User selectByName(String uname) {         if ("admin".equals(uname)) {             User user = new User("admin", "aaa");             return user;         }         return null;     }   }

package com.hlx.service;   import javax.annotation.Resource;   import org.springframework.stereotype.Service; import org.springframework.web.servlet.ModelAndView;   import com.hlx.bean.User; import com.hlx.dao.UserDao;   @Service public class UserService {       @Resource     private UserDao userDao;       /**      * 登录处理      * @param uname      * @param upass      * @return      * @throws Exception      */     public User doLogin(String uname, String upass) throws Exception {         // 判断         if (uname == null || "".equals(uname)) {             throw new Exception("用户名不能为空!");         }         if (upass == null || "".equals(upass)) {             throw new Exception("密码不能为空!");         }           User user = userDao.selectByName(uname);           if (user == null) {             throw new Exception("用户名不存在!");         }           if (!user.getUpass().equals(upass)) {             throw new Exception("密码不正确!");         }           return user;       } }

package com.hlx.controller;   import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest;   import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.bind.support.SessionStatus;     import com.hlx.bean.User; import com.hlx.service.UserService;   @Controller @SessionAttributes("user") //保存user对象 public class UserController {       //业务层     @Resource     private UserService userService;          @RequestMapping("login")     public String toLoginPage(){         return "jsp/login.jsp";     }     /**      *       * @param uname 表单传过来的参数      * @param upass       * @param request  请求对象      * @return      */     @RequestMapping(value="dologin",method=RequestMethod.POST)     public String doLogin(@RequestParam String uname,@RequestParam String upass,HttpServletRequest request,ModelMap map){         try {             //调用方法          User user=userService.doLogin(uname,upass);                    //存入user          map.put("user", user);          ///                   } catch (Exception e) {             // TODO: handle exception             request.setAttribute("error", e.getMessage());  //提示错误消息             return "jsp/login.jsp";  //返回登录页面         }         return "jsp/success.jsp";     }          /**      * 退出      * @return      */     @RequestMapping("dologout")     public String doLogout(SessionStatus status){         //清空session         status.setComplete();         //返回登录页面         return "jsp/login.jsp";     }      }

效果:

package com.hlx.controller;   import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody;   import com.hlx.bean.User;   @Controller public class JSONController {       @ResponseBody     @RequestMapping("/getJson")     public User getUserinfo(){         User user = new User("mike", "123456");         return user;     } }

效果:

package com.hlx.controller;   import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody;   import com.hlx.bean.User;   @Controller public class PathVariableControler {          @ResponseBody     @RequestMapping("/pathvariable/{uname}")     public User test1(@PathVariable String uname){         User user = new User();         user.setUname("john");         return user;     }     @ResponseBody     @RequestMapping("/pathvariable2/{intval}")     public User test1(@PathVariable Integer intval){         User user = new User();         user.setUname(intval + "");         return user;     }   }

效果:

注意:这里是数字

注意:这里只能是数字,不能字符串,否则找不到页面!

总结:

应用了四大注解类Component、Controller、Service、Repository;掌握PathVariable,RequestParam注解类

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自由互联。

本文共计2128个文字,预计阅读时间需要9分钟。

如何通过SpringMVC注解轻松实现用户登录功能?

原文示例:本文实例为大家分享了SpringMVC使用注解实现登录的具体代码,供大家参考。具体内容如下:

一、使用Component、Controller四大注解:① @Component:通用注解② @Controller:控制层注解③ @Service:业务层注解④ @Repository:数据访问层注解

二、@Component注解:@Component是通用注解,用于标注类,Spring会自动扫描并注册到Bean容器中。

三、@Controller注解:@Controller注解用于标注控制层,是SpringMVC中的核心注解,用于处理HTTP请求。

四、@Service注解:@Service注解用于标注业务层,用于封装业务逻辑。

五、@Repository注解:@Repository注解用于标注数据访问层,用于操作数据库。

本文实例为大家分享了SpringMVC使用注解实现登录的具体代码,供大家参考,具体内容如下

一、使用Component\Controller\Service\Repository四大注解类:

  • @Component 是通用标注
  • @Controller 标注 web 控制器
  • @Service 标注 Servicec 层的服务
  • @Respository 标注 DAO层的数据访问

这些注解都是类级别的,可以不带任何参数,也可以带一个参数,代表bean名字,在进行注入的时候就可以通过名字进行注入了。

二、@Resource和@Autowired注解的异同

  • @Autowired默认按类型装配,默认情况下必须要求依赖对象必须存在,如果要允许null值,可以设置它的required属性为false

例如:@Autowired(required=false),如果我们想使用名称装配可以结合@Qualifier注解进行使用

  • @Resource,默认安装名称进行装配,名称可以通过name属性进行指定,如果没有指定name属性,当注解写在字段上时,默认取字段名进行安装名称查找 ,如果注解写在setter方法上默认取属性名进行装配 。当找不到与名称匹配的bean时才按照类型进行装配。但是需要注意的是,如果name属性一旦指定,就只会按照名称进行装配。

三、其他注解类

(1) PathVariable注解类

@RequestMapping注解中使用占位符的情况下,需要使用@PathVariable注解指定占位符参数

(2) RequestParam注解类

表单提交数据时,可以通过这个注解来解决request.getParameter("uname")

(3) CookieValue注解类

如果要保存字符串数据,可以使用这个注解

(4) SessionAttributes注解类

如果希望在多个请求之间公用某个模型属性数据,则可以在控制器类标注一个@SessionAttributes,SpringMVC会将模型中对应的属性暂存到HttpSerssion中除了SessionAttributes,还可以直接用原生态的request.getSession()来处理

(5) ResponseBody注解类

如何通过SpringMVC注解轻松实现用户登录功能?

用于将Controller的方法返回的对象,通过适当的HttpMessageConverter(转换器)转换为指定格式后,写入到Response对象的body数据区; 返回如json、xml等时使用

(6)RequestHeader注解类

@RequestHeader注解,可以把Request请求header部分的值绑定到方法的参数上

四、应用注解来实现登录

(1)、创建工程如下:

(2)、配置文件pom.xml(主要是修改:dependencies的内容)

<project xmlns="maven.apache.org/POM/4.0.0" xmlns:xsi="www.w3.org/2001/XMLSchema-instance"     xsi:schemaLocation="maven.apache.org/POM/4.0.0 maven.apache.org/xsd/maven-4.0.0.xsd">     <modelVersion>4.0.0</modelVersion>     <groupId>springmvc</groupId>     <artifactId>springmvc</artifactId>     <version>0.0.1-SNAPSHOT</version>     <packaging>war</packaging>     <name />     <description />     <properties>         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>     </properties>     <dependencies>           <dependency>             <groupId>org.springframework</groupId>             <artifactId>spring-webmvc</artifactId>             <version>4.1.6.RELEASE</version>         </dependency>           <dependency>             <groupId>org.springframework</groupId>             <artifactId>spring-tx</artifactId>             <version>4.1.6.RELEASE</version>         </dependency>         <dependency>             <groupId>javax.servlet</groupId>             <artifactId>javax.servlet-api</artifactId>             <version>3.1-b05</version>         </dependency>           <!-- jackson start -->           <dependency>             <groupId>com.fasterxml.jackson.core</groupId>             <artifactId>jackson-core</artifactId>             <version>2.1.0</version>         </dependency>         <dependency>             <groupId>com.fasterxml.jackson.core</groupId>             <artifactId>jackson-databind</artifactId>             <version>2.1.0</version>         </dependency>         <dependency>             <groupId>com.fasterxml.jackson.core</groupId>             <artifactId>jackson-annotations</artifactId>             <version>2.1.0</version>         </dependency>         <!-- jackson end -->     </dependencies>     <build>         <finalName>springmvc</finalName>         <sourceDirectory>${basedir}/src</sourceDirectory>         <outputDirectory>${basedir}/WebRoot/WEB-INF/classes</outputDirectory>         <resources>             <resource>                 <directory>${basedir}/src</directory>                 <excludes>                     <exclude>**/*.java</exclude>                 </excludes>             </resource>         </resources>         <plugins>             <plugin>                 <artifactId>maven-war-plugin</artifactId>                 <configuration>                     <webappDirectory>${basedir}/WebRoot</webappDirectory>                     <warSourceDirectory>${basedir}/WebRoot</warSourceDirectory>                 </configuration>             </plugin>             <plugin>                 <artifactId>maven-compiler-plugin</artifactId>                 <configuration>                     <source>1.6</source>                     <target>1.6</target>                 </configuration>             </plugin>         </plugins>     </build> </project>

(3)spring-mvc.xml文件

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="www.springframework.org/schema/beans" xmlns:p="www.springframework.org/schema/p" xmlns:xsi="www.w3.org/2001/XMLSchema-instance"     xmlns:context="www.springframework.org/schema/context" xmlns:mvc="www.springframework.org/schema/mvc"     xmlns:util="www.springframework.org/schema/util"     xsi:schemaLocation="www.springframework.org/schema/mvc www.springframework.org/schema/mvc/spring-mvc-4.0.xsd         www.springframework.org/schema/beans www.springframework.org/schema/beans/spring-beans-4.0.xsd         www.springframework.org/schema/context www.springframework.org/schema/context/spring-context-4.0.xsd         www.springframework.org/schema/util  www.springframework.org/schema/util/spring-util-3.0.xsd         ">     <!-- 自动扫描 com.hlx 包下面的所有组件(使用了springmvc注解)-->     <context:component-scan base-package="com.hlx.*" />      <bean         class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">         <property name="messageConverters">             <util:list >                 <!-- 配置处理JSON数据 -->                 <ref bean="mappingJackson2HttpMessageConverter" />             </util:list>           </property>     </bean>    <!-- 读写JSON对象 -->   <bean id="mappingJackson2HttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">     <property name="supportedMediaTypes">      <list>       <value>text/html;charset=UTF-8</value>      </list>     </property>   </bean>    </beans>

(4)web.xml文件同前一个springmvc中的文件相同

(5)JSP页面(省略)

(6)创建src/main/java 下 bean,dao.service,controller

package com.hlx.bean;   public class User {     private String uname;     private String upass;       public String getUname() {         return uname;     }       public void setUname(String uname) {         this.uname = uname;     }       public String getUpass() {         return upass;     }       public void setUpass(String upass) {         this.upass = upass;     }      public User() {         super();     }       public User(String uname, String upass) {         super();         this.uname = uname;         this.upass = upass;     }       @Override     public String toString() {         return "User [uname=" + uname + ", upass=" + upass + "]";     }        }

package com.hlx.dao;   import org.springframework.stereotype.Repository;   import com.hlx.bean.User;   @Repository public class UserDao {       /**      * 根据用户名来查询      * @param uname      * @return      */     public User selectByName(String uname) {         if ("admin".equals(uname)) {             User user = new User("admin", "aaa");             return user;         }         return null;     }   }

package com.hlx.service;   import javax.annotation.Resource;   import org.springframework.stereotype.Service; import org.springframework.web.servlet.ModelAndView;   import com.hlx.bean.User; import com.hlx.dao.UserDao;   @Service public class UserService {       @Resource     private UserDao userDao;       /**      * 登录处理      * @param uname      * @param upass      * @return      * @throws Exception      */     public User doLogin(String uname, String upass) throws Exception {         // 判断         if (uname == null || "".equals(uname)) {             throw new Exception("用户名不能为空!");         }         if (upass == null || "".equals(upass)) {             throw new Exception("密码不能为空!");         }           User user = userDao.selectByName(uname);           if (user == null) {             throw new Exception("用户名不存在!");         }           if (!user.getUpass().equals(upass)) {             throw new Exception("密码不正确!");         }           return user;       } }

package com.hlx.controller;   import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest;   import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.bind.support.SessionStatus;     import com.hlx.bean.User; import com.hlx.service.UserService;   @Controller @SessionAttributes("user") //保存user对象 public class UserController {       //业务层     @Resource     private UserService userService;          @RequestMapping("login")     public String toLoginPage(){         return "jsp/login.jsp";     }     /**      *       * @param uname 表单传过来的参数      * @param upass       * @param request  请求对象      * @return      */     @RequestMapping(value="dologin",method=RequestMethod.POST)     public String doLogin(@RequestParam String uname,@RequestParam String upass,HttpServletRequest request,ModelMap map){         try {             //调用方法          User user=userService.doLogin(uname,upass);                    //存入user          map.put("user", user);          ///                   } catch (Exception e) {             // TODO: handle exception             request.setAttribute("error", e.getMessage());  //提示错误消息             return "jsp/login.jsp";  //返回登录页面         }         return "jsp/success.jsp";     }          /**      * 退出      * @return      */     @RequestMapping("dologout")     public String doLogout(SessionStatus status){         //清空session         status.setComplete();         //返回登录页面         return "jsp/login.jsp";     }      }

效果:

package com.hlx.controller;   import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody;   import com.hlx.bean.User;   @Controller public class JSONController {       @ResponseBody     @RequestMapping("/getJson")     public User getUserinfo(){         User user = new User("mike", "123456");         return user;     } }

效果:

package com.hlx.controller;   import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody;   import com.hlx.bean.User;   @Controller public class PathVariableControler {          @ResponseBody     @RequestMapping("/pathvariable/{uname}")     public User test1(@PathVariable String uname){         User user = new User();         user.setUname("john");         return user;     }     @ResponseBody     @RequestMapping("/pathvariable2/{intval}")     public User test1(@PathVariable Integer intval){         User user = new User();         user.setUname(intval + "");         return user;     }   }

效果:

注意:这里是数字

注意:这里只能是数字,不能字符串,否则找不到页面!

总结:

应用了四大注解类Component、Controller、Service、Repository;掌握PathVariable,RequestParam注解类

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自由互联。