• SpringMvc


    Springmvc

    一般的步骤:

    1.搭建开发环境

    2.传值

    3.保存数据

    4.核心思想

    5.文件上传

    6.深入了解源码

    MVC  Model1:页面和代码混用

    MVC  Model2:页面和代码分离

    具体实现:

    一、搭建SpringMVC开发环境

    步骤:

    1.导jar包

    2.配置web.xml(一般配置完成后不需要再次改变)

      <servlet>

           <servlet-name>springmvc</servlet-name>

             <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-clas>

      </servlet>

      <servlet-mapping>

           <servlet-name>springmvc</servlet-name>

           <url-pattern>/</url-pattern>

      </servlet-mapping>

    3.编写Controller层

     继承于AbstractController实现他的

    protected ModelAndView handleRequestInternal(HttpServletRequest arg0,

                HttpServletResponse arg1) throws Exception {

              return null;

        }

    方法

    AbstractController是整个Controller继承层次的起源,该类通过模板方法模式(Template Method Pattern)帮我们解决了如下几个通用关注点:

    • 管理当前Controller所支持的请求方法类型(GET/POST);
    • 管理页面的缓存设置,即是否允许浏览器缓存当前页面;
    • 管理执行流程在会话(Session)上的同步。

    而我们所要做的,只不过是在AbstractController所公开的handleRequestInternal (request,response)模板方法中实现具体Web请求处理过程中的其他逻辑。

    3.编写xxx-servlet.xml配置文件

      <bean name="/hello" class="具体实现的类名和包名 " />

    小案例:可以在调用浏览器时在控制台输出一段话

    xxx-servlet.xml文件:

    通过注解:

      <context:component-scan base-package="com.Springmvc"/>

      <bean name="/hello" class="com.Springmvc.Controller.HelloController" />

    在浏览器调用的时候访问:(加项目名!!)

    http://localhost:8080/springmvc/hello

    Web.xml文件配置:

    <?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" version="3.0">

      <servlet>

        <servlet-name>springmvc</servlet-name>

        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

      </servlet>

      <servlet-mapping>

        <servlet-name>springmvc</servlet-name>

        <url-pattern>/</url-pattern>

      </servlet-mapping>

    </web-app>

    具体的实现:

    public class HelloController extends AbstractController{

        protected ModelAndView handleRequestInternal(HttpServletRequest arg0,

                HttpServletResponse arg1) throws Exception {

               System.out.println("Hello Spring");

            return null;

        }

    }
    二、简单的页面传参

    1)          HandlerMapping介绍:

     

    2)视图解析器

    视图解析器

    将逻辑视图的名字与JSP等视图技术进行匹配

    InternalResourceViewResolver

    在Web应用程序的WAR文件中查找视图模板,视图模板的路径

    根据加完前缀和后缀的逻辑视图名称来确定

    prefix

    suffix

    <beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver" >

    //文件是在WEB-INF/的对应文件

    <property name="prefix" value="/WEB-INF/"/>

    //是以.jsp结尾的

    <property name="suffix" value=".jsp"/>

    </bean>

    如:逻辑视图名称 /WEB-INF/index.jsp

    3.)案例在页面上传参(map / modal)

    xxx.sevlet.xml文件

    //开启注解

    <context:component-scan base-package="com.Springmvc"/>

    <!-- 配置视图解析器 -->

       <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

         //文件是在WEB-INF/的对应文件

          <property name="prefix" value="/WEB-INF/" />

    //是以.jsp结尾的

          <property name="suffix" value=".jsp" />

       </bean>

    Web.xml文件:

    <?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" version="3.0">

      <servlet>

        <servlet-name>springmvc</servlet-name>

        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

      </servlet>

      <servlet-mapping>

        <servlet-name>springmvc</servlet-name>

        <url-pattern>/</url-pattern>

      </servlet-mapping>

    </web-app>

    1. 通过@RequestMapping("名")注解实现打开相应的.jsp文件

    具体的实现

    package com.Springmvc.Controller;

    import org.springframework.stereotype.Controller;

    import org.springframework.web.bind.annotation.RequestMapping;

    @Controller

    @RequestMapping("/group")//具体的指向

    public class Group {    

     @RequestMapping("/toadd")//在浏览器中调用的名称

      public String add(){

               System.out.println("asdasda");

               Return  "group/add";//返回到对应的文件路径

      }

    }

    "group/add"所对应的是:

     

    访问:

    http://localhost:8080/com.Springmvc/toadd

    2.通过MAP集合实现界面上的输出信息

      实现类

      public class userController {

             @RequestMapping("/show")//在浏览器中调用的名称

        public String show (String username,Map<String,Object> param){

                //界面上传入的值:

                            param.put("uname", username);

                   List<String> users = new ArrayList<String>();

                   users.add("asdas");

                   users.add("asdas");

                   users.add("sdfsdfsf");

                   param.put("users", users);   //在jsp界面上调用的名称users

                       return "user/show";//返回到对应的文件路径

        }

     

    Jsp界面

    <body>

        <h2>user show...</h2>

                //获取

        用户名:${uname}<br />

        <c:forEach var="user" items="${users }">

        ${user }<br />

        </c:forEach>

      </body>

    访问:

    http://localhost:8080/com.Springmvc/show

    3.通过model实现界面上的输出信息

    用户类:

    package com.Springmvc.Controller;

    public class User {

        private int id;

        private String username;

        private String name;

        public User(){}

        public User(int id,String username,String name){

            this.id = id;

            this.username = username;

            this.name = name;

        }

        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 getName() {

            return name;

        }

        public void setName(String name) {

            this.name = name;

        }

       

        @Override

        public String toString() {

            return "User [id=" + id + ", username=" + username + ", name=" + name

                    + "]";

        }

    }

    实现类:

    public class userconter {

        Map<Integer, Object>  users = new HashMap<Integer, Object>();

        public   userconter(){

            User u1 = new User(1,"lp","asdas");

            User u2 = new User(2,"syp","sadasd");

            User u3 = new User(3,"mxd","asdasd");

            users.put(u1.getId(), u1);

            users.put(u2.getId(), u2);

            users.put(u3.getId(), u3);

        }

     

        @RequestMapping("/list")

        public String list(Model model){

            model.addAttribute("user",users);

            return "user/list";

          }

    }

    网页显示界面:

    <body>

           <table>

             <caption>用户列表</caption>

             <thead>

                <tr>

                  <th>ID</th>

                  <th>用户名</th>

                  <th>用户昵称</th>

                </tr>

             </thead>

             <tbody>

                  <c:forEach var="u" items="${user }">

                   <tr>

                      <td> ${u.value.id}</td>

                       <td>${u.value.username}</td>

                        <td>${u.value.name }</td>

                   </tr>

                  </c:forEach>

             </tbody>

          </table>

      </body>

    访问:

    http://localhost:8080/com.Springmvc/list

     

    传参:   @RequestParam:  必须给参数

    public String fangfa(@RequestParam){

      return “jsp文件”

    }

    Controller间的跳转

    redirect:类似于重定向

    eg:return "redirect:/user/list";

    表单元素name与对象属性一致即可!

    REST风格

    url:user/show/1

        通过@RequestMapping("/show/{id}")

    public String show(@PathVariable int id,Model model){

    实现

    session使用:

    方法参数:HttpSession session

    参数传递

    直接传递参数

    有些是必须的@RequestParam

    Rest{参数}

    值得保存

    Map

    Model

    跳转:Return “”

    重定向:return “readice”

    一、异常处理:

    自定义异常

    1.局部异常

      --针对单个Controller有效

    步骤:

    1)自定义一个异常类继承RuntimeException

    eg:public class UserException extends RuntimeException {

    2)@ExceptionHandler

    eg:

    public String handler(UserException ex,Model model){

             model.addAttribute("ex", ex);

             return "error";

    }

    在相应方法中捕获

    throw new UserException("用户名或密码不正确");

    3)配置spring MVC注解

    eg:<mvc:annotation-driven />

    2.全局异常

      --针对所有Controller有效

    步骤:

    1)自定义一个异常类继承RuntimeException

    eg:public class UserException extends RuntimeException {

    2)配置spring.xml

    eg:

    <!-- 全局异常处理解析器 -->

    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">

             <!-- 设置异常属性 -->

             <property name="exceptionAttribute" value="ex" />

             <!-- 异常映射 -->

             <property name="exceptionMappings">

                       <props>

                                <prop key="com.ibeifeng.springmvc.exception.UserException">error</prop>

                       </props>

             </property>

    </bean>

    二、静态资源文件处理

    在spring.xml中配置如下:

    <mvc:resources location="/resources/" mapping="/resources/**" />

    三、处理文件上传

    1、单文件

    步骤:

    1).导包

    commons-fileupload-1.3.2.jar

    commons-io-2.5.jar

    2)修改form表单

    ①<form enctype="multipart/form-data">

    ②头像:<input type="file" name="photo" />

    3)修改add方法

    public String add(User user,MultipartFile photo){

             String filename = photo.getOriginalFilename();

             FileUtils.copyInputStreamToFile(photo.getInputStream(), new File("D:\Workspaces\temp\resources\"+filename));

    4)修改spring.xml配置

    <!-- 配置文件上传解析器 -->

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

    </bean>

    2、多文件

    步骤:

    1)@RequestParam("photo") MultipartFile[] photos

    for(MultipartFile photo : photos){

             String filename = photo.getOriginalFilename();

             //判断文件是否为空

             if(filename.isEmpty()){

                       continue;

             }

             try {

                       FileUtils.copyInputStreamToFile(photo.getInputStream(), new File("D:\Workspaces\temp\resources\"+filename));

             } catch (IOException e) {

                       e.printStackTrace();

             }

    }

    2)修改页面

    头像:<input type="file" name="photo" /><br />

    头像:<input type="file" name="photo" /><br />

    头像:<input type="file" name="photo" /><br />

    四、Spring  MVC返回JSON数据

    步骤:

    1.导jar

    jackson-annotations-2.8.5.jar

    jackson-core-2.8.5.jar

    jackson-databind-2.8.5.jar

    2.在方法上加入@ResponseBody

    eg:

    @RequestMapping("/show/{id}")

    @ResponseBody

    public User show(@PathVariable int id,Model model){

             User user = users.get(id);

             model.addAttribute("user",user);

             return user;

    }

    $.ajax({

             url:"user/show/1",

             dataType:

             success:function(data){

                      

             }

    })

    {"id":1,"username":"lp","name":"李","password":null}

    data.id

    {stu:{id:1,name:abc}}

    data.stu.id

    案例:SpringMvc + JdbcTemplate+Jq+js+web

      Spring –servlet.xml配置文件:

    <?xml version="1.0" encoding="UTF-8"?>

    <beans xmlns="http://www.springframework.org/schema/beans"

    xmlns:context="http://www.springframework.org/schema/context"

    xmlns:aop="http://www.springframework.org/schema/aop"

     xmlns:mvc="http://www.springframework.org/schema/mvc"

      xmlns:tx="http://www.springframework.org/schema/tx"

        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

        xsi:schemaLocation="http://www.springframework.org/schema/beans

            http://www.springframework.org/schema/beans/spring-beans.xsd

            http://www.springframework.org/schema/context

            http://www.springframework.org/schema/context/spring-context.xsd

            http://www.springframework.org/schema/aop

              http://www.springframework.org/schema/mvc 

        http://www.springframework.org/schema/tx

        http://www.springframework.org/schema/tx/spring-tx.xsd

            http://www.springframework.org/schema/aop/spring-aop.xsd

            http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">

      <!-- 指明注解包 -->

     <bean

     class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">

     </bean>

     <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">

      <property name="messageConverters">

       <list><!-- json的时候必须加上,不然会提示406错误 -->

        <bean

         class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />

       </list>

      </property>

     </bean>

      <context:annotation-config/>

      <context:component-scan base-package="control"/>

      <context:component-scan base-package="Dao"/>

       <context:component-scan base-package="biz"/>

       <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

       <property name="prefix" value="/WEB-INF/page/"/>

    <!-- 配置我们自定义的返回方法调用的前缀 -->

       <property name="suffix" value=".jsp"/><!-- 返回我们自定义方法调用的后缀 -->

       <!-- 这样固定完成后,我们的地址就会变成 /WEB-INF/page/  .jsp我们在我们的文件中提供了String的返回值了之后就会将返回的String

            自动填充到这个空格里面,然后重定向 -->

      </bean>

        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" >

            <property name="driverClassName" value="com.mysql.jdbc.Driver"/>

            <property name="url" value="jdbc:mysql://localhost:3306/lintext"/>

            <property name="username" value="root"/>

            <property name="password" value="linqx"/>

        </bean>

       <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

        <!-- 设置上传文件的尺寸(52428805M   这个bean 上面两个是固定格式的-->

        <property name="maxUploadSize"> 

            <value>52428800</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://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">

       

        <servlet>

            <servlet-name>spring</servlet-name>

            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

            <enabled>true</enabled>

            <async-supported>true</async-supported>

        </servlet>

       

        <servlet-mapping>

            <servlet-name>spring</servlet-name>

            <url-pattern>/</url-pattern>

        </servlet-mapping>

        <servlet-mapping>

         <servlet-name>default</servlet-name>

         <url-pattern>*.css</url-pattern>

    </servlet-mapping>

    <servlet-mapping>

        <servlet-name>default</servlet-name>

        <url-pattern>*.gif</url-pattern>

     </servlet-mapping>

       

     <servlet-mapping>

         <servlet-name>default</servlet-name>

         <url-pattern>*.jpg</url-pattern>

     </servlet-mapping>

     <servlet-mapping>

        <servlet-name>default</servlet-name>

        <url-pattern>/image/*</url-pattern>

    </servlet-mapping>

     <servlet-mapping>

         <servlet-name>default</servlet-name>

         <url-pattern>*.js</url-pattern>

     </servlet-mapping>

       <!—过滤器-->

     <filter>

            <filter-name>encodingFilter</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>

            <init-param>

                <param-name>forceEncoding</param-name>

                <param-value>true</param-value>

            </init-param>

        </filter>

        <filter-mapping>

            <filter-name>encodingFilter</filter-name>

            <url-pattern>/*</url-pattern>

        </filter-mapping>

    </web-app>

    Dao层

    package Dao;

    import javax.annotation.Resource;

    import javax.sql.DataSource;

    import org.junit.runner.RunWith;

    import org.springframework.jdbc.core.JdbcTemplate;

    import org.springframework.stereotype.Component;

    import org.springframework.test.context.ContextConfiguration;

    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

    @RunWith(SpringJUnit4ClassRunner.class)

    @ContextConfiguration("/WEB-INF/spring-servlet.xml")

    @Component("da")

    public class BasicDao {

    public JdbcTemplate jdbcTemplate;

    @Resource(name="dataSource")

    public void setDataSource(DataSource dataSource) {

        this.jdbcTemplate = new JdbcTemplate(dataSource);

    }

    public JdbcTemplate getJdbcTemplate() {

             return jdbcTemplate;

    }

    Mldel层:user:

    package biz;

    public class UserPass {

    private String username;

    private String password;

    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;

    }

    }

    Mldel层:newcon

    package biz;

    import java.sql.Date;

    import java.text.SimpleDateFormat;

    import org.springframework.stereotype.Component;

    @Component("newslist")

    public class NewCon {

    private int id;

    private String  title;

    private String index;

    private String pic;

    private String create;

    private String  createtime;

    public int getId() {

             return id;

    }

    public void setId(int id) {

             this.id = id;

    }

    public String getTitle() {

             return title;

    }

    public void setTitle(String title) {

             this.title = title;

    }

    public String getIndex() {

             return index;

    }

    public void setIndex(String index) {

             this.index = index;

    }

    public String getPic() {

             return pic;

    }

    public void setPic(String pic) {

             this.pic = pic;

    }

    public String getCreate() {

             return create;

    }

    public void setCreate(String create) {

             this.create = create;

    }

    public String getCreatetime() {

             return createtime;

    }

    public void setCreatetime(Date createtime) {

             SimpleDateFormat myFmt=new SimpleDateFormat("YYYY-MM-DD");

             this.createtime = myFmt.format(createtime);

    }

    }

    Controller层登录层:

    package control;

    import java.util.ArrayList;

    import java.util.Map;

    import javax.annotation.Resource;

    import org.junit.Test;

    import org.junit.runner.RunWith;

    import org.springframework.jdbc.core.JdbcTemplate;

    import org.springframework.stereotype.Controller;

    import org.springframework.test.context.ContextConfiguration;

    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

    import org.springframework.ui.Model;

    import org.springframework.web.bind.annotation.RequestMapping;

    import Dao.BasicDao;

    @RunWith(SpringJUnit4ClassRunner.class)

    @ContextConfiguration("/WEB-INF/spring-servlet.xml")

    @Controller("DengLu")

    @RequestMapping("/con")

    public class DengLu {

             public  BasicDao dao;

             private JdbcTemplate jdbcTemplate;

             private NewCon newcon;

             public NewCon getNewcon() {

                       return newcon;

             }

             @Resource(name="NewCon")

             public void setNewcon(NewCon newcon) {

                       this.newcon = newcon;

             }

             public  BasicDao  BasicDao() {

                       return dao;

             }

             @Resource(name="da")

             public void setDao( BasicDao dao) {

                       this.dao = dao;

             }

             public JdbcTemplate getjdbcTemplate(){

                       jdbcTemplate=dao.getJdbcTemplate();

                       return  jdbcTemplate;

             }

             @RequestMapping("/checkname")

             @Test

            public String checkname(String username,String password,Model model){

                       String sql=" SELECT password,username FROM lintext.usepass where username=? and password=?";

                       jdbcTemplate=dao.getJdbcTemplate();

                       ArrayList<Map<String,Object>> o=(ArrayList<Map<String, Object>>) this.jdbcTemplate.queryForList(sql, username, password);

                       if(o!=null&&o.size()!=0){

                                return "redirect:/NewCon/select";

                       }

                       else{

                                return "redirect:/index.jsp";

                                }       

    }

    }

    Controller层新闻管理层:

    package control;

    import java.io.File;

    import java.io.IOException;

    import java.io.InputStream;

    import java.sql.Date;

    import java.util.ArrayList;

    import java.util.List;

    import java.util.Map;

    import javax.annotation.Resource;

    import javax.websocket.server.PathParam;

    import org.apache.commons.io.FileUtils;

    import org.junit.Test;

    import org.junit.runner.RunWith;

    import org.springframework.jdbc.core.JdbcTemplate;

    import org.springframework.stereotype.Controller;

    import org.springframework.test.context.ContextConfiguration;

    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

    import org.springframework.ui.Model;

    import org.springframework.web.bind.annotation.PathVariable;

    import org.springframework.web.bind.annotation.RequestMapping;

    import org.springframework.web.bind.annotation.RequestParam;

    import org.springframework.web.bind.annotation.ResponseBody;

    import org.springframework.web.multipart.MultipartFile;

    import Dao.BasicDao;

    @RunWith(SpringJUnit4ClassRunner.class)

    @ContextConfiguration("/WEB-INF/spring-servlet.xml")

    @RequestMapping("/NewCon")

    @Controller("NewCon")

    public class NewCon {

             public  BasicDao dao;

             private JdbcTemplate jdbcTemplate;

             public  BasicDao  BasicDao() {

                       return dao;

             }

             @Resource(name="da")

             public void setDao( BasicDao dao) {

                       this.dao = dao;

             }

             public JdbcTemplate getjdbcTemplate(){

                       jdbcTemplate=dao.getJdbcTemplate();

                       return  jdbcTemplate;

             }

             @Test

             @RequestMapping("/select")

       public String selectnew(Model model){

                       //int id=0;

                       jdbcTemplate=dao.getJdbcTemplate();

                       ArrayList<Map<String,Object>> o;

                       String sql="";

                       sql="select * from lintext.newsindex ";

                        o=(ArrayList<Map<String, Object>>) this.jdbcTemplate.queryForList(sql);

                       model.addAttribute("newslist", o);

                 return "newlist";

    }

             @RequestMapping("/insertintodetail")

       //public String updatenewdetail(String id,String  title,String index,String pic,String create,String  createtime){

             public String insertnewdetail(String id,@RequestParam MultipartFile img,String  title,String index,String create,String  createtime) throws IOException{

                       //int id=0;

                       System.out.println( img);

                       String imgname=img.getOriginalFilename();

                       if(imgname!=null){

                                jdbcTemplate=dao.getJdbcTemplate();

                                   int o;

                                         String sql="INSERT INTO `lintext`.`newsindex` "

                                                            + "( `title`, `index`, `create`, `createtime`,pic) VALUES "

                                                            + "( ?, ?,  ?, ?,?); ";

                                                   this.jdbcTemplate.update(sql, title,index,create,createtime,imgname);

                                                   File dir=new File("D:/Users/lin/Workspaces/MyEclipse 10/sprwebproject/WebRoot/image/"+imgname);

                                                   InputStream imgfile=img.getInputStream();

                                                   FileUtils.copyInputStreamToFile(imgfile,dir); 

                                                   imgfile.close();

                       }

            return "redirect:/NewCon/select";

    }

             @RequestMapping("/updatedetail")

                //public String updatenewdetail(String id,String  title,String index,String pic,String create,String  createtime){

             public String updatenewdetail(String id,@RequestParam MultipartFile file,String image,String  title,String index,String create,String  createtime) throws IOException{

                                //int id=0;

                       String imgname=file.getOriginalFilename();

                       if(imgname!=null||imgname!=""){

                                File dir=new File("D:/Users/lin/Workspaces/MyEclipse 10/sprwebproject/WebRoot/image/"+imgname);

                                InputStream imgfile=file.getInputStream();

                                FileUtils.copyInputStreamToFile(imgfile,dir); 

                                imgfile.close();

                       }else{

                                imgname=image;

                       }

                                jdbcTemplate=dao.getJdbcTemplate();           

                 int o;

                                String sql="UPDATE lintext.newsindex SET `title`=?,`index`=?, `create`=?, `createtime`=?,pic=? WHERE `id`=?";

                                         this.jdbcTemplate.update(sql,title,index,create,createtime,imgname,id);

                                        

                     return "redirect:/NewCon/select";

             }

             @RequestMapping("/selectdetail/{id}")

             //public void selectnew(){

       public String selectnewdetail(@PathVariable int id,Model model){

                       //int id=0;

                       jdbcTemplate=dao.getJdbcTemplate();

                       ArrayList<Map<String,Object>> o;

                       String sql="select * from lintext.newsindex ";;

                       if(id==0){

                        o=(ArrayList<Map<String, Object>>) this.jdbcTemplate.queryForList(sql);

                       }else{

                                sql+=" where id=?";

                                o=(ArrayList<Map<String, Object>>) this.jdbcTemplate.queryForList(sql,id);

                       }

                       model.addAttribute("newslist", o);

                 return "/newdetail";

    }

             @RequestMapping("/deletedetail/{id}")

             //public void selectnew(){

       public String deletedetail(@PathVariable int id){

                       //int id=0;

                       jdbcTemplate=dao.getJdbcTemplate();

                       ArrayList<Map<String,Object>> o;

                       String sql="delete from lintext.newsindex where id=? ";;

                       this.jdbcTemplate.update(sql, id);

                      

                         return "redirect:/NewCon/select";

             }

    @RequestMapping("/selectajax/{id}")

    @ResponseBody

    //public void selectnew(){

    public Map<String, Object> selectajax(@PathVariable int id,Model model){

             jdbcTemplate=dao.getJdbcTemplate();

             List<Map<String, Object>> o;

             String sql="select * from lintext.newsindex ";;

             if(id==0){

              o=(List<Map<String, Object>>) this.jdbcTemplate.queryForObject(sql, NewCon.class,id);

             }else{

                       sql+=" where id=?";

             o= this.jdbcTemplate.queryForList(sql, id);

             }

        return  o.get(0);

    }

    }

     

    Web层:用户登录界面

    <%@ 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">

    <html>

      <head>

        <base href="<%=basePath%>">

       

        <title>My JSP 'index.jsp' starting page</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">

             -->

             <script src="jquery-1.8.3.js" type="text/javascript"></script>

      </head>

     

      <body>

      <div>

      <form method="get" action="con/checkname" onsubmit="return sub()  ">

      <table>

      <tr><td>用户名:</td><td><input type="text" name="username" id="username"></td><td></td></tr>

      <tr><td>密码;:</td><td><input type="text" name="password" id="password"></td><td></td></tr>

      <tr><td colspan="3" id="info">&nbsp;</td></tr>

      <tr><td colspan="3" align="center"><input type="submit" value="登录"  ></td></tr>

      </table>

      </form>

      </div>

      <script type="text/javascript">

      function  sub(){

      if($("#username").required()&&$("#password").required()){

    $("#info").html("&nbsp;");

    return true;

    }else{

    $("#info").html("用户名或者密码不为空");

    return false;

    }

      }

     $.fn.required=function(){

     debugger;

    var value=this.val();

    if(value==null||value.lenght<=0||value==""){

    return false;

    }else{

    return true;

    }

    }

      </script>

      </body>

    </html>

    用户新增页面:

    <%@page import="java.text.SimpleDateFormat"%>

    <i><%@page language="java" import="java.util.*" pageEncoding="utf-8"%>

    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

    <%

    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>My JSP 'newdetail.jsp' starting page</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">

             -->

      </head>

     

      <body>

        <div>

          <%

       Date da=new Date();

       SimpleDateFormat si=new SimpleDateFormat("YYYY-MM-dd");

       String date= si.format(da);

       %>

        <table border="1px">

        <caption>新闻新增页面</caption>

        <form method="Post" action="NewCon/insertintodetail" onsubmit="return sub()" enctype="multipart/form-data">

       

        <tr><td>编码:</td><td><input type="input" name="id" readonly="readonly"  ></td></tr>

        <tr><td>标题:</td><td><input type="input"  name="title"></td></tr>

        <tr><td>摘要:</td><td><input type="input" name="index"></td></tr>

        <tr><td>图片:</td><td><input type="file" name="img"></td></tr><!--传文件一定记得传递方法要用post,get大小不一定够 -->

       

        <tr><td>创建人:</td><td><input type="input"  name="create"></td></tr>

        <tr><td>创建时间:</td><td><input type="date"  name="createtime" value=<%=date %>></td></tr>

        <tr><td colspan="2"><input type="submit" value="确认新增" ></tr>

        </form>

        <script type="text/javascript">

        function sub(){

         var msg = "您真的确定要确认新增吗? 请确认!";

     if (confirm(msg)==true){

      return true;

     }else{

      return false;

     }

    }

        </script>

        </table>

        </div>

      </body>

    </html>

    </i>

    新闻修改页面:

    <i><%@page language="java" import="java.util.*" pageEncoding="utf-8"%>

    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

    <%

    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>My JSP 'newdetail.jsp' starting page</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">

             -->

      </head>

     

      <body>

        <div>

        <table border="1px">

        <caption>新闻修改页面</caption>

        <form method="post" action="NewCon/updatedetail" enctype="multipart/form-data" onsubmit="return sub()">

         <c:forEach items="${newslist}" var="s">

        <tr><td>编码:</td><td><input type="input" value="${s.id}" name="id" readonly="readonly"></td></tr>

        <tr><td>标题:</td><td><input type="input" value="${s.title}" name="title"></td></tr>

        <tr><td>摘要:</td><td><input type="input" value="${s.index}" name="index"></td></tr>

        <tr><td>图片:</td><td><input type="file"  id="file" name="file" >

        <img src="image/${s.pic}" width="40px" height="40px" id="image" name="image" value="${s.pic}"></td></tr>

        <tr><td>创建人:</td><td><input type="input" value="${s.create}" name="create"></td></tr>

        <tr><td>创建时间:</td><td><input type="date"   value="${s.createtime}" name="createtime"></td></tr>

        <tr><td colspan="2"><input type="submit" value="确认修改" ></tr>

        </c:forEach>

         <script src="jquery-1.8.3.js"></script>

         <script type="text/javascript">

         $(function(){

         $("#file").change(function(){

         debugger;

      

         alert(  $("#file").val());

         $("#image").attr("src", $("#file").val());

         $()

         });

         })

         </script>

        </form>

        <script type="text/javascript">

        function sub(){

         var msg = "您真的确定要修改吗? 请确认!";

     if (confirm(msg)==true){

      return true;

     }else{

      return false;

     }

    }

       

        </script>

        </table>

        </div>

      </body>

    </html>

    </i>

    新闻list界面

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

    <%

    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>My JSP 'newlist.jsp' starting page</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">

             -->

      </head>

     

      <body>

      <div>

       <table border="1px">

       <tr><td>编号 </td>

       <td>标题 </td>

         <td>摘要 </td>

         <td>图片</td>

         <td>创建人 </td>

         <td>创建时间</td>

          <td>操作</td>

       </tr>

       <c:forEach items="${newslist}" var="s">

       <tr><td>${s.id} </td>

       <td>${s.title} </td>

         <td>${s.index} </td>

         <td><img src="image/${s.pic}"  width="40px"  height="40px" /></td>

         <td>${s.create} </td>

         <td>${s.createtime} </td>

    <td id="a">

           <a href="NewCon/selectdetail/${s.id}" id=${s.id} ">修改</a>|

              <a href="NewCon/deletedetail/${s.id}" id=${s.id} onclick="return cli()">删除</a> </td>

       </tr>

          </c:forEach>

       <div id="detail" background-color="white">

      编码:<input type="input" id="id" readonly="readonly"  ><br/>

       标题:<input type="input"  id="title"><br/>

      摘要:<input type="input" id="index"><br/>

        图片:<img name="img" id="img" width="20px" height="20px"><br/>

        创建人:<input type="input"  id="create"><br/>

      创建时间:<input type="date"  id="createtime" ><br/>

    </div>

       <script src="jquery-1.8.3.js"></script>

       <script type="text/javascript">

       $(function(){

       $("#detail").css("display","none");

       $("#detail").css("background-color","pink");

          debugger;

        $("tr").not( $("tr")[0] ).not("#a").mouseover(function(e){

    var left=e.originalEvent.x ;

    var top=e.originalEvent.y ;

     $("#detail").css("position","absolute");

      $("#detail").css("top",top+10);

        $("#detail").css("left",left+10);

      var id=$(this).children(0).html();

      $.ajax({

      dataType:"json",

       type: "GET",

      url:"NewCon/selectajax/"+id+".json",

      success:function(a){

       $("#detail").css("display","inline");

     $("#id").attr("value",a.id);

      $("#title").attr("value",a.title);

        $("#index").attr("value",a.index);

        $("#img").attr("src","image/"+a.pic);

        $("#create").attr("value",a.create);

        $("#createtime").attr("value",a.createtime);

      }

      });

     

       });

       })

       function cli(){

         var msg = "您真的确定要删除吗? 请确认!";

     if (confirm(msg)==true){

      return true;

     }else{

      return false;

     }

       }

       </script>

      

    </div>

       </table>

       <a href="insertnewdetail.jsp">新增</a>

      </body>

    </html>

  • 相关阅读:
    使用Koa搭建一个mock服务器
    d3 使用记录: 树形图
    转载: 矩阵的运算及运算规则
    d3 使用记录: 插值
    d3 使用记录: Selection
    转载: javascript 模块化历程
    Git 常用操作
    贝塞尔曲线_初探
    css 基础-
    Freemarker模板语法
  • 原文地址:https://www.cnblogs.com/guyuxuan/p/6857988.html
Copyright © 2020-2023  润新知