In the near future, the company will develop new projects and use the struts2+mybatis+spring framework. So after learning it, I will post it on my blog, hoping to help you!
Mainly realizes user addition, deletion, modification and search operations
1. Import the corresponding jar package
2. Configuring web.xml mainly configures struts2 and spring
The content of the web.xml file is as follows:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- Loading spring configuration file --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Configure the location of spring configuration file loading --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:beans.xml</param-value> </context-param> <!-- Configure struts2 --> <filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
3. Configure spring configuration files, mainly including configuring data sources, transactions, mybaits, etc.
The beans.xml configuration file is as follows:
<?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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- Configure beans with comments --> <context:annotation-config /> <!-- Configure the package to be scanned --> <context:component-scan base-package="com.pdsu.edu"></context:component-scan> <!-- proxy-target-class="true" Force the use of cglib proxy If false, spring will automatically select --> <aop:aspectj-autoproxy proxy-target-class="true"/> <!-- Database configuration file location--> <context:property-placeholder location="classpath:jdbc.properties" /> <!-- Configure dbcp data source--> <bean id="dataSource" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <!-- Minimum waiting time in the queue--> <property name="minIdle" value="${jdbc.minIdle}"></property> <!-- Maximum waiting time in milliseconds--> <property name="maxWait" value="${jdbc.maxWait}"></property> <!-- Maximum active number--> <property name="maxActive" value="${jdbc.maxActive}"></property> <property name="initialSize" value="${jdbc.initialSize}"></property> </bean> <!-- Configure mybitasSqlSessionFactoryBean --> <bean id="sqlSessionFactory"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:mybatis.xml"></property> </bean> <!-- Configure SqlSessionTemplate --> <bean id="sqlSessionTemplate"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean> <!-- Transaction Configuration--> <bean id="transactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- Configure transactions using annotation annotation--> <tx:annotation-driven transaction-manager="transactionManager"/> </beans> 4. JDBC configuration file details
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/operationLog jdbc.username=root jdbc.password= jdbc.maxActive = 2 jdbc.maxIdle =5 jdbc.minIdle=1 jdbc.initialSize =3 jdbc.maxWait =3000
5. Configure the mybatis main configuration file:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <typeAliases> <typeAlias alias="user" type="com.pdsu.edu.domain.User"/> </typeAliases> <mappers> <mapper resource="com/pdsu/edu/domain/sqlMappers/user.xml" /> </mappers> </configuration>
6. Configure user.xml file
<?xml version="1.0" encoding="utf-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.pdsu.edu.domain.User"> <resultMap type="com.pdsu.edu.domain.User" id="userResult"> <result property="id" column="id" jdbcType="INTEGER" javaType="java.lang.Integer" /> <result property="username" column="username" /> <result property="password" column="password" /> </resultMap> <select id="userLogin" parameterType="user" resultMap="userResult"> select * from user where username=#{username} and password=#{password} </select> <select id="selectAllUser" resultMap="userResult"> select * from user </select> <select id="findUserById" parameterType="int" resultMap="userResult"> select * from user where id=#{id} </select> <insert id="insertUser" parameterType="user"> <![CDATA[ insert into user(username,password) values(#{username},#{password}) ]]> </insert> <update id="updateUser" parameterType="user"> update user set username=#{username},password=#{password} where id=#{id} </update> <delete id="deleteUser" parameterType="int"> delete from user where id=#{id} </delete> </mapper> 7. How to write User entity
public class User implements Serializable { private static final long serialVersionUID = -4415990281535582814L; private Integer id; private String username; private String password; public Integer getId() { return id; } public void setId(Integer 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; } @Override public String toString() { return "User [id=" + id + ", password=" + password + ", username=" + username + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; User other = (User) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } } 8. How to write UserDao
public interface UserDao { public abstract void insertUser(User user); public abstract void updateUser(User user); public abstract void deleteUser(Integer userId); public abstract User findUserByid(Integer userId); public abstract List<User> findAll(); public abstract User userLogin(User user); } 9. Implementation of UserDao
@Repository public class UserDaoImpl implements UserDao { private final String INSERT_USER = "insertUser"; private final String UPDATE_USER = "updateUser"; private final String DELETE_USER = "deleteUser"; private final String FIND_USER_BYID = "findUserById"; private final String SELECT_ALL_USER = "selectAllUser"; private final String USER_LOGIN = "userLogin"; @Autowired private SqlSessionTemplate sqlSessionTemplate; public void insertUser(User user) { sqlSessionTemplate.insert(INSERT_USER, user); } public void updateUser(User user) { sqlSessionTemplate.update(UPDATE_USER, user); } public void deleteUser(Integer userId) { sqlSessionTemplate.delete(DELETE_USER, userId); } public User findUserByid(Integer userId) { return sqlSessionTemplate.selectOne(FIND_USER_BYID, userId); } public List<User> findAll() { return sqlSessionTemplate.selectList(SELECT_ALL_USER); } public User userLogin(User user) { return sqlSessionTemplate.selectOne(USER_LOGIN, user); } } 10. UserService interface
public interface UserService { // Add user public abstract void addUser(User user); public abstract void updateUser(User user); public abstract void deleteUser(Integer userId); public abstract User findUserById(Integer userId); public abstract List<User> findAllUser(); public abstract User login(User user); } 11. Implementation of UserService interface
@Service @Transactional public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; // Add user public void addUser(User user) { userDao.insertUser(user); } // Update user public void updateUser(User user) { userDao.updateUser(user); } public void deleteUser(Integer userId) { userDao.deleteUser(userId); } public User findUserById(Integer userId) { return userDao.findUserByid(userId); } public List<User> findAllUser() { return userDao.findAll(); } public User login(User user) { return userDao.userLogin(user); } } 12. Configure Struts2
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <constant name="struts.i18n.encoding" value="UTF-8"/> <!-- Specify the default encoding set, which is used on the setCharacterEncoding() and freemarker of HttpServletRequest, and the output of vilocity--> <constant name="struts.configuration.xmlreload" value="true"/> <!-- Whether it is automatically loaded when the struts configuration file is modified--> <constant name="struts.devMode" value="true"/> <!-- Print detailed error information in development mode--> <constant name="struts.ui.theme" value="xhtml"/> <package name="user" namespace="/user" extends="struts-default"> <action name="user_*" method="{1}"> <result name="success" type="redirectAction">user_queryAllUser.action</result> <result name="input">/index.jsp</result> <result name="userList">/userList.jsp</result> <result name="addUser">/userAdd.jsp</result> <result name="updateUser">/userUpdate.jsp</result> </action> </package> </struts> 13. UserAction specific implementation
@Controller @Scope("prototype") public class UserAction extends ActionSupport { @Autowired private UserService userService; private User user; private List<User> userList; public String execute() throws Exception { return null; } public String login() { if (user != null) { User user2 = userService.login(user); if (user2 != null) { return SUCCESS; } } this.addFieldError("user.username", "Error in username or password!"); return INPUT; } public String addUI() { return "addUser"; } public String updateUI() { user = userService.findUserById(user.getId()); return "updateUser"; } public String add() { userService.addUser(user); return SUCCESS; } public String delete() { userService.deleteUser(user.getId()); return SUCCESS; } public String update() { userService.updateUser(user); return SUCCESS; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String queryAllUser() { userList = userService.findAllUser(); return "userList"; } public List<User> getUserList() { return userList; } public void setUserList(List<User> userList) { this.userList = userList; } } 14. Implementation of login page
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>User Login</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <s:head/> </head> <body> <center> <h1>User Login</h1> <s:a action="user_addUI" namespace="/user">Add a new user</s:a> <s:form action="user_login" namespace="/user" method="post"> <s:textfield label="username" name="user.username"></s:textfield> <s:password label="password" name="user.password"></s:password> <s:submit value="login"></s:submit> </s:form> </center> </body> </html>
15. Add a page
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Add a new user</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> </head> <body> <center> <h1>Add a new user</h1> <s:form action="user_add" namespace="/user" method="post"> <s:textfield label="username" name="user.username"></s:textfield> <s:password label="password" name="user.password"></s:password> <s:submit value="submit"></s:submit> </s:form> </center> </body> </html>
16. Modify the page
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Modify user</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> </head> <body> <center> <h1>Modify user</h1> <s:form action="user_update" namespace="/user" method="post"> <s:hidden name="user.id"></s:hidden> <s:textfield label="username" name="user.username"></s:textfield> <s:password label="password" name="user.password"></s:password> <s:submit value="submit"></s:submit> </s:form> </center> </body> </html>
17. List page
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>User List</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> </head> <body> <center> <h2>User List</h2> <h3><s:a action="user_addUI" namespace="/user">Add a new user</s:a> </h3> <table> <tr> <th>User ID</th> <th>User name</th> <th>User Password</th> <th>Operation</th> </tr> <s:iterator value="userList"> <tr> <td><s:property value="id"/> </td> <td><s:property value="username"/> </td> <td><s:property value="password"/> </td> <td><s:a action="user_updateUI" namespace="/user"><s:param name="user.id">${id}</s:param>Modify</s:a> <s:a action="user_delete" namespace="/user"><s:param name="user.id">${id}</s:param>Delete</s:a></td> </tr> </s:iterator> </table> </center> </body> </html>The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.