赞
踩
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>hotel</display-name> <welcome-file-list> <welcome-file>userlogin.jsp</welcome-file> </welcome-file-list> <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> <filter> <filter-name>encoding</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>encoding</filter-name> <url-pattern>*</url-pattern> </filter-mapping> <servlet> <servlet-name>hotel</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>hotel</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
applicationContext.xml文件:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <!-- 开启扫描 --> <context:component-scan base-package="com.serviceImpl"></context:component-scan> <!-- 读取db.properties --> <context:property-placeholder location="classpath:db.properties"/> <!-- 配置数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"> <!-- 数据库驱动 --> <property name="driverClassName" value="${jdbc.driver}"></property> <!-- 连接数据库url --> <property name="url" value="${jdbc.url}"/> <!-- 连接数据库的用户名密码 --> <property name="username" value="${jdbc.username}"></property> <property name="password" value="${jdbc.password}"></property> <!-- 最大连接数 --> <property name="maxTotal" value="${jdbc.maxTotal}"></property> <!-- 最大空闲连接数 --> <property name="maxIdle" value="${jdbc.maxIdle}"></property> <!-- 初始化连接数 --> <property name="initialSize" value="${jdbc.initialSize}"></property> </bean> <!-- 事务管理器,依赖于数据源 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 开启事务注解,注册事务管理驱动 --> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- 配置MyBatis工厂 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 注入数据源 --> <property name="dataSource" ref="dataSource"></property> <!-- 指定核心配置文件的位置 --> <property name="configLocation" value="classpath:mybatis-config.xml"></property> </bean> <!-- Mapper代理开发(基于MapperScannerConfigurer) --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.mapper"></property> </bean> </beans>
<?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>
<package name="com.po" />
</typeAliases>
</configuration>
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/hotel?characterEncoding=utf-8&serverTimezone=UTC&&useAffectedRows=true
jdbc.username=root
jdbc.password=241070
jdbc.maxTotal=30
jdbc.maxIdle=10
jdbc.initialSize=5
log4j.properties文件信息:
# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.itheima=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
<?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" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <!-- 配置包扫描器,扫描@Controller注解的类 --> <context:component-scan base-package="com.controller" /> <!-- 加载注解驱动 --> <mvc:annotation-driven /> <!-- 配置视图解析器 --> <bean class= "org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> </beans>
记住一个关系:mybatis.xml;和其他两个文本文件是在applicationContext.xml文件里面配置的,而applicationContext.xml和mvc.xml是web.xml里面配置的
<%@ 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"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>酒店信息管理系统登录</title> </head> <body> <h2 align="center"><font color=blue>酒店管理系统登录页面</font></h2> <form action="login" method="post"> <table align="center" border="1"> <tr> <td>用户名:</td> <td><input type="text" name="username"></td> </tr> <tr> <td>密 码:</td> <td><input type="password" name="password"></td> </tr> <tr> <td><input type="submit" value="登录" name="login"></td> <td><input type="reset" value="重置" name="reset"></td> </tr> </table> <p align="center"><a href="preregister" color=blue size="20">注册用户</a></p> </form> </body> </html>
<%@ 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"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>酒店信息管理系统首页</title> </head> <body> <h2 align="center"><font color=blue>酒店信息管理系统首页</font></h2> <p align="right"><a href="userinfo?username=${sessionScope.username}" color="blue" size="20" >当前用户信息</a></p> <p align="right"><a href="logout" color="blue" size="20">注销</a></p> <table align="center" border="1" style="width: 40%; max-width: 50%;border-spacing:10px;"> <tr> <td align="center"><a href="roomlist">客房管理</a></td> </tr> <tr> <td align="center"><a href="customerlist">入住客户管理</a></td> </tr> <tr> <td align="center"><a href="stafflist">人事管理</a></td> </tr> <tr> <td align="center"><a href="memberlist">会员管理</a></td> </tr> <tr> <td align="center"><a href="userlist">系统用户管理</a></td> </tr> </table> </body> </html>
package com.service;
import java.util.List;
import com.po.User;
public interface UserService {
List<User> findAllUser();
List<User> findUserByName(String name);
User findUserByid(String id);
int addUser(User user);
void deleteUsers(String[] idArray);
int updateUser(User user);
}
package com.serviceImpl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.mapper.UserMapper; import com.po.User; import com.service.UserService; @Service @Transactional public class userServiceImpl implements UserService{ @Autowired private UserMapper userMapper; public List<User> findAllUser() { return userMapper.findAllUser(); } public List<User> findUserByName(String username) { return userMapper.findUserByName(username); } public int addUser(User user) { return userMapper.addUser(user); } public void deleteUsers(String[] nameArray) { for(int i=0;i<nameArray.length;i++) { userMapper.deleteUsers(nameArray[i]); } } public int updateUser(User user) { return userMapper.updateUser(user); } public User findUserByid(String id) { return userMapper.findUserByid(id); } }
package com.po; public class User { private String username; private String password; private String sex; private String tel; private String address; private String number; private String tips; 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 getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getTips() { return tips; } public void setTips(String tips) { this.tips = tips; } }
package com.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import com.po.User; public interface UserMapper { List<User> findAllUser(); List<User> findUserByName(@Param("username")String username); User findUserByid(String username); int addUser(User user); int deleteUsers(@Param("username")String idArray); int updateUser(User user); }
<?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.mapper.UserMapper"> <!-- 模糊查询 --> <select id="findUserByName" parameterType="String" resultType="User"> <bind name="username" value="'%'+username+'%'" /> select * from user <where> <if test="username!=null and username!=''"> and username like #{username} </if> </where> </select> <select id="findUserByid" parameterType="String" resultType="User"> select * from user where username=#{username}; </select> <select id="findAllUser" resultType="User"> select * from user; </select> <insert id="addUser" parameterType="User"> insert into user(username,password,sex,tel,address,number,tips) values(#{username},#{password},#{sex},#{tel},#{address},#{number},#{tips}); </insert> <delete id="deleteUsers" parameterType="String"> delete from user where username=${username}; </delete> <update id="updateUser" parameterType="User"> update user <set> <if test="username!=null and username!=''"> username=#{username}, </if> <if test="password!=null and password!=''"> password=#{password}, </if> <if test="sex!=null and sex!=''"> sex=#{sex}, </if> <if test="tel!=null"> tel=#{tel}, </if> <if test="address!=null"> address=#{address}, </if> <if test="number!=null"> number=#{number}, </if> <if test="tips!=null"> tips=#{tips}, </if> </set> where username=#{username} </update> </mapper>
package com.controller; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import com.po.User; import com.service.UserService; @Controller public class userController { @Autowired private UserService userService; @RequestMapping("/preregister") public String preregister() { return "register/userRegister"; } @RequestMapping("/userregister") public void register(User user,HttpServletRequest request,HttpServletResponse response ) throws IOException { PrintWriter out = null; response.setContentType("text/html; charset=UTF-8"); //转码 user.setUsername(request.getParameter("username")); String password_01=request.getParameter("password_01"); String password_02=request.getParameter("password_02"); if(password_01.equals(password_02)&&password_01!=null&&!password_01.equals("")) { user.setPassword(password_01); }else { try { out = response.getWriter(); out.flush(); out.println("<script>"); out.println("alert('前后密码不一致!');"); out.println("history.back();"); out.println("</script>"); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); }finally { out.close(); } } user.setSex(request.getParameter("sex")); user.setTel(request.getParameter("tel")); user.setAddress(request.getParameter("address")); user.setNumber(request.getParameter("number")); user.setTips(request.getParameter("tips")); int row=userService.addUser(user); if (row>0) { out = response.getWriter(); out.flush(); out.println("<script>"); out.println("alert('恭喜您!注册成功!');"); out.println("history.back();"); out.println("</script>"); out.close(); } } @RequestMapping("/login") public String userlogin(@RequestParam(value="username")String username,@RequestParam(value="password")String password,HttpServletResponse response,HttpServletRequest request,Model model) throws IOException { PrintWriter out = null; HttpSession session=request.getSession(); User user=userService.findUserByid(username); if(user!=null&&user.getPassword().equals(password)) { session.setAttribute("username", username);//登录成功则在session对象中添加用户名信息 response.setContentType("text/html; charset=UTF-8"); //转码 try { out = response.getWriter(); out.flush(); out.println("<script>"); out.println("alert('登陆成功!');"); out.println("</script>"); return "index/systemindex"; } catch (IOException e) { e.printStackTrace(); } }else { response.setContentType("text/html; charset=UTF-8"); //转码 try { out = response.getWriter(); out.flush(); out.println("<script>"); out.println("alert('用户名或者密码错误!');"); out.println("history.back();"); out.println("</script>"); } catch (IOException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); }finally { out.close(); } } return null; } @RequestMapping(value="/userinfo") public String userinfo(User user,String username,Model model){ user=userService.findUserByid(username); model.addAttribute("user", user); return "index/userinfo"; } @RequestMapping(value="/systemindex") public String systemindex() { return "index/systemindex"; } @RequestMapping(value="/userpreupdate") public String userpreupdate(User user,String username,Model model) { user=userService.findUserByid(username); model.addAttribute("user", user); return "index/userupdate"; } @RequestMapping(value="/userupdate") public void userupdate(User user,HttpServletRequest request,HttpServletResponse response) throws IOException { PrintWriter out = null; response.setContentType("text/html; charset=UTF-8"); //转码 String username=request.getParameter("username"); out = response.getWriter(); user.setUsername(username); user.setTel(request.getParameter("tel")); user.setAddress(request.getParameter("address")); user.setNumber(request.getParameter("number")); user.setTips(request.getParameter("tips")); int row=userService.updateUser(user); System.out.println(row); if (row>0) { out = response.getWriter(); out.println("<script>"); out.println("alert('恭喜您!修改成功!');"); out.println("history.back();"); out.println("</script>"); out.close(); } } @RequestMapping(value="logout") public void logout(HttpSession session,HttpServletResponse response) throws IOException { session.removeAttribute("username");//移除session中用户名的信息,表示已注销 PrintWriter out = null; response.setContentType("text/html; charset=UTF-8"); //转码 out = response.getWriter(); out.flush(); out.println("<script>"); out.println("alert('注销成功!');"); out.print("window.location='userlogin.jsp'"); out.println("</script>"); out.close(); } @RequestMapping(value="userlist") public String userlist(Model model) { List<User> userlist=userService.findAllUser(); model.addAttribute("userlist",userlist); return "systemuser/userlist"; } @RequestMapping(value="findUserByName") public String findUser(HttpServletRequest request,Model model) { String username=request.getParameter("username"); List<User> userlist=userService.findUserByName(username); model.addAttribute("userlist",userlist); return "systemuser/userselect"; } @RequestMapping(value="/userdelete") public String studentDelete(String[] usernameArray) { userService.deleteUsers(usernameArray); return "redirect:userlist"; } }
重点:
要记住ssm框架完成一次请求的步骤:
①用户通过jsp页面发送请求;
②服务器通过controller接收请求并采用对应注解的方式调用服务请求的方法;
③在方法里面通过对数据的操作,然后再返回处理结果。
这就是一次完整的请求处理步骤。
关键是在方法里面的操作如何,在方法里面一般是定义一个service,比如userService,userService去调用userServiceImpl中的方法,而在userServiceImpl中使用Mapper接口中的方法对数据进行操纵。而操纵的 方法在mapper.xml文件中定义,这里要注意mapper接口中的方法名要跟xml文件中的id名要一致,不然会出错。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。