Spring4 + SpringMVC + MyBatis logon registration details, spring4mybatis

Source: Internet
Author: User

Spring4 + SpringMVC + MyBatis logon registration details, spring4mybatis

Project Structure:

Package com. mstf. controller; import org. springframework. stereotype. controller; import org. springframework. web. bind. annotation. pathVariable; import org. springframework. web. bind. annotation. requestMapping;/*** dynamic page Jump controller */@ Controllerpublic class FormController {@ RequestMapping (value = "/{formName}") public String loginForm (@ PathVariable String formName) {// return formName ;}}

  

Package com. mstf. controller; import javax. servlet. http. httpSession; import org. springframework. beans. factory. annotation. autowired; import org. springframework. beans. factory. annotation. qualifier; import org. springframework. stereotype. controller; import org. springframework. web. bind. annotation. modelAttribute; import org. springframework. web. bind. annotation. requestMapping; import org. springframework. web. servlet. ModelAndView; import org. springframework. web. servlet. view. redirectView; import com. mstf. domain. user; import com. mstf. service. userService;/*** process user request controller */@ Controllerpublic class UserController {/*** automatically injects UserService */@ Autowired @ Qualifier ("userService") private UserService userService; /*** process/login requests */@ RequestMapping (value = "/login") public ModelAndView login (String username, String password, Mode LAndView mv, HttpSession session) {// find a User based on the login name and password, and determine the user login user User = userService. login (username, password); if (user! = Null) {// login successful. Set the user object to the domain session in the range of HttpSession. setAttribute ("user", user); // forward to the main request, forwarding address mv. setView (new RedirectView ("/Demo4/index");} else {// Logon Failed, set the failure prompt, and jump to the logon page mv. addObject ("message", "the logon name or password is incorrect. enter a new one! "); Mv. setViewName ("loginForm");} return mv;}/*** process/regeist requests */@ RequestMapping (value = "/regeist ") public String regeist (@ ModelAttribute ("user") User user) {userService. regeist (user); return "success ";}}

  

package com.mstf.domain;import java.io.Serializable;public class User implements Serializable {private static final long serialVersionUID = 1L;private int id;private String username;private String password;private String phone;private String email;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public User(int id, String username, String password, String phone, String email) {super();this.id = id;this.username = username;this.password = password;this.phone = phone;this.email = email;}public User() {super();}@Overridepublic String toString() {return "User [id=" + id + ", username=" + username + ", password=" + password + ", phone=" + phone + ", email="+ email + "]";}}

  

Package com. mstf. mapper; import org. apache. ibatis. annotations. select; import com. mstf. domain. user; import org. apache. ibatis. annotations. insert; import org. apache. ibatis. annotations. param; /*** UserMapper interface */public interface UserMapper {/*** query the user name and password ** @ param String * username * @ param String * password * @ return user object, null */@ Select ("select * from loginuser where username = # {username} and password = # {password}") User findWithLoginnameAndPassword (@ Param ("username") not found ") string username, @ Param ("password") String password);/*** register */@ Insert ("insert into loginuser (username, 'Password', phone, email) values (# {username}, # {password}, # {phone}, # {email}) ") int regeist (@ Param (" username ") String username, @ Param ("password") String password, @ Param ("phone") String phone, @ Param ("email") String email );}

  

Package com. mstf. service; import com. mstf. domain. user; /*** User service layer interface */public interface UserService {/*** determine User logon ** @ param String * username * @ param String * password * @ return User object, null */User login (String username, String password) not found;/*** int */int regeist (User user User) returned by User registration );}

  

Package com. mstf. service. impl; import org. springframework. beans. factory. annotation. autowired; import org. springframework. stereotype. service; import org. springframework. transaction. annotation. isolation; import org. springframework. transaction. annotation. propagation; import org. springframework. transaction. annotation. transactional; import com. mstf. domain. user; import com. mstf. mapper. userMapper; import com. mstf. service. userService;/*** User Service layer interface implementation class @ Service ("userService") is used to comment the current class into a Spring bean, the name is userService */@ Transactional (propagation = Propagation. REQUIRED, isolation = Isolation. DEFAULT) @ Service ("userService") public class UserServiceImpl implements UserService {/*** automatically injects UserMapper */@ Autowiredprivate UserMapper userMapper; /*** implement the login method of the UserService interface ** @ see {UserService} */@ Transactional (readOnly = true) @ Overridepublic User login (String username, String password) {return userMapper. findWithLoginnameAndPassword (username, password);}/*** UserService interface regeist method implementation ** @ see {UserService} */@ Overridepublic int regeist (User user User) {System. out. println (user); return userMapper. regeist (user. getUsername (), user. getPassword (), user. getPhone (), user. getEmail ());}}

  

dataSource.driverClass=com.mysql.jdbc.DriverdataSource.jdbcUrl=jdbc:mysql://127.0.0.1:3306/demo4dataSource.user=rootdataSource.password=rootdataSource.maxPoolSize=20dataSource.maxIdleTime = 1000dataSource.minPoolSize=6dataSource.initialPoolSize=5

  

# Global logging configurationlog4j.rootLogger=ERROR, stdout# MyBatis logging configuration...log4j.logger.org.fkit.mapper.UserMapper=DEBUGlog4j.logger.org.fkit.mapper.BookMapper=DEBUG# Console output...log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

Index. jsp

<% @ Page language = "java" import = "java. util. * "pageEncoding =" UTF-8 "%> <% String path = request. getContextPath (); String basePath = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/"; %> <! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN"> 

LoginForm. JSP

<% @ Page language = "java" contentType = "text/html; charset = UTF-8" pageEncoding = "UTF-8" %> <! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd"> 

REGEISTER. JSP

<% @ Page language = "java" import = "java. util. * "pageEncoding =" UTF-8 "%> <% String path = request. getContextPath (); String basePath = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/"; %> <! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN"> 

SUCCESS. JSP

<% @ Page language = "java" import = "java. util. * "pageEncoding =" UTF-8 "%> <% String path = request. getContextPath (); String basePath = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/"; %> <! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN"> 

ApplicationContext

<? Xml version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: mybatis = "http://mybatis.org/schema/mybatis-spring" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: p = "http://www.springframework.org/schema/p" xmlns: context = "http://www.springframework.org/schema/context" xmlns: mvc = "http://www.springframework.org/schema/mvc" xmlns: tx = "http://www.springframework.org/schema/tx" xsi: schemaLocatio Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd http://www.springframework.org/schema/tx G/schema/tx/spring-tx-4.1.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd "> <! -- Mybatis: scan will. mstf. all interfaces in the ER er package are configured as mapper, and then the mapper class can be automatically introduced --> <mybatis: scan base-package = "com. mstf. mapper "/> <! -- Scan org. if the java file under the fkit package contains Spring-related annotation classes, register these classes as Spring beans --> <context: component-scan base-package = "com. mstf "/> <! -- Use propertyoverridemo-er to load data source parameters --> <context: property-override location = "classpath: db. properties"/> <! -- Configure the c3p0 data source --> <bean id = "dataSource" class = "com. mchange. v2.c3p0. ComboPooledDataSource"/> <! -- Configure SqlSessionFactory, org. mybatis. spring. sqlSessionFactoryBean is a bean developed by the Mybatis community to integrate Spring --> <bean id = "sqlSessionFactory" class = "org. mybatis. spring. sqlSessionFactoryBean "p: dataSource-ref =" dataSource "/> <! -- JDBC Transaction Manager --> <bean id = "transactionManager" class = "org. springframework. jdbc. datasource. cetcetransactionmanager" p: dataSource-ref = "dataSource"/> <! -- Enable transaction Management in annotation mode --> <tx: annotation-driven transaction-manager = "transactionManager"/> </beans>

Springmvc-config

<? Xml version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: mvc = "http://www.springframework.org/schema/mvc" xmlns: context = "http://www.springframework.org/schema/context" xsi: schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/mvc htt P: // www.springframework.org/schema/mvc/spring-mvc-4.2.xsd http://www.springframework.org/schema/context Co., http://www.springframework.org/schema/context/spring-context-4.2.xsd. "> <! -- Automatically scans this package. SpringMVC registers the class with the @ controller annotation under the package as the controller of Spring --> <context: component-scan base-package = "com. mstf. controller "/> <! -- Set the default configuration scheme --> <mvc: annotation-driven/> <! -- Use the default Servlet to respond to static files --> <mvc: default-servlet-handler/> <! -- View parser --> <bean id = "viewResolver" class = "org. springframework. web. servlet. view. InternalResourceViewResolver"> <! -- Prefix --> <property name = "prefix"> <value>/WEB-INF/jsp/</value> </property> <! -- Suffix --> <property name = "suffix"> <value>. jsp </value> </property> </bean> </beans>

WEB. XML

<? Xml version = "1.0" encoding = "UTF-8"?> <Web-app xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://xmlns.jcp.org/xml/ns/javaee" xsi: schemaLocation = "http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id = "WebApp_ID" version = "3.1"> <! -- Configure the spring core listener, which defaults to/WEB-INF/applicationContext. xml is used as the configuration file --> <listener-class> org. springframework. web. context. contextLoaderListener </listener-class> </listener> <! -- ContextConfigLocation parameter is used to specify the Spring configuration file --> <context-param> <param-name> contextConfigLocation </param-name> <param-value>/WEB-INF/applicationContext *. xml </param-value> </context-param> <! -- Define the front-end controller of Spring MVC --> <servlet-name> springmvc </servlet-name> <servlet-class> org. springframework. web. servlet. dispatcherServlet </servlet-class> <init-param> <param-name> contextConfigLocation </param-name> <param-value>/WEB-INF/springmvc-config.xml </param-value> </init-param> <load-on-startup> 1 </load-on-startup> </servlet> <! -- Let the front-end controller of Spring MVC intercept all requests --> <servlet-mapping> <servlet-name> springmvc </servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <! -- Encoding filter --> <filter-name> characterEncodingFilter </filter-name> <filter-class> org. springframework. web. filter. characterEncodingFilter </filter-class> <init-param> <param-name> encoding </param-name> <param-value> UTF-8 </param-value> </init- param> </filter> <filter-mapping> <filter-name> characterEncodingFilter </filter-name> <url-pattern>/* </url-pattern> </filter- mapping> </web-app>

  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.