MVC 구조 (1) JSP + Servlet + JDBC 구 조 를 구축 하 는 웹 프로젝트
간단 한 자바 웹 프로젝트 는 MVC 구 조 를 통 해 사용자 와 데이터 의 상호작용 을 실현 하 는 효과 로 요약 할 수 있다.한편, 자바 웹 프로젝트 의 MVC 구 조 는 이미 매우 성숙 하여 최초의 servlet + jsp + jdbc 에서 SSH 프레임 워 크 에 이 르 기 까지 현재 매우 유행 하 는 SSM 프레임 워 크 입 니 다.본 고 는 JSP 를 V (view) 층 으로, servlet 를 C (controller) 층 으로, JDBC 를 M (model) 층 으로 하여 원시 자바 웹 프로젝트 를 구축 하고 체험 하고 자 한다.
프로젝트 구 조 를 구축 하 다.
< dependency>
 < groupId>javax.servletgroupId>
 <artifactId>javax.servlet-apiartifactId>
  <version>4.0.0version>
 dependency>
 <dependency>
  <groupId>mysqlgroupId>
  <artifactId>mysql-connector-javaartifactId>
  <version>5.1.10version>
dependency>  프론트 에서 백 스테이지 까지
로그 인 요청 실현
  이 클래스 에서 ctrl + o 를 두 번 누 르 면 부모 클래스 (HttpServlet) 의 속성 과 방법 을 볼 수 있 습 니 다.
단축 키 alt + shift + s 를 통 해 Override / Implement Methods 를 선택 하면 부모 클래스 의 방법 을 선택 하여 재 작성 하거나 실현 할 수 있 습 니 다.
일반적으로 doGet, doPost, service, init 와 destroy 방법 을 다시 쓸 수 있 습 니 다.
service 방법 은 인터페이스 에 있 는 방법 입 니 다. servlet 용 기 는 모든 요청 을 이 방법 으로 보 냅 니 다. 이 방법 은 http 요청 을 doXXX 방법 으로 전송 하 는 것 입 니 다. 이 방법 을 다시 불 러 오 면 기본 동작 이 덮어 쓰 이 고 퍼 가기 작업 을 하지 않 습 니 다!
현재 클 라 이언 트 가 pos 든 get 으로 이 servlet 을 요청 하 든 service 방법 은 service 방법 만 실행 할 수 있 고 doPost 나 doGet 방법 을 실행 하지 않 습 니 다.
get 한자 의 전 삼 에 사용 할 수 없습니다.
    private static final long serialVersionUID = 1L;
    public UserLoginAction(){
        System.out.println("LoginServlet    ");
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("servlet doGet");
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("servlet doPost");
    }
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("  servlet service");
        req.setCharacterEncoding("utf-8"); 
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println("            "+username+password);
        //req.getRequestDispatcher("/subinfo.jsp").forward(req, resp);
         resp.sendRedirect("/MavenWeb/subinfo.jsp");
    }
    @Override
    public void init() throws ServletException {
        System.out.println("servlet   ");
    }
    @Override
    public void destroy() {
        System.out.println("servlet   ");
    }  처리 요청 의 마지막 코드:
    //req.getRequestDispatcher("/subinfo.jsp").forward(req, resp);
     resp.sendRedirect("/MavenWeb/subinfo.jsp");  요청 을 처리 한 후 점프 하 는 방식 은 두 가지 가 있 습 니 다. redirect (리 셋) 와 forward (리 트 윗) 입 니 다.
redirect: 서버 가 request 를 받 은 후 클 라 이언 트 브 라 우 저 에 상태 헤더 요청 을 보 냅 니 다. 두 번 의 요청 에 해당 합 니 다. 페이지 를 모든 페이지 로 옮 길 수 있 습 니 다. 이 웹 응용 에 국한 되 지 않 습 니 다.
forward: 이 웹 애플 리 케 이 션 의 페이지 로 만 이동 할 수 있 습 니 다. 점프 후 브 라 우 저 주소 표시 줄 은 변 하지 않 습 니 다. 퍼 가기 요청, 즉 앞 뒤 페이지 에서 하나의 request 를 공유 하 는 것 은 서버 에서 실 행 됩 니 다.
6. 이 servlet 를 웹. xml 에 등록 합 니 다.
<servlet>
    <servlet-name>loginServletservlet-name>
    <servlet-class>com.leetech.action.UserLoginActionservlet-class>
servlet>
<servlet-mapping>
    <servlet-name>loginServletservlet-name>
    <url-pattern>/userLoginActionurl-pattern>
