Spring MVC+MyBatis+MySql 具体实践

来源:互联网 发布:第三方辅助软件 编辑:程序博客网 时间:2024/06/07 19:53

本文演示常见的用户登录和数据库增删查改操作

SpringMVC 框架



SpringMVC注解概念一些介绍

以下非Demo实例内容
Java代码  收藏代码
  1. @Controller // 用来标注当前类是springmvc的控制层的类  
  2. @RequestMapping("/test"// RequestMapping表示 该控制器的唯一标识或者命名空间  
  3. public class TestController {  
  4.   
  5.     /** 
  6.      * 方法的返回值是ModelAndView中的 
  7.      */  
  8.     @RequestMapping("/hello.do"// 用来访问控制层的方法的注解  
  9.     public String hello() {  
  10.         System.out.println("springmvc annotation... ");  
  11.         return "jsp1/index";  
  12.     }  
  13.   
  14.     //*****  
  15. }  

在本例中,项目部署名为mvc,tomcat url为 http://localhost,所以实际为:http://localhos/mvc

在本例中,因为有命名空间 /test,所以请求hello方法地址为:http://localhost/mvc/test/hello.do

输出:springmvc annotation...

注解形式的参数接收

1可以直接定义在参数的列表,通过该请求可以传递参数

url:http://localhost/mvc/test/toPerson.do?name=zhangsan

Java代码  收藏代码
  1. /** 
  2.  * HttpServletRequest可以直接定义在参数的列表, 
  3.  *  
  4.  */  
  5. @RequestMapping("/toPerson.do")  
  6. public String toPerson(HttpServletRequest request) {  
  7.     String result = request.getParameter("name");  
  8.     System.out.println(result);  
  9.     return "jsp1/index";  
  10. }  

 可以从HttpServletRequest 取出“name”属性,然后进行操作!如上,可以取出 “name=zhangsan”

输出:zhangsan
2. 在参数列表上直接定义要接收的参数名称,只要参数名称能匹配的上就能接收所传过来的数据, 可以自动转换成参数列表里面的类型,注意的是值与类型之间是可以转换的

2.1传递多种不同类型的参数:

url:http://localhost/mvc/test/toPerson1.do?name=zhangsan&age=14&address=china&birthday=2000-2-11

Java代码  收藏代码
  1. /** 
  2.  * 传递的参数的名字必须要与实体类的属性set方法后面的字符串匹配的上才能接收到参数,首字符的大小写不区分 
  3.  * 请求中传的参数只要是能和参数列表里面的变量名或者实体里面的set后面的字符串匹配的上就能接收到 a 
  4.  *  
  5.  */  
  6. @RequestMapping("/toPerson1.do")  
  7. public String toPerson1(String name, Integer age, String address,  
  8.              Date birthday) {  
  9.            System.out.println(name + " " + age + " " + address + " " + birthday);  
  10.            return "jsp1/index";  
  11. }  
  12.   
  13. /** 
  14.  * 注册时间类型的属性编辑器,将String转化为Date 
  15.  */  
  16. @InitBinder  
  17. public void initBinder(ServletRequestDataBinder binder) {  
  18.     binder.registerCustomEditor(Date.classnew CustomDateEditor(  
  19.             new SimpleDateFormat("yyyy-MM-dd"), true));  
  20. }  

输出:zhangsan 14 china Fri Feb 11 00:00:00 CST 2000

2.2传递数组:

url:http://localhost/mvc/test/toPerson2.do?name=tom&name=jack  

Java代码  收藏代码
  1. /** 
  2.  * 对数组的接收,定义为同名即可  
  3.  */  
  4. @RequestMapping("/toPerson2.do")  
  5. public String toPerson2(String[] name) {  
  6.     for (String result : name) {  
  7.         System.out.println(result);  
  8.     }  
  9.     return "jsp1/index";  
  10. }  

 输出:tom jack

2.3传递自定义对象(可多个):

url:http://localhost/mvc/test/toPerson3.do?name=zhangsan&age=14&address=china&birthday=2000-2-11

 User 定义的属性有:name,age,并且有各自属性的对应的set方法以及toString方法

 Person定义的属性有:name,age.address,birthday,并且有各自属性的对应的set方法以及toString方法

Java代码  收藏代码
  1. /** 
  2.  *  
  3.  * 传递的参数的名字必须要与实体类的属性set方法后面的字符串匹配的上才能接收到参数,首字符的大小写不区分 
  4.  * 请求中传的参数只要是能和参数列表里面的变量名或者实体里面的set后面的字符串匹配的上就能接收到  
  5.  *  
  6.  */  
  7. @RequestMapping("/toPerson3.do")  
  8. public String toPerson3(Person person, User user) {  
  9.     System.out.println(person);  
  10.     System.out.println(user);  
  11.     return "jsp1/index";  
  12. }  

  输出:

Person [name=zhangsan, age=14, address=china, birthday=Fri Feb 11 00:00:00 CST 2000]
User [name=zhangsan, age=14]
 

自动封装了对象,并且被分别注入进来!

 

注解形式的结果返回

 1. 数据写到页面,方法的返回值采用ModelAndView, new ModelAndView("index", map);,相当于把结果数据放到response里面

url:http://localhost/mvc/test/toPerson41.do

url:http://localhost/mvc/test/toPerson42.do

url:http://localhost/mvc/test/toPerson43.do

url:http://localhost/mvc/test/toPerson44.do 

Java代码  收藏代码
  1. /** 
  2.  * HttpServletRequest可以直接定义在参数的列表,并且带回返回结果 
  3.  *  
  4.  */  
  5. @RequestMapping("/toPerson41.do")  
  6. public String toPerson41(HttpServletRequest request) throws Exception {  
  7.     request.setAttribute("p", newPesion());  
  8.     return "index";  
  9. }  
  10.   
  11. /** 
  12.  *  
  13.  * 方法的返回值采用ModelAndView, new ModelAndView("index", map); 
  14.  * ,相当于把结果数据放到Request里面,不建议使用 
  15.  *  
  16.  */  
  17. @RequestMapping("/toPerson42.do")  
  18. public ModelAndView toPerson42() throws Exception {  
  19.     Map<String, Object> map = new HashMap<String, Object>();  
  20.     map.put("p", newPesion());  
  21.     return new ModelAndView("index", map);  
  22. }  
  23.   
  24. /** 
  25.  *  
  26.  * 直接在方法的参数列表中来定义Map,这个Map即使ModelAndView里面的Map, 
  27.  * 由视图解析器统一处理,统一走ModelAndView的接口,也不建议使用 
  28.  */  
  29. @RequestMapping("/toPerson43.do")  
  30. public String toPerson43(Map<String, Object> map) throws Exception {  
  31.     map.put("p", newPesion());  
  32.     return "index";  
  33. }  
  34.   
  35. /** 
  36.  *  
  37.  * 在参数列表中直接定义Model,model.addAttribute("p", person); 
  38.  * 把参数值放到request类里面去,建议使用 
  39.  *  
  40.  */  
  41. @RequestMapping("/toPerson44.do")  
  42. public String toPerson44(Model model) throws Exception {  
  43.     // 把参数值放到request类里面去  
  44.     model.addAttribute("p", newPesion());  
  45.     return "index";  
  46. }  
  47.   
  48. /** 
  49.  * 为了测试,创建一个Persion对象 
  50.  *  
  51.  */  
  52. public Person newPesion(){  
  53.     Person person = new Person();  
  54.     person.setName("james");  
  55.     person.setAge(29);  
  56.     person.setAddress("maami");  
  57.     SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");  
  58.     Date date = format.parse("1984-12-28");  
  59.     person.setBirthday(date);  
  60.     return person;  
  61. }  

  以上四种方式均能达到相同的效果,但在参数列表中直接定义Model,model.addAttribute("p", person);把参数值放到request类里面去,建议使用

 

2. Ajax调用springmvc的方法:直接在参数的列表上定义PrintWriter,out.write(result);把结果写到页面,建议使用的

 url:http://localhost/mvc/test/toAjax.do 

 

Java代码  收藏代码
  1.     /** 
  2.      *  
  3.      * ajax的请求返回值类型应该是void,参数列表里直接定义HttpServletResponse, 
  4.      * 获得PrintWriter的类,最后可把结果写到页面 不建议使用  
  5.      */  
  6.     @RequestMapping("/ajax1.do")  
  7.     public void ajax1(String name, HttpServletResponse response) {  
  8.         String result = "hello " + name;  
  9.         try {  
  10.             response.getWriter().write(result);  
  11.         } catch (IOException e) {  
  12.             e.printStackTrace();  
  13.         }  
  14.     }  
  15.   
  16.     /** 
  17.      *  
  18.      * 直接在参数的列表上定义PrintWriter,out.write(result); 
  19.      * 把结果写到页面,建议使用的  
  20.      *  
  21.      */  
  22.     @RequestMapping("/ajax2.do")  
  23.     public void ajax2(String name, PrintWriter out) {  
  24.         String result = "hello " + name;  
  25.         out.write(result);  
  26.     }  
  27.     /** 
  28.      * 转向ajax.jsp页面 
  29.      */  
  30.   
  31.     @RequestMapping("/toAjax.do")  
  32.    
  33.     public String toAjax() {  
  34.         return "ajax";  
  35.    }  

ajax页面代码如下:

Html代码  收藏代码
  1. <script type="text/javascript" src="js/jquery-1.6.2.js"></script>  
  2. <script type="text/javascript">  
  3.         $(function(){  
  4.             $("#mybutton").click(function(){  
  5.                 $.ajax({  
  6.                     url:"test/ajax1.do",  
  7.                     type:"post",  
  8.                     dataType:"text",  
  9.                     data:{  
  10.                         name:"zhangsan"  
  11.                     },  
  12.                     success:function(responseText){  
  13.                         alert(responseText);  
  14.                     },  
  15.                     error:function(){  
  16.                         alert("system error");  
  17.                     }  
  18.                 });  
  19.             });  
  20.         });  
  21.     </script>  
  22. </head>  
  23. <body>  
  24.     <input id="mybutton" type="button" value="click">  
  25. </body>  
  26.    

表单提交和重定向

表单提交:

请求方式的指定:@RequestMapping( method=RequestMethod.POST )可以指定请求方式,前台页面就必须要以它制定好的方式来访问,否则出现405错误

 表单jsp页面: 
Html代码  收藏代码
  1. <html>  
  2.   <head>  
  3.     <base href="<%=basePath%>">  
  4.     <title>SpringMVC Form</title>  
  5.   </head>  
  6.   <body>  
  7.     <form action="test/toPerson5.do" method="post">  
  8.         name:<input name="name" type="text"><br>  
  9.         age:<input name="age" type="text"><br>  
  10.         address:<input name="address" type="text"><br>  
  11.         birthday:<input name="birthday" type="text"><br>  
  12.         <input type="submit" value="submit"><br>  
  13.     </form>  
  14.   </body>  
  15. </html>  
 对应方法为:
Java代码  收藏代码
  1. /** 
  2.  * 转向form.jsp页面 
  3.  * @return 
  4.  */  
  5. @RequestMapping("/toform.do")  
  6. public String toForm() {  
  7.     return "form";  
  8. }  
  9.   
  10. /** 
  11.  *  
  12.  * @RequestMapping( method=RequestMethod.POST) 
  13.  * 可以指定请求方式,前台页面就必须要以它制定好的方式来访问,否则出现405错误 a 
  14.  *  
  15.  */  
  16. @RequestMapping(value = "/toPerson5.do", method = RequestMethod.POST)  
  17. public String toPerson5(Person person) {  
  18.     System.out.println(person);  
  19.     return "jsp1/index";  
  20. }  
 url:http://localhost/mvc/test/toform.do  
重定向:controller内部重定向,redirect:加上同一个controller中的requestMapping的值,controller之间的重定向:必须要指定好controller的命名空间再指定requestMapping的值,redirect:后必须要加/,是从根目录开始
Java代码  收藏代码
  1. /** 
  2.  *  
  3.  * controller内部重定向 
  4.  * redirect:加上同一个controller中的requestMapping的值  
  5.  *  
  6.  */  
  7. @RequestMapping("/redirectToForm.do")  
  8. public String redirectToForm() {  
  9.     return "redirect:toform.do";  
  10. }  
  11.   
  12. /** 
  13.  *  
  14.  * controller之间的重定向:必须要指定好controller的命名空间再指定requestMapping的值, 
  15.  * redirect:后必须要加/,是从根目录开始 
  16.  */  
  17. @RequestMapping("/redirectToForm1.do")  
  18. public String redirectToForm1() {  
  19.               //test1表示另一个Controller的命名空间  
  20.     return "redirect:/test1/toForm.do";  
  21. }  

一. 准备工作

数据库:

--Mysql 5.6


创建数据库 wolf

1
CREATE DATABASE wolf;

创建用户表 user

1
2
3
4
5
6
create table user(
id int  AUTO_INCREMENT  primary key,
name varchar(255) not null,
niceName varchar(255)not null,
pwd varchar(255) not null,
age int
)

向表中插入测试数据

1
2
3
4
insert into user(name,nickname,pwd,agevalues("wangxin","wang","123",16);
insert into user(name,nickname,pwd,age) valuse("liming","li","123",18);

jar:

 1.驱动:mysql-connector-java-5.1.7-bin.jar

 2.jstl 的

jstl.jar

standard.jar

 3.spring 的

 spring-aop-4.0.0.M2.jar

 spring-beans-4.0.0.M2.jar

 spring-context-4.0.0.M2.jar

 spring-core-4.0.0.M2.jar      (若出现问题,可以替换 spring-core-4.0.0.RELEASE.jar)

 spring-expression-4.0.0.M2.jar

 spring-jdbc-4.0.0.M2.jar

 spring-test-4.0.0.M2.jar

 spring-tx-4.0.0.M2.jar

 4.mybatis 的 

 mybatis-3.1.1.jar

 log4j-1.2.16.jar

 mybatis-spring-1.2.1.jar

 5.以及spring-depend 

 aopalliance-1.0.jar

 cglib-nodep-2.1_3.jar

 commons-logging-1.1.1.jar

 6.web 相关的

 spring-web-4.0.0.RELEASE.jar

 spring-webmvc-4.0.0.RELEASE.jar



二. Spring MVC 配置文件

WebContent/WEB-INF/Web.xml:

<pre name="code" class="html"><pre name="code" class="html"><?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" 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">  <!-- spring提供转码 -->  <display-name>ADong</display-name>    <context-param>   <param-name>contextConfigLocation</param-name>   <param-value>classpath:config/applicationContext.xml</param-value>  </context-param>    <listener>   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  </listener>    <!-- spring提供转码 --> <filter>        <filter-name>characterEncoding</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>characterEncoding</filter-name>        <url-pattern>/*</url-pattern>    </filter-mapping>      <servlet>        <servlet-name>spring-mvc</servlet-name>        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>        <servlet-name>woder</servlet-name>        <url-pattern>/</url-pattern>    </servlet-mapping>    </web-app>

src/config/applicationContext.xml

<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"xmlns:tx="http://www.springframework.org/schema/tx"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.2.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.2.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.2.xsd"><!-- 1. 数据源 : DriverManagerDataSource --><bean id="datasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3307/wolf"/><property name="username" value="root"/><property name="password" value="root"/></bean><!-- 2. mybatis的SqlSession的工厂: SqlSessionFactoryBean dataSource / typeAliasesPackage--><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="datasource"/><property name="typeAliasesPackage" value="com.adong.model"/><property name="configLocation" value="classpath:config/mybatis-config.xml" /></bean><!-- 3. mybatis自动扫描加载Sql映射文件 : MapperScannerConfigurer sqlSessionFactory / basePackage--><bean  class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.adong.mapper"/><property name="sqlSessionFactory" ref="sqlSessionFactory"/></bean><!-- 4. 事务管理 : DataSourceTransactionManager --><bean id="manager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="datasource"/></bean><!-- 5. 使用声明式事务 --><tx:annotation-driven transaction-manager="manager" /></beans>


WebContent/WEB-INF/spring-mvc.xml

<?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:cxt="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd "><!-- 启动包扫描功能,以便注册带有@Controller、@Service、@repository、@Component等注解的类成为spring的bean --><cxt:component-scan base-package="com.adong.controller"><!-- <cxt:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/> --></cxt:component-scan><!--  主要作用于@Controller,激活该模式,下面是一种简写形式,完全可以手动配置替代这种简写形式,它会自动注册DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter,是spring MVC为@Controllers分发请求所必须的   --><mvc:annotation-driven/><!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 --><bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"><!-- <property name="cache" value="true"/> --><!-- viewClass属性可以用来指定前台在解析数据时,所允许采用的手段。实际上其默认值就是JstlView --> <!-- 将来有需要的话,就可以在这里把JstlView改成其它的,如FreeMarkerView,VelocityView,TilesView --> <!-- <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> --><property name="prefix" value="/WEB-INF"/><property name="suffix" value=".jsp"/><property name="contentType" value="text/html;charset=UTF-8"/></bean></beans>

src/config/mybatis-config.xml

<?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 type="com.adong.bean.User" alias="User" /></typeAliases><!-- 设置数据库连接环境 --><!-- 映射文件 --><mappers><mapper resource="com/adong/mapper/userMapper.xml" /></mappers></configuration>
src/com/adong/mapper/userMapper.xml

<?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.adong.mapper.UserMapper"><select id="login" resultMap="User">select * fromuserwherename=#{name}and pwd=#{password}</select><select id="list" resultMap="User">select * from user</select><insert id="add" parameterType="User">insert into user(name,nickname,pwd,age) values(#(name),#(nickname),#(pwd),#(age))</insert><select id="load" resultMap="User">select * from user where id = #{id}</select><delete id="delete" >delete from user where id = #{id}</delete><update id="update" >update user set name=#(name),nickname=#(nickname),pwd=#(pwd),age=#(age) where id = #{id}</update></mapper>





三.代码实践

以下为demo实例内容

model中user.java代码如下

package com.aodong.model;public class User  {      private long id;      private String name;      private String niceName;      private int age;    private String pwd; public long getId() {return id;}public void setId(long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getNiceName() {return niceName;}public void setNiceName(String niceName) {this.niceName = niceName;}        public String getNiceName() {return niceName;}public void setNiceName(String niceName) {this.niceName = niceName;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}             }


UserMapper.java代码如下

package com.aodong.mapper;import java.util.List;import com.aodong.model.User;public interface UserMapper  {  public void add(User user);public void update(User user);public void delete(long id);public User load(long id);public List<user> list();} 


UserController.java代码如下:

com.aodong.controller;import java.util.List;import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.servlet.ModelAndView;import com.aodong.model.User;import com.aodong.mapper.UserMapper;@Controller  @RequestMapping("/user")  public class UserController  {     @Resource    private UserMapper userMapper;        @RequestMapping(value="/list.do",method=RequestMethod.GET)    public ModelAndView getUserlist(Model model){                ModelAndView mv = new ModelAndView();        List<Student> userList = userMapper.list();        System.out.println("log======table 'user' all records:"+userList.size());        mv.addObject("userList", userList);        mv.setViewName("list");        return mv;    }        @RequestMapping(value="/add.do",method=RequestMethod.GET)    public ModelAndView getAdd(){        ModelAndView mv = new ModelAndView();        mv.setViewName("add");        return mv;    }        @RequestMapping(value="/add.do",method=RequestMethod.POST)    public String add(@ModelAttribute("user") User user){        userMapper.add(user);        return "redirect:/user/list.do";    }        @RequestMapping(value="/{userid}/show.do",method=RequestMethod.GET)    public String show(@PathVariable Long userid,Model model){        User user = userMapper.load(userid);    model.addAttribute("user", user);        return "detail";    }        @RequestMapping(value="/{userid}/del.do",method=RequestMethod.GET)    public String del(@PathVariable Long userid){        userMapper.delete(userid);        List<User> user=userMapper.list();        System.out.println(user.size());        return "redirect:/user/list.do";    }        @RequestMapping(value="/{userid}/edit.do",method=RequestMethod.GET)    public ModelAndView getEdit(@PathVariable Long userid,Model model){    User user = userMapper.load(userid);        model.addAttribute("userAttribute", user);        ModelAndView mv = new ModelAndView();        mv.setViewName("edit");        return mv;    }        @RequestMapping(value="/{userid}/save.do",method=RequestMethod.POST)    public String saveEdit(@ModelAttribute("userAttribute") User user,@PathVariable Long userid){        userMapper.update(user);          return "redirect:/user/list.do";     }     @RequestMapping(value="/login.do", method=RequestMethod.GET)     public String login(){ return "login"; }     @RequestMapping(value="/login.do", method=RequestMethod.POST)     public String submit(String userName, String passwd, HttpServletRequest request,HttpServletResponse response, ModelMap model){String name = request.getParameter("username");String password = request.getParameter("password");System.out.println("login");User user_login = usermapper.login(name, password);System.out.println(user_login);if (user_login == null) {System.out.println("Error login!");        return "fail";        }       else {   model.addAttribute("user", user_login);return "success";       }                      }}


WebContent/index.jsp 粉墨登场,(跳转到登录页面)
<jsp:forward page="/WEB-INF/user/login.jsp"></jsp:forward>

WebContent/WEB-INF/user/login.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"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>login</title></head><body><form action="user/login.do" method="post"><table align="left"><tr><td>用户名:</td><td><input id="userName" type="text" name="username"></td></tr><tr><td>密码:</td><td><input id="password" type="password" name="password"></td></tr><tr><td><button type="submit" name="Submit">登录</button></td></tr></table></form></body></html>


WebContent/WEB-INF/user/sucess.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"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Success</title></head><body>Welcome<font color="red">${requestScope.user.name} </font>!<br><br><a href="list.do">用户信息列表</a></body></html>
WebContent/WEB-INF/user/fail.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"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Fail</title></head><body><h3><font color="red">fail login!</font></h3><h2><a href="${pageContext.request.contextPath}">return the LoginPage!</a></h2></body></html>


WebContent/WEB-INF/student/list.jsp(列出所有记录)

<%@ page language="java" contentType="text/html; charset=UTF-8"      pageEncoding="UTF-8"%>  <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  <!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>User List</title>  </head>  <body>      <a href="add.do">Add</a>      <table>          <tr>              <td>ID</td>              <td>Name</td>              <td>NiceName</td>              <td>Age</td>          </tr>          <c:forEach var="user" items="${userList }" >              <tr>                  <td>${user.id }</td>                  <td>${user.name }</td>                  <td>${user.niceName }</td>                  <td>${user.age }</td>                  <td><a href="${user.id }/show.do">详细</a></td>                  <td><a href="${user.id}/edit.do">编辑</a></td>                  <td><a href="${user.id}/del.do">删除</a></td>              </tr>          </c:forEach>      </table>  </body>  </html> 


WebContent/WEB-INF/user/add.jsp(增加一条记录)

<%@ page language="java" contentType="text/html; charset=UTF-8"      pageEncoding="UTF-8"%>   <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  <!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>Add User</title>  </head>  <body>      <form action="add.do" method="post">                    Name:<input id="name" name="name" type="text" />          <br>          Nice Name:<input id="niceName" name="niceName" type="text" />         <br>          Password:<input id="pwd" name="pwd" type="password" />       <br> Age:<input id="age" name="age" type="text" /> <br> <input type="submit" value="提交"> </form> </body> </html>


WebContent/WEB-INF/user/detail.jsp(显示一条记录)

<%@ page language="java" contentType="text/html; charset=UTF-8"      pageEncoding="UTF-8"%>  <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  <!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>Show user</title>  </head>  <body>      <c:out value="${user.id }"></c:out>      <br>      <c:out value="${user.name }"></c:out>      <br>      <c:out value="${user.niceName }"></c:out>      <br>      <c:out value="${user.age }"></c:out>  </body>  </html>  

WebContent/WEB-INF/user/edit.jsp (编辑记录)

<%@ page language="java" contentType="text/html; charset=UTF-8"      pageEncoding="UTF-8"%>  <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>  <!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>Edit user</title>  </head>  <body>      <c:url var="saveUrl" value="/student/${userAttribute.id}/save.do" />      <form:form modelAttribute="userAttribute" action="${saveUrl }">          <table>              <tr>                  <td>ID:</td>                  <td><form:input path="id" /></td>              </tr>              <tr>                  <td>Name:</td>                  <td><form:input path="name"/></td>              </tr>              <tr>                  <td>Nice name:</td>                  <td><form:input path="niceName"/></td>              </tr>         <tr>                  <td>Password:</td>                  <td><form:password path="pwd"/></td>              </tr> <tr> <td>Age:</td> <td><form:input path="age"/></td> </tr> </table> <input type="submit" value="Save"> </form:form> </body> </html>


0 0
原创粉丝点击