servlet-mapping>  servlet 3.0 은 주 해 를 제공 합 니 다. servlet 클래스 에 직접 쓸 수 있 습 니 다.
@WebServlet("/userSubinfoAction")
public class UserLoginAction extends HttpServlet{...}
//  :
@WebServlet(name="loginAction",urlPatterns="/userSubinfoAction")  enctype=”multipart/form-data”
(2) 폼 에 업로드 파일 요 소 를 추가 합 니 다.
"photoFile" type="file" id="inputfile" class="col-sm-4">
  (3) servlet 클래스 를 등록 할 때의 설정: 주 해 를 통 해 등록 하면 클래스 에 @ MultipartConfig 를 추가 하고 xml 를 통 해 등록 하면 servlet 탭 에 가입 해 야 합 니 다.
 <multipart-config>multipart-config>    두 설정 모두 파일 의 기본 업로드 경로, 단일 파일 의 최대 값, 모든 파일 의 최대 값 등 속성 을 설정 할 수 있 습 니 다.(4) servlet 클래스 는 업 로드 된 파일 을 받 아 저장 합 니 다.
//               :
Part part = req.getPart("photoFile");
part.write( "F:/picture.png");
//                
part.getSize();//    
part.getContentType();//    
part.getHeader("content-disposition");//form-data; name="photoFile"; filename="mavenWeb     .png"  배경 에서 데이터베이스 까지
사용자 등록 실현
    <form class="form-horizontal" enctype="multipart/form-data"  role="form" action="userSubinfoAction" method="post">
     <div class="form-group">
        <label for="inputName" class="col-sm-2 control-label">  label>
        <div class="col-sm-4">
            <input name="name" type="text" class="form-control" id="inputName" placeholder="       ">
        div>
    div>
     <div class="form-group">
         <label for="inputName" class="col-sm-2 control-label">  label>
            <label class="radio-inline">
        <input type="radio" name="sex"  value="man" checked>  
    label>
    <label class="radio-inline">
        <input type="radio" name="sex"   value="woman">  
    label>
        div>
    <div class="form-group">
        <label  class="col-sm-2 control-label">  label>
        <select class=" col-sm-4" name="country">
            <option>  option>
            <option>  option>
            <option>  option>
            <option>  option>
            <option>  option>
        select>
    div>
      <div class="form-group">
        <label class="col-sm-2 control-label" for="inputfile">    label>
        <input name="photoFile" type="file" id="inputfile" class="col-sm-4">
    div>
        <button class="btn btn-lg btn-warning btn-block" type="submit">  button>
    form>
  @WebServlet("/userSubinfoAction")
@MultipartConfig
public class UserSubinfoAction extends HttpServlet{
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String savePath = req.getServletContext().getRealPath("/WEB-INF/uploadFile");
        System.out.println(savePath);
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        Part part = req.getPart("photoFile");
        String header = part.getHeader("content-disposition");
        System.out.println(header);
        part.write("F:/s.png");
        User user = new User();
        user.setUserName(req.getParameter("name"));
        user.setSex(req.getParameter("sex"));
        user.setCountry(req.getParameter("country"));
        user.setPhotoFile("F:/s.png");
        new UserService().subInfo(user);
    }
}  new UserService().subInfo(user);
  서비스 층 에 새 UserService 클래스 를 만 들 면 제출 한 데 이 터 를 처리 할 수 있 습 니 다.
public class UserService {
        public void subInfo(User user){
            new UserDao().savaUser(user);
        }
}
  new UserDao().savaUser(user);
  dao 층 에 새 UserDao 클래스 를 만 들 고 방법 에서 데이터베이스 와 데이터 상호작용 을 하 는 데 사용 합 니 다.
    public void savaUser(User user){
        Connection conn = DBConnect.getConn();
        String sql = "insert into user (username,sex,country,photo_file) values(?,?,?,?)";
        PreparedStatement pstmt;
        try {
            pstmt = (PreparedStatement) conn.prepareStatement(sql);
            pstmt.setString(1, user.getUserName());
            pstmt.setString(2, user.getSex());
            pstmt.setString(3, user.getCountry());
            pstmt.setString(4, user.getCountry());
           int i = pstmt.executeUpdate();
         if(i==1){
             System.out.println("    ");
         }else System.out.println("  ");
            pstmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }  DBConnect 클래스:
public class DBConnect {
    public static Connection getConn() {
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/MavenWeb";
        String username = "root";
        String password = "root";
        Connection conn = null;
        try {
            Class.forName(driver); //classLoader,      
            conn = (Connection) DriverManager.getConnection(url, username, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
}
  전체 등 록 된 업무 절 차 는 지금까지 실현 되 었 습 니 다. 주로 프레임 워 크 를 신속하게 구축 하기 위해 기록 하고 작은 tips 도 삽입 되 었 습 니 다. 이번 기록 은 여기까지 입 니 다.
tips:
어떤 게 get 방식 인가요?
form 기본 제출 방식
어떤 게 포스트 방식 인가요?
form 에 method = "post" 를 표시 할 때 ajax 가 post 방식 을 지정 할 때
others
doGet () 또는 doPost () 를 실행 하기 전에 service () 를 먼저 실행 합 니 다.
service () 방법 으로 판단 합 니 다. doGet () 을 호출 해 야 합 니까? doPost () 를 호출 해 야 합 니까?
Serlvet 는 하나의 인 스 턴 스 입 니 다. (init 와 구조 방법 은 한 번 만 실 행 됩 니 다)
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.