Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
212 views

Java Practice

1. The document describes programs to pass information between servlets using cookies, sessions, and JDBC. 2. For cookies, Servlet1 sets cookies and redirects to Servlet2, which reads the cookies to retrieve the passed data. 3. For sessions, Servlet1 stores data in the user's session and redirects to Servlet2, which retrieves the data from the session. 4. For JDBC, Servlet1 authenticates user credentials from a database, and Second.html collects user registration data to save in Servlet2.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
212 views

Java Practice

1. The document describes programs to pass information between servlets using cookies, sessions, and JDBC. 2. For cookies, Servlet1 sets cookies and redirects to Servlet2, which reads the cookies to retrieve the passed data. 3. For sessions, Servlet1 stores data in the user's session and redirects to Servlet2, which retrieves the data from the session. 4. For JDBC, Servlet1 authenticates user credentials from a database, and Second.html collects user registration data to save in Servlet2.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 105

1.

Write a program to pass information through cookie of


stateless protocol.

Servlet1Cookkie.java
import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.Cookie;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet("/Servlet1Cookkie")

public class Servlet1Cookkie extends HttpServlet {

private static final long serialVersionUID = 1L;

public Servlet1Cookkie() {

super();

// TODO Auto-generated constructor stub

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {
// TODO Auto-generated method stub

response.getWriter().append("Served at: ").append(request.getContextPath());

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

PrintWriter out=response.getWriter();

response.setContentType("text/html");

String name=request.getParameter("name");

String branch=request.getParameter("branch");

String reg=request.getParameter("reg");

out.print("Welcome "+name);

Cookie ck=new Cookie("user",name);//creating cookie object

// ck.setMaxAge(0);

response.addCookie(ck);//adding cookie in the response

Cookie ck1=new Cookie("branch",branch);//creating cookie object

response.addCookie(ck1);

out.print("<form action='Servlet2Cokkie' method='post'>");

out.print("<input type='submit' value='Servlet2'>");

// out.print("<input type='submit' value='Go to servlet1'>");

out.print("</form>");

}
Servlet2Cokkie.java

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.Cookie;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

/**

* Servlet implementation class Servlet2Cokkie

*/

@WebServlet("/Servlet2Cokkie")

public class Servlet2Cokkie extends HttpServlet {

private static final long serialVersionUID = 1L;

public Servlet2Cokkie() {

super();

// TODO Auto-generated constructor stub

}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {

PrintWriter out=response.getWriter();

response.setContentType("text/html");

Cookie ck[]=request.getCookies();

out.print("Welcome back "+ck[0].getValue());

out.print("<br> Here is the value stored in cookie:- "+ck[0].getValue()+"<br> here is the name
of the cookie:- "+ck[0].getName()+"<br> get max age of cookie:- "+ck[0].getMaxAge());

// for(int i=0;i<ck.length;i++){

// out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of cookie

// }

Index.jsp

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action='Servlet1 Cokkie' method="post" >


<!-- Servlet1,
//Servlet1Cookkie,Servlet1url,Servlet1Hidden,Servlet1Session-->
Full Name:- <input type="text" name="name" placeholder="enter
your name" required><br><br>
Branch:- <input type="text" name='branch' placeholder='enter your
branch'required><br><br>
Registration number:- <input type='text' name='reg'
placeholder='enter your registration number' required><br><br>
<input type='submit' value="Go to servlet1">
</form>
</body>
</html>

OUTPUT
2. Write a program to pass the data of stateless protocol with
the help of session.

Servlet1Session.java
import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

@WebServlet("/Servlet1Session")

public class Servlet1Session extends HttpServlet {

private static final long serialVersionUID = 1L;

public Servlet1Session() {

super();

// TODO Auto-generated constructor stub

}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {

PrintWriter out=response.getWriter();

response.setContentType("text/html");

String name=request.getParameter("name");

HttpSession session = request.getSession();

session.setAttribute("user", name);

response.sendRedirect("Servlet2Session");

Servlet2Session.java

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;
/**

* Servlet implementation class Servlet2Session

*/

@WebServlet("/Servlet2Session")

public class Servlet2Session extends HttpServlet {

private static final long serialVersionUID = 1L;

public Servlet2Session() {

super();

// TODO Auto-generated constructor stub

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

// TODO Auto-generated method stub

response.setContentType("text/html");

PrintWriter out = response.getWriter();

HttpSession session = request.getSession();

String user = (String)session.getAttribute("user");

out.println("Hello "+user);

out.print("<br>This is servlet 2 page");

session.invalidate();

}
Index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action='Servlet1Session' method="post" >


<!-- Servlet1,
//Servlet1Cookkie,Servlet1url,Servlet1Hidden,Servlet1Session-->
Full Name:- <input type="text" name="name" placeholder="enter
your name" required><br><br>
Branch:- <input type="text" name='branch' placeholder='enter your
branch'required><br><br>
Registration number:- <input type='text' name='reg'
placeholder='enter your registration number' required><br><br>
<input type='submit' value="Go to servlet1">
</form>
</body>
</html>

OUTPUT
3. Write a program to demonstrate the registration using
JDBC architecture.

First.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="Servlet1" method="get">
ID:<input type="text"name="num"/><br><br>
password:<input type="text"name="pwd"/><br><br>

<br><br>
<input type="submit"value="Login">
</form>
<form action="Second.html" method="get">

<input type="submit"value="NEW USER">


</form>
</body>
</html>

Second.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="Servlet2" method="get">
ID:<input type="text"name="num" required ><br><br>
password:<input type="text"name="pwd" required><br><br>
NAME:<input type="text"name="nm" required><br><br>
BRANCH:<input type="text"name="brh" required><br><br>

<br><br>
<input type="submit"value="SAVE">
</form>
</body>
</html>

Servlet1.java

//Through setter method

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.Statement;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

/**
* Servlet implementation class Servlet1

*/

@WebServlet("/Servlet1")

public class Servlet1 extends HttpServlet {

private static final long serialVersionUID = 1L;

Connection con;

Statement stmt;

ResultSet rs;

public Servlet1() {

// TODO Auto-generated constructor stub

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

response.setContentType("text/html");

PrintWriter out= response.getWriter();

String id= request.getParameter("num");

String spass=request.getParameter("pwd");

Connection con = null;

java.sql.Statement stmt = null;

try

Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/my_db", "root", "");

stmt= con.createStatement();

rs=((java.sql.Statement) stmt).executeQuery("Select * from reg where uid=


'"+id+"' and Password='"+spass+"' ");

if(rs.next())

out.println("<h1>WELCOME </h1>" +rs.getString("uid"));

out.println("<form action='First.html' method='get'>");

out.println("<input type='submit'value='BACK'>");

out.println("</form>");

else

out.println("<h1> ID is not exists</h1>"); }

catch(Exception e)

out.println(e);

}
Servlet2.java

import java.io.IOException;

import java.io.PrintWriter;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.Statement;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet("/Servlet2")

public class Servlet2 extends HttpServlet {

private static final long serialVersionUID = 1L;

Connection con;

Statement stmt;

int rs;

public Servlet2() {

// TODO Auto-generated constructor stub

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

response.setContentType("text/html");
PrintWriter out= response.getWriter();

String id= request.getParameter("num");

String pass=request.getParameter("pwd");

String sname=request.getParameter("nm");

String sbranch=request.getParameter("brh");

Connection con = null;

java.sql.Statement stmt = null;

try

Class.forName("com.mysql.jdbc.Driver");

con = DriverManager.getConnection("jdbc:mysql://localhost:3306/my_db", "root", "");

stmt= con.createStatement();

rs= stmt.executeUpdate("INSERT INTO `reg`(`uid`, `Password`, `Name`, `Branch`) VALUES


( '"+id+"' , '"+pass+"','"+sname+"','"+sbranch+"') ");

out.println("<h1>SUCCESFULLY REGISTRED </h1>" );

out.println("<form action='First.html' method='get'>");

out.println("<input type='submit'value='LOGIN'>");

out.println("</form>");
}

catch(Exception e)

out.println(e);

OUTPUT
4. Write a program of registration using MVC architecture

First.jsp
<%@ page language="java" contentType="text/html; charset=ISO-
8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<script>
function validate()
{
var fullname = document.form.fullname.value;
var email = document.form.email.value;
var username = document.form.username.value;
var password = document.form.password.value;
var conpassword= document.form.conpassword.value;

if (fullname==null || fullname=="")
{
alert("Full Name can't be blank");
return false;
}
else if (email==null || email=="")
{
alert("Email can't be blank");
return false;
}
else if (username==null || username=="")
{
alert("Username can't be blank");
return false;
}
else if(password.length<6)
{
alert("Password must be at least 6 characters long.");
return false;
}
else if (password!=conpassword)
{
alert("Confirm Password should match with the Password");
return false;
}
}
</script>
</head>
<body>
<center><h2>Java Registration application using MVC and MySQL
</h2></center>
<form name="form" action="RegisterMVCServlet" method="post"
onsubmit="return validate()">
<table align="center">
<tr>
<td>Full Name</td>
<td><input type="text" name="fullname" /></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" /></td>
</tr>
<tr>
<td>Username</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td>Confirm Password</td>
<td><input type="password" name="conpassword" /></td>
</tr>
<tr>
<td><%=(request.getAttribute("errMessage") == null) ?
"": request.getAttribute("errMessage")%></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Register"></input><input
type="reset" value="Reset"></input></td>
</tr>
</table>
</form></body>
</html>
Register.jsp

<%@ page language="java" contentType="text/html; charset=ISO-


8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<center><h2>Home Page</h2></center>
<b>User Registration Successful</b>
<br></br>
<b>Please <a href="https://cutm.ac.in">log-in</a> to
continue.</b>

</body>
</html>

DBConnection.java
import java.sql.Connection;

import java.sql.DriverManager;

public class DBConnection {

public static Connection createConnection() {

// // TODO Auto-generated method stub

//

// Connection con=null;

// try {

// try {
// Class.forName("com.mysql.jdbc.Driver");

// }

// catch(Exception e)

// {

//// PrintWriter out=getWriter();

// e.printStackTrace();

// }

//
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");

//

// }

// catch(Exception e)

// {

// e.printStackTrace();

// }

// return con;

// }

Connection con = null;

String url = "jdbc:mysql://localhost:3306/test"; //MySQL URL followed by the


database name

String username = "root"; //MySQL username

String password = ""; //MySQL password

System.out.println("In DBConnection.java class ");

try

{
try

Class.forName("com.mysql.jdbc.Driver"); //loading MySQL drivers. This differs for


database servers

catch (ClassNotFoundException e)

e.printStackTrace();

con = DriverManager.getConnection(url, username, password); //attempting to


connect to MySQL database

System.out.println("Printing connection object "+con);

catch (Exception e)

e.printStackTrace();

return con;

RegisterBean.java

public class RegisterBean {


String fullnam;
String usernam;
String pass;
String emi;

public void setFull(String fullname) {


this.fullnam=fullname;
}
public String getFull()
{
return fullnam;
}
public void setEmail(String email) {
this.emi=email;
}
public String getEmail()
{
return emi;
}
public void setUserN(String userName) {
this.usernam=userName;
}
public String getUserN()
{
return usernam;
}

public void setPassW(String password) {


this.pass=password;
}
public String getPassW()
{
return pass;
}

}
RegisterDao.java

import java.sql.Connection;

import java.sql.PreparedStatement;

import java.sql.SQLException;

public class RegisterDao {

public String registerUser(RegisterBean registerSbean) {

String fullname=registerSbean.getFull();

String email=registerSbean.getEmail();

String username=registerSbean.getUserN();

String password=registerSbean.getPassW();

Connection con = null;

PreparedStatement preparedStatement = null;

try

con = DBConnection.createConnection();

String query = "insert into registers(fullName,Email,userName,password) values (?,?,?,?)";


//Insert user details into the table 'USERS'

preparedStatement = con.prepareStatement(query); //Making use of prepared statements here


to insert bunch of data

preparedStatement.setString(1, fullname);

preparedStatement.setString(2, email);
preparedStatement.setString(3, username);

preparedStatement.setString(4, password);

int i= preparedStatement.executeUpdate();

if (i!=0) //Just to ensure data has been inserted into the database

return "SUCCESS";

catch(SQLException e)

e.printStackTrace();

return "Oops.. Something went wrong there..!"; // On failure, send a message from here.

RegisterMVCServlet.java

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

/**

* Servlet implementation class RegisterMVCServlet

*/

@WebServlet("/RegisterMVCServlet")

public class RegisterMVCServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

public RegisterMVCServlet() {

// TODO Auto-generated constructor stub

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

String fullName=request.getParameter("fullname");

String Email=request.getParameter("email");

String UserName=request.getParameter("username");

String Password =request.getParameter("password");

RegisterBean registerSbean =new RegisterBean();

registerSbean.setFull(fullName);

registerSbean.setEmail(Email);

registerSbean.setUserN(UserName);

registerSbean.setPassW(Password);
RegisterDao registerDaoTryl=new RegisterDao();

String userRegistered = registerDaoTryl.registerUser(registerSbean);

if(userRegistered.equals("SUCCESS"))

request.getRequestDispatcher("/Register.jsp").forward(request, response);

else //On Failure, display a meaningful message to the User.

request.setAttribute("errMessage", userRegistered);

request.getRequestDispatcher("/first.jsp").forward(request, response);

}
OUTPUT

5.Write a program to demonstrate the crud operations using


springboot.
Home.jsp
<%@ page language="java" contentType="text/html; charset=ISO-
8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Home page for Login</title>
</head>
<body bgcolor="lightblue">
<table align="center">
<tr>
<td><a href="login.jsp">Login</a></td>
<td><a href="register.jsp">Register</a></td>
</tr>
</table>
</body>
</html>

index.jsp
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>

login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-
8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body bgcolor="lightblue"><center>
<form name="rf" action="./loginprocess" method="post">

Sname<input type=text name="Sname"><br>


Password<input type=text name="Password"><br>

<input type=submit value="Login">


<input type=reset value="Clear">
</form></center>
<a href="Home.jsp">HOME</a>
</body>
</html>
register.jsp
<%@ page language="java" contentType="text/html; charset=ISO-
8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body bgcolor="lightblue"><center>
<form name="rf" action="./registerprocess" method="post">

Regdno<input type=text name="Regdno"><br>


Name<input type=text name="Sname"><br>
UserId<input type=text name="Userid"><br>
Password<input type=text name="Password"><br>
MobileNo<input type=text name="Mobile"><br >

<input type=submit value="Register">


<input type=reset value="Clear">
</form></center>
<a href="Home.jsp">HOME</a>
</body>
</html>

welcome.jsp
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
WELCOME
</body>
</html>
loginController.java

package com.springmvc.controller;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

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

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

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

import org.springframework.web.servlet.ModelAndView;

import com.springmvc.model.Login;

import com.springmvc.model.User;

import com.springmvc.service.userService;

@Controller

public class loginController {

@Autowired

userService userService;

@RequestMapping(value = "/login", method = RequestMethod.GET)


public ModelAndView showLogin(HttpServletRequest request, HttpServletResponse response) {

ModelAndView mav = new ModelAndView("login");

mav.addObject("login", new Login());

return mav;

@RequestMapping(value = "/loginprocess", method = RequestMethod.POST)

public ModelAndView loginProcess(HttpServletRequest request, HttpServletResponse response,

@ModelAttribute("login") Login login) {

ModelAndView mav = null;

User user = userService.validateUser(login);

if (null != user) {

mav = new ModelAndView("welcome");

mav.addObject("Loginname", login.getSname());

else {

mav = new ModelAndView("error");

mav.addObject("message", "Username or Password is wrong!!");

return mav;

}
}

registerController.java
package com.springmvc.controller;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

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

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

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

import org.springframework.web.servlet.ModelAndView;

import com.springmvc.model.User;

import com.springmvc.service.userService;

@Controller

//@RequestMapping("/registerprocess")

public class registerController {

@Autowired

public userService userservice;

@RequestMapping(value="/register",method=RequestMethod.GET)
public ModelAndView doRegister(HttpServletRequest request, HttpServletResponse response)

//String name=request.getParameter("nm");

ModelAndView mv=new ModelAndView("register");

//mv.setViewName("display.jsp");

//return "display.jsp";

mv.addObject("user", new User());

return mv;

@RequestMapping(value="/registerprocess",method=RequestMethod.POST)

public ModelAndView addUser(HttpServletRequest request, HttpServletResponse response,

@ModelAttribute("user") User user )

userservice.register(user);

// String name=request.getParameter("nm");

// ModelAndView mv=new ModelAndView("register");

// mv.setViewName("display.jsp");

return new ModelAndView("NewFile");

}
userDao.java
package com.springmvc.dao;

import com.springmvc.model.Login;

import com.springmvc.model.User;

public interface userDao

void register(User user);

User validateUser(Login login);

userDaoImpl.java
package com.springmvc.dao;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.List;

import javax.sql.DataSource;

//import javax.swing.tree.RowMapper;

import org.springframework.jdbc.core.RowMapper;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.jdbc.core.JdbcTemplate;

import com.springmvc.model.Login;
import com.springmvc.model.User;

public class userDaoImpl implements userDao

@Autowired

DataSource datasource;

@Autowired

JdbcTemplate jdbctemplate;

public void register(User user)

String sql="insert into register values(?,?,?,?,?)";

jdbctemplate.update(sql,new Object[]
{user.getRegdno(),user.getSname(),user.getUserid(),user.getPassword(),user.getMobile()});

public User validateUser(Login login)

String sql="select * from register where Sname='" + login.getSname() + "' and Password='" +
login.getPassword()

+ "'";

List<User> users = jdbctemplate.query(sql, new UserMapper());

return users.size() > 0 ? users.get(0) : null;

class UserMapper implements RowMapper<User>


{

public User mapRow(ResultSet rs,int argl) throws SQLException {

User user=new User();

user.setSname(rs.getString("Sname"));

user.setPassword(rs.getString("Password"));

return user;

Login.java
package com.springmvc.model;

public class Login {


private String regdno;
private String sname;
private String userid;
private String password;
private String mobile;
public String getRegdno() {
return regdno;
}
public void setRegdno(String regdno) {
this.regdno = regdno;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}

User.java
package com.springmvc.model;

public class User {

private String regdno;


private String sname;
private String userid;
private String password;
private String mobile;
public String getRegdno() {
return regdno;
}
public void setRegdno(String regdno) {
this.regdno = regdno;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}

userService.java
package com.springmvc.service;

import com.springmvc.model.Login;

import com.springmvc.model.User;

public interface userService {

void register(User user);

User validateUser(Login login);

userServiceImpl.java

package com.springmvc.service;

import org.springframework.beans.factory.annotation.Autowired;

import com.springmvc.dao.userDao;
import com.springmvc.model.Login;

import com.springmvc.model.User;

public class userServiceImpl implements userService {

@Autowired

userDao userdao;

public void register(User user)

userdao.register(user);

public User validateUser(Login login)

return userdao.validateUser(login);

OUTPUT
6. Write a program of registration and login process using
spring.

Home.jsp
<%@ page language="java" contentType="text/html; charset=ISO-
8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Home page for Login</title>
</head>
<body bgcolor="lightblue">
<table align="center">
<tr>
<td><a href="login.jsp">Login</a></td>
<td><a href="register.jsp">Register</a></td>
</tr>
</table>
</body>
</html>

Index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-


8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Start Learning</title>
<style>
body {
font-family: Arial, Helvetica, sans-serif;
color: rgb(190, 58, 58);
background-color: aquamarine;
}

header h3 {
float: right;
margin-right: 40px;
}

header a {
position: relative;
top: 60px;
left: 80px;
padding: 10px;
border: 1px solid #000;
border-radius: 10px;
width: 100px;
background: rgba(56, 8, 159, 0.8);
color: #fff;
cursor: pointer;
}

.options {
position: absolute;
right: 60px;
top: 120px;
}

.options a {
border: 1px solid #000;
padding: 10px;
text-decoration: none;
margin-right: 10px;
margin-top: -20px;
}

.course {
margin-top: 100px;
}

.docs {
position: absolute;
right: 60px;
bottom: 200px;
}

.docs a {
text-decoration: none;
border: 1px solid #000 !important;
padding: 14px;
color: #fff;
background-color: rgba(56, 8, 159, 0.8);
border-radius: 10px;
}
.main-outline {
height: 41vh;
width: 400px;
background: #000;
position: absolute;
top: 29%;
left: 6%;
border: 1px solid lightgrey;
border-radius: 7px;
}

.inside-container {
margin: 15px;
border: none;
height: 36vh;
}

.base {
height: 11px;
width: 435px;
background: #000;
position: absolute;
top: 69%;
left: 4.8%;
border: 1px solid #101011;
border-bottom-left-radius: 8px;
border-bottom-right-radius: 8px;
}

video {
position: absolute;
bottom: 6%;
right: 4%;
}

.content {
position: absolute;
right: 24%;
top: 28%;
color: #000;
padding: 10px;
}

.content h3 {
text-align: center;
color: orange;
}
</style>
</head>

<body>
<header>
<div>
<h3>By Prof Debendra Maharana</h3>
<a href="video.html">Start Learning</a>
</div>
<div class="options">
<a href="#">Deregister</a>
<a href="student.html">Register</a>
</div>
</header>
<section class="conatainer">
<div class="content">
<h3>About the Course</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing
elit. <br> Adipisci, dolorum. Lorem ipsum dolor sit amet
consectetur adipisicing elit. <br> Excepturi aliquid nobis esse
asperiores inventore <br>temporibus sequi quaerat a doloremque
repellendus.</p>
<p>Lorem ipsum dolor sit amet consectetur adipisicing
elit. <br> Adipisci, dolorum. Lorem ipsum dolor sit amet
consectetur adipisicing elit. <br> Excepturi aliquid nobis esse
asperiores inventore <br>temporibus sequi quaerat a doloremque
repellendus.
<br> Adipisci, dolorum. Lorem ipsum dolor sit
amet consectetur adipisicing elit.</p>

</div>
<div class="docs">
<a href="my_meetings.html">Files</a> <br> <br> <br>
<a href="video.html">Live Session</a>
</div>

<div id="screen">
<div class="main-outline">
<h3 style="text-align: center; color: #fff; font-
family: Arial, Helvetica, sans-serif; ">Intro to our course</h3>
<div class="inside-container">

<video width="367" height="222" controls>


<source src="video.mp4" type="video/mp4">
</video>
</div>
</div>
<div class="base"></div>
</div>
</section>

</body>

</html>

login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-
8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body bgcolor="lightblue"><center>
<form name="rf" action="./loginprocess" method="post">

Sname<input type=text name="Sname"><br>


Password<input type=text name="Password"><br>

<input type=submit value="Login">


<input type=reset value="Clear">
</form></center>
<a href="Home.jsp">HOME</a>
</body>
</html>

register.jsp
<%@ page language="java" contentType="text/html; charset=ISO-
8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body bgcolor="lightblue"><center>
<form name="rf" action="./registerprocess" method="post">

Regdno<input type=text name="Regdno"><br>


Name<input type=text name="Sname"><br>
UserId<input type=text name="Userid"><br>
Password<input type=text name="Password"><br>
MobileNo<input type=text name="Mobile"><br >

<input type=submit value="Register">


<input type=reset value="Clear">
</form></center>
<a href="Home.jsp">HOME</a>
</body>
</html>

welcome.jsp
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
WELCOME
</body>
</html>

loginController.java
package com.springmvc.controller;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

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

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

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

import org.springframework.web.servlet.ModelAndView;

import com.springmvc.model.Login;

import com.springmvc.model.User;

import com.springmvc.service.userService;

@Controller

public class loginController {

@Autowired

userService userService;

@RequestMapping(value = "/login", method = RequestMethod.GET)

public ModelAndView showLogin(HttpServletRequest request, HttpServletResponse response) {

ModelAndView mav = new ModelAndView("login");

mav.addObject("login", new Login());

return mav;

}
@RequestMapping(value = "/loginprocess", method = RequestMethod.POST)

public ModelAndView loginProcess(HttpServletRequest request, HttpServletResponse response,

@ModelAttribute("login") Login login) {

ModelAndView mav = null;

User user = userService.validateUser(login);

if (null != user) {

mav = new ModelAndView("welcome");

mav.addObject("Loginname", login.getSname());

else {

mav = new ModelAndView("error");

mav.addObject("message", "Username or Password is wrong!!");

return mav;

registerController.java
package com.springmvc.controller;
import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

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

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

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

import org.springframework.web.servlet.ModelAndView;

import com.springmvc.model.User;

import com.springmvc.service.userService;

@Controller

//@RequestMapping("/registerprocess")

public class registerController {

@Autowired

public userService userservice;

@RequestMapping(value="/register",method=RequestMethod.GET)

public ModelAndView doRegister(HttpServletRequest request, HttpServletResponse response)

//String name=request.getParameter("nm");

ModelAndView mv=new ModelAndView("register");

//mv.setViewName("display.jsp");
//return "display.jsp";

mv.addObject("user", new User());

return mv;

@RequestMapping(value="/registerprocess",method=RequestMethod.POST)

public ModelAndView addUser(HttpServletRequest request, HttpServletResponse response,

@ModelAttribute("user") User user )

userservice.register(user);

// String name=request.getParameter("nm");

// ModelAndView mv=new ModelAndView("register");

// mv.setViewName("display.jsp");

return new ModelAndView("NewFile");

userDao.java
package com.springmvc.dao;

import com.springmvc.model.Login;

import com.springmvc.model.User;

public interface userDao


{

void register(User user);

User validateUser(Login login);

userDaoImpl.java

package com.springmvc.dao;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.List;

import javax.sql.DataSource;

//import javax.swing.tree.RowMapper;

import org.springframework.jdbc.core.RowMapper;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.jdbc.core.JdbcTemplate;

import com.springmvc.model.Login;

import com.springmvc.model.User;

public class userDaoImpl implements userDao

@Autowired

DataSource datasource;
@Autowired

JdbcTemplate jdbctemplate;

public void register(User user)

String sql="insert into register values(?,?,?,?,?)";

jdbctemplate.update(sql,new Object[]
{user.getRegdno(),user.getSname(),user.getUserid(),user.getPassword(),user.getMobile()});

public User validateUser(Login login)

String sql="select * from register where Sname='" + login.getSname() + "' and Password='" +
login.getPassword()

+ "'";

List<User> users = jdbctemplate.query(sql, new UserMapper());

return users.size() > 0 ? users.get(0) : null;

class UserMapper implements RowMapper<User>

public User mapRow(ResultSet rs,int argl) throws SQLException {

User user=new User();

user.setSname(rs.getString("Sname"));

user.setPassword(rs.getString("Password"));
return user;

Login.java
package com.springmvc.model;

public class Login {


private String regdno;
private String sname;
private String userid;
private String password;
private String mobile;
public String getRegdno() {
return regdno;
}
public void setRegdno(String regdno) {
this.regdno = regdno;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}

}
User.java
package com.springmvc.model;

public class User {

private String regdno;


private String sname;
private String userid;
private String password;
private String mobile;
public String getRegdno() {
return regdno;
}
public void setRegdno(String regdno) {
this.regdno = regdno;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}

}
userService.java

package com.springmvc.service;

import com.springmvc.model.Login;

import com.springmvc.model.User;

public interface userService {

void register(User user);

User validateUser(Login login);

userServiceImpl.java

package com.springmvc.service;

import org.springframework.beans.factory.annotation.Autowired;

import com.springmvc.dao.userDao;

import com.springmvc.model.Login;

import com.springmvc.model.User;
public class userServiceImpl implements userService {

@Autowired

userDao userdao;

public void register(User user)

userdao.register(user);

public User validateUser(Login login)

return userdao.validateUser(login);

OUTPUT
6. Write a program in spring to a message from one java file
to another file with the help of bean xml
Beans.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"
xsi:schemaLocation =
"http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-
3.0.xsd">

<bean id = "helloWorld" class = "HelloWorld">


<property name = "message" value = "Hello World!"/>
</bean>

</beans>

HelloWorld.java
public class HelloWorld {
private String message;

public void setMessage(String message){


this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}

MainApp.java
import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {

public static void main(String[] args) {

ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

HelloWorld obj = (HelloWorld) context.getBean("helloWorld");

obj.getMessage();

OUTPUT
7.Write a program to fetch the information from another file
using xml configuration using interface.

AccountService.java

package AfrConUsInterface;

public interface AccountService {


public void create();
}

App.java
package AfrConUsInterface;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

//Interface came to picture dur tight copling of java files

//as we saw in previous programs that to access other java files

//we have create a object in other file such that we can access that files indirectly by ioc container

//in main only by single object we can access any class

public class App

public static void main( String[] args )

System.out.println( "Hello World!" );


ApplicationContext context=new ClassPathXmlApplicationContext("Bank.xml");

AccountService obj=(AccountService)context.getBean("BankAccount");

obj.create();

CurrentAccount.java
package AfrConUsInterface;

public class CurrentAccount implements AccountService{


public void create()
{
System.out.print("create a current account");
}

SavingAccount.java
package AfrConUsInterface;

public class SavingAccount implements AccountService {

public void create()


{
System.out.print("create a saving account");
}

Bank.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"
xsi:schemaLocation =
"http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-
3.0.xsd">

<bean id = "BankAccount" class =


"AfrConUsInterface.CurrentAccount">

</bean>

</beans>

OUTPUT

8.Write a program of maven project


App.java
package com.mavenConstructer.CountryMaven;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

/**

* Hello world!
*use of constructor to create Deployment Incription

*/

public class App

public static void main( String[] args )

ApplicationContext Context = new ClassPathXmlApplicationContext("ApplicationContext.xml");

Country countryObj = (Country) Context.getBean("CountryBean");

String countryName=countryObj.getCountryName();

String capitalName=countryObj.getCapital().getCapitalName();

System.out.println(capitalName+" is capital of "+countryName);

Captial.java
package com.mavenConstructer.CountryMaven;

public class Capital {


String capitalName;

public String getCapitalName() {


return capitalName;
}

public void setCapitalName(String capitalName) {


this.capitalName = capitalName;
}
}
Country.java
package com.mavenConstructer.CountryMaven;

public class Country {


String countryName;
Capital capital;

public Country(String countryName, Capital capital) {


super();
this.countryName = countryName;
this.capital = capital;
}
public String getCountryName() {
return countryName;
}

public Capital getCapital() {


return capital;
}
}

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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-
3.0.xsd">

<bean id="CountryBean"
class="com.mavenConstructer.CountryMaven.Country">
<constructor-arg index="0" type="java.lang.String"
value="India" />
<constructor-arg index="1" ref="CaptialBean" />
</bean>
<bean id="CaptialBean"
class="com.mavenConstructer.CountryMaven.Capital">
<property name="capitalName" value="Delhi" />
</bean>
</beans>

OUTPUT
9.Write a react program where the props use is done.
App.js
// import logo from './logo.svg';
import './App.css';
// import Props from './Props';
import State from './State';
function App() {
  return (
   
    <div className="App">
    <h1>Hello world</h1>
     {/* <State /> */}
     <Props  name="sravani"/>
    </div>
  );
}

export default App;

Props.js
function Props(props)
{
    return(
    <div>
        <p>
            Iam {props.name}
        </p>
    </div>
    );
}
export default Props;
OUTPUT

10.Write a react program where State is been used.

App.js
// import logo from './logo.svg';
import './App.css';
// import Props from './Props';
import State from './State';
function App() {
  return (
   
    <div className="App">
    <h1>Hello world</h1>
     <State />
     {/* <Props  name="sravani"/> */}
    </div>
  );
}

export default App;

State.js
import React from 'react';
class State extends React.Component{
    constructor(props)
    {
        super(props);
        this.state={
            name:"sravani"
        }
    }
    changeName=()=>{
        this.setState({name:"sravs"});
    }
    render()
    {
        return(
            <div>
                <h1>
                    succfully Register :- {this.state.name}
                </h1>
                <button
                type='button'
                onClick={this.changeName}>
                     Register
                </button>
            </div>
        );
    }
}
export default State;

OUTPUT
11.Write a program of React where forms are used.

Form.js
import React, { Component } from 'react'

class Form extends Component{


    constructor(props)
    {
        super(props)
        this.state={
            username:'',
            comments:'',
            topic:'react'
        }
    }
    handleUsernameChange=(event)=>
    {
          this.setState({
            username:event.target.value
          })
    }
    handleCommentsChange=(event)=>
    {
        this.setState({
            comments:event.target.value
        })
    }
    handleTopicChange=(event)=>
    {
        this.setState({
            topic: event.target.value
        })
    }
    handleSubmit=(event)=>{
alert(`${this.state.username} ${this.state.comments} ${this.state.topic}`)
event.preventDefault();
    }
    render(){
        return(
            <form onSubmit={this.handleSubmit}>
                <div>
                    <label>Username:- </label>
                    <input type="text" value={this.state.username}
                     onChange={this.handleUsernameChange}/>
                </div>
                <div>
                    <label>Comments</label>
                    <input value={this.state.comments}
onChange={this.handleCommentsChange}/>
                </div>
                <div>
                <label>Topic</label>
                <select value={this.state.topic}
onChange={this.handleTopicChange}>
                    <option value="react">React</option>
                    <option value="angular">Angular</option>
                    <option value="vue">Vue</option>
                </select>
                </div>
                <button type='submit'>Submit</button>
            </form>
        )
    }
}
export default Form;

App.js
// import logo from './logo.svg';
import './App.css';
import React, { Component} from 'react'
import Form from './Form'

class App extends Component{


  render(){
    return(
      <div className="App">
           <Form />
      </div>
    )
  }

}
export default App;

OUTPUT

Controller.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"
xsi:schemaLocation =
"http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-
3.0.xsd">

<bean id = "controller" class =


"com.maven2.AssVechicle.HardDisk">

</bean>

</beans>
App.java

package com.maven2.AssVechicle;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

/**

* Hello world!

*/

public class App

public static void main( String[] args )

System.out.println( "Hello World!" );

ApplicationContext context=new ClassPathXmlApplicationContext("Controll.xml");

Computer obj=(Computer)context.getBean("controller");

obj.display();

}
Computer.java

package com.maven2.AssVechicle;

public interface Computer {


public void display();
}

HardDisk.java

package com.maven2.AssVechicle;

public class HardDisk implements Computer {


public void display()
{
System.out.print("Hard disk is of 2 tb");
}
}

Processor.java

package com.maven2.AssVechicle;

public class processor implements Computer {


public void display()
{
System.out.print("This a intel proccesor with 4 slots
");
}
}

Ram.java

package com.maven2.AssVechicle;
public class ram implements Computer {

public void display() {


System.out.print("This is of 8GB ram");
}
}

BASIC MAVEN

App.java

package Basic2.BasicSpring;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

//use of property method, getter and setter method of DI

//use of only single class

//in next need to two create two java classes where one reference will be stored in other ,and that other
referece will be called by app java

/**

*use of setter and getter methods here

* Hello world!

*Basic

*/

public class App

private static ApplicationContext c;


public static void main( String[] args )

System.out.println( "Hello World!" );

c = new ClassPathXmlApplicationContext("Details2.xml");

Student obj=(Student)c.getBean("Stdls");

String StudentAddress=obj.getStudentadress();

System.out.print("Student address "+StudentAddress);

// Country countryObj = (Country) Context.getBean("CountryBean");

// String countryName=countryObj.getCountryName();

// String capitalName=countryObj.getCapital().getCapitalName();

// System.out.println(capitalName+" is capital of "+countryName);

Student.java

package Basic2.BasicSpring;

public class Student {


public String studentname;
public String getStudentname() {
return studentname;
}
public void setStudentname(String studentname) {
this.studentname = studentname;
}
public String studentadress;
public String studentid;
public String studentstd;
public String getStudentadress() {
return studentadress;
}
public void setStudentadress(String studentadress) {
System.out.print("this is student Address "+studentadress);
this.studentadress = studentadress;
}
public String getStudentid() {
return studentid;
}
public void setStudentid(String studentid) {
this.studentid = studentid;
}
public String getStudentstd() {
return studentstd;
}
public void setStudentstd(String studentstd) {
this.studentstd = studentstd;
}

//System.out.print();
//System.out.print("hii Student name"+studentadress+"kvhjy");

Details2.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"
xsi:schemaLocation =
"http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-
3.0.xsd">

<bean id = "Stdls" class = "Basic2.BasicSpring.Student">


<property name="studentadress" value="Gunpur"></property>
<property name="studentid" value="986356"></property>
<property name="studentstd" value="Btech"></property>
</bean>
</beans>
Use of reference in mavaen
App.java

package Basic3.BasicSpring.reference;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

/**

* Hello world!

*Basic

*This program is done by the use of reference

*/

//trying for reference

//next use try with constructor

//next along with interfave

//annotation

//scope

public class App

private static ApplicationContext c;

public static void main( String[] args )

System.out.println( "Hello World!" );


c = new ClassPathXmlApplicationContext("Details3.xml");

Student obj=(Student)c.getBean("StdlsWtFlt");

String StudentAddress=obj.getStudentadress();

System.out.println("Student address "+StudentAddress);

String FacultyName=obj.getFlt().getFltname();

System.out.println("Student's Faculty "+FacultyName);

// Country countryObj = (Country) Context.getBean("CountryBean");

// String countryName=countryObj.getCountryName();

// String capitalName=countryObj.getCapital().getCapitalName();

// System.out.println(capitalName+" is capital of "+countryName);

Faculty.java

package Basic3.BasicSpring.reference;

public class Faculty {


public String fltname;

public String getFltname() {


return fltname;
}

public void setFltname(String fltname) {


this.fltname = fltname;
}

}
Student.java

package Basic3.BasicSpring.reference;

public class Student {


public String studentname;
public Faculty flt;
public String studentadress;
public String studentid;
public String studentstd;

public Faculty getFlt() {


return flt;
}
public void setFlt(Faculty flt) {
this.flt = flt;
}
public String getStudentname() {
return studentname;
}
public void setStudentname(String studentname) {
this.studentname = studentname;
}
public String getStudentadress() {
return studentadress;
}
public void setStudentadress(String studentadress) {
System.out.println("this is student Address
"+studentadress);
this.studentadress = studentadress;
}
public String getStudentid() {
return studentid;
}
public void setStudentid(String studentid) {
this.studentid = studentid;
}
public String getStudentstd() {
return studentstd;
}
public void setStudentstd(String studentstd) {
this.studentstd = studentstd;
}

//System.out.print();
//System.out.print("hii Student name"+studentadress+"kvhjy");

Details3.java

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


<beans xmlns = "http://www.springframework.org/schema/beans"
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-
3.0.xsd">

<bean id = "StdlsWtFlt" class =


"Basic3.BasicSpring.reference.Student">
<property name="studentadress" value="Gunpur"></property>
<property name="studentid" value="986356"></property>
<property name="studentstd" value="Btech"></property>
<property name="flt" ref="Faculty"></property>
</bean>
<bean id="Faculty"
class="Basic3.BasicSpring.reference.Faculty">
<property name="fltname" value="Debendra sir"></property>

</bean>
</beans>

Use of Constructor

App.java

package Basic4.constuctor;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;
//use of property method, getter and setter method of DI

//use of only single class

//in next need to two create two java classes where one reference will be stored in other ,and that other
referece will be called by app java

/**

* Hello world!

*Basic

*/

public class App

private static ApplicationContext c;

public static void main( String[] args )

ApplicationContext c=new ClassPathXmlApplicationContext("Config.xml");

Person person=(Person)c.getBean("person");

System.out.print(person);

Person.java

package Basic4.constuctor;

public class Person {


private String name;
private int personid;
public Person(String name,int personid)
{
this.name=name;
this.personid=personid;

System.out.println("person name = "+name+" id :-"+personid);


}
}

Config.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"
xsi:schemaLocation =
"http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-
3.0.xsd">
<bean class="Basic4.constuctor.Person" name="person">
<constructor-arg value="sravani" />
<constructor-arg value="235" type="int"/>
</bean>
</beans>

Constructor Using Reference


App.java
package Basic4.constuctor.reference;

import org.springframework.context.ApplicationContext;

import
org.springframework.context.support.ClassPathXmlApplicationContex
t;

//use of property method, getter and setter method of DI


//use of only single class

//in next need to two create two java classes where one reference
will be stored in other ,and that other referece will be called
by app java

/**

* Hello world!

*Basic

*Country Maven also same example

*/

public class App

private static ApplicationContext c;

public static void main( String[] args )

ApplicationContext c=new
ClassPathXmlApplicationContext("BasicSpring.src.main.java.ConfigC
onsrt.xml.xml");

Person person=(Person)c.getBean("person");

System.out.print(person);

Certificate.java

package Basic4.constuctor.reference;

public class Certifice {


private String uname;
public String getUname() {
return uname;
}

public void setUname(String uname) {


this.uname = uname;
System.out.print(" uname:- "+this.uname);

Person.java

package Basic4.constuctor.reference;

public class Person {


private String name;
private int personid;
private Certifice certi;
public Person(String name,int personid,Certifice certi)
{
this.name=name;
this.personid=personid;
this.certi=certi;
System.out.println("person name = "+name+" id :-"+personid);
}
}

configConsrt.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"
xsi:schemaLocation =
"http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-
3.0.xsd">

<bean class="Basic4.constuctor.reference.Certifice" id="cer">


<constructor-arg value="Android using java "/>
</bean>
<bean class="Basic4.constuctor.reference.Person" id="person">
<constructor-arg value="sravani" />
<constructor-arg value="235" type="int"/>
<constructor-arg ref="cer"/>
</bean>
</beans>

Configure Using java class

App.java
package AftrWithoutUsingXml;

import org.springframework.context.ApplicationContext;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**

* Here without using the xml file only using the bean tag creating the objectint for Di

* Hello world!

*/

public class App

public static void main(String[] args) {

// TODO Auto-generated method stub


ApplicationContext context =new
AnnotationConfigApplicationContext(CompConfig.class);

Computer c=context.getBean(Computer.class);

c.config();

Compconfig.java

package AftrWithoutUsingXml;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

@Configuration

public class CompConfig {

@Bean

public Computer getComp() {

return new Computer();

@Bean

public Samsung getMob() {

return new Samsung();

}
Computer.java

package AftrWithoutUsingXml;

public class Computer {


public void config() {
System.out.print("Core i7 Processor , 1gb");
}

Samsung.java
package AftrWithoutUsingXml;

public class Samsung {


public void config() {
System.out.print("Core i7 Samsong Processor , 1gb");
}
}

//JAVA file

package AftrWithoutUsingXml;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

@Configuration

public class CompConfig {

@Bean
public Computer getComp() {

return new Computer();

@Bean

public Samsung getMob() {

return new Samsung();

MICROSERVICES-MVC

Login microservices

package com.Springboot.mvc;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class LginMicroserviceMvcApplication {

public static void main(String[] args) {

SpringApplication.run(LginMicroserviceMvcApplication.class, args);

loginController.java

package com.Springboot.mvc.controller;

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 org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.client.RestTemplate;

import com.Springboot.mvc.model.User;

import com.Springboot.mvc.model.UserRepo;

@Controller
public class loginController {

@Autowired

private UserRepo userRepo;

RestTemplate restTemplate=new RestTemplate();

@RequestMapping("/")

public String checkMVC()

return "login";

@RequestMapping("/records")

public String goToRecordMicroservice(Model model)

System.out.println("going to show records page from login microservices");

restTemplate.getForObject("http://localhost:8082/records"

,String.class);

model.addAttribute("Thank you");

return "all";

@RequestMapping("/login")

public String login(@RequestParam("username") String userName, @RequestParam("password")String password,Model model)

//to send data to home page model is used

User u=null;
try {

u=userRepo.findByName(userName);

catch(Exception e){

System.out.println("User not found!!");

if(u!=null)

model.addAttribute("UserName",userName);

return "home";

model.addAttribute("error","user not found ,kindly register!!");

return "login";}

@RequestMapping("/register")

public String goToRegisterationPage()

return "register";

@RequestMapping("/set-user")

public String goToRegisterationMicroservice(@RequestParam("username")String userName, @RequestParam("password1")


String password1,

@RequestParam("password2") String password2,Model model)

System.out.println("going to regestration page from login microservices");

if(password1.equals(password2))

restTemplate.getForObject("http://localhost:8081/register-user/"+userName+"/"+password2
,String.class);

model.addAttribute("registrationSuccess","succesfuly done, kindly login");

else {

model.addAttribute("registerError","password is not same");

//code to register

return "login";

@RequestMapping("/delete")

@ResponseBody

public String delete(@RequestParam("id") int id)

//System.out.println("deleted Successfully");

restTemplate.getForObject("http://localhost:8082/delete/"+id, String.class);

//System.out.println("deleted Successfully");

return "deleted successfully";

@RequestMapping("/update")

@ResponseBody

public String update(@RequestParam("id") String id,@RequestParam("name") String name,@RequestParam("password") String


password,Model model)

restTemplate.getForObject("http://localhost:8082/update/"+id+"/"+name+"/"+password, String.class);

model.addAttribute("updated successfullly");
return "updated successfully.";

//@RequestMapping("/set-user")

//public String goToRegisterMicroservice(){

// return "login";

//

//}

User.java

package com.Springboot.mvc.model;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

@Entity//marks class class should be maped in database

public class User {

@Id//id is a primary key

@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;

private String name;

private String password;

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

super();

this.id = id;

this.name = name;

this.password = password;

public int getId() {

return id;

public void setId(int id) {

this.id = id;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public String getPassword() {

return password;

public void setPassword(String password) {

this.password = password;

public User() {

super();
// TODO Auto-generated constructor stub

UserRepo.java

package com.Springboot.mvc.model;

import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepo extends JpaRepository<User,Integer> {

User findByName(String userName);

all.jsp

<%@ page language="java" contentType="text/html; charset=ISO-


8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<%@ taglib prefix="spring"
uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html lang="en">
<head>

<link rel="stylesheet" type="text/css"


href="webjars/bootstrap/3.3.7/css/bootstrap.min.css" />
</head>
<body>
<div class="container">
<header>
</header>
<div class="starter-template">
<h1>Users List</h1>
<table
class="table table-striped table-hover table-condensed table-
bordered">
<tr>
<th>Id</th>
<th>Name</th>
<th>Password</th>

</tr>
<c:forEach var="user" items="${user}">
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.password}</td>
</tr>
</c:forEach>
</table>
</div>

</div>

<script type="text/javascript"
src="webjars/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>

</html>

Home.jsp

<html>
<head>
</head>
<body>
<h1>Welcome to Home page ${UserName}</h1>
<br>
<br>
<h3>UPDATE RECORD</h3>

<form action="update" method="post">


id :<input type="text" name="id"><br>
username:<input type="text" name="name"><br>
password :<input type="text" name="password"><br>
<input type="submit"><br>

</form>

<br><br>
<h3>DELETE RECORD</h3>
<form action="delete" method="post">
ID :<input type="text" name="id"><br>
<input type="submit"><br>
</form>
</body>
</html>

Login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-
8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div>
<h1> Login </h1>
<form action="/login" method="post">

<div>
<div>Username: <input type="text" name="username" value=""></div>
<br><br>
<c:if test="$(not empty error)">
<div><h5>${error}</h5></div>
</c:if>
<c:if test="$(not empty registrationSuccess)">
<div><h5>${registrationSuccess}</h5></div>
</c:if>
<c:if test="$(not empty registerError)">
<div><h5>${registerError}</h5></div>
</c:if>
<div>Password: <input type="text" name="password" value=""></div>
<div><input type="submit" value="login"></div>
<div><input type="button" value="Register"
onclick="goToRegister()"></div>
<div><input type="button" value="Show Records"
onclick="goToAll()"></div>
</div>
</form>
</div>
<script type="text/javascript">
function goToRegister()
{
alert("going to registration page ");
window.location.href="/register";
}
</script>
<script type="text/javascript">
function goToAll()
{
alert("going to records page ");
window.location.href="/records";
}
</script>

</body>
</html>

Register.jsp

<%@ page language="java" contentType="text/html; charset=ISO-


8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div>
<h1>Register Form</h1>
<form action="/set-user" method="post">

<div>
<div>Username: <input type="text" name="username" value=""></div>
<br><br>
<div>Password: <input type="text" name="password1"
value=""></div>

<div>retype Password: <input type="text" name="password2"


value=""></div>
<div><input type="submit" value="Register"
onclick="goToRegister()"></div>
</div>
</form>
</div>
welcome to registration page
</body>
</html>

Pom.xml

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


<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>lgin-microservice-mvc</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>lgin-microservice-mvc</name>
<description>login-mvc</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-
jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-
services</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.7</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-
plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

Application properties

spring.datasource.url=jdbc:mysql://localhost:3306/micro
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=
spring.jpa.ddl-auto=update
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MyS
QL5InnoDBDialect
server.port=8080
spring.mvc.view.prefix=/view/
spring.mvc.view.suffix=.jsp
spring.mvc.static-path-pattern=/resource/**

Registermicroservices
package com.Springboot.mvc;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class RegisterMicroserviceMvc1Application {

public static void main(String[] args) {

SpringApplication.run(RegisterMicroserviceMvc1Application.class, args);

RegisterController.java
package com.Springboot.mvc.controller;

import org.springframework.beans.factory.annotation.Autowired;

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

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

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

import com.Springboot.mvc.model.User;
import com.Springboot.mvc.model.UserRepo;

@RestController

public class RegistrationController {

@Autowired

private UserRepo userRepo;

@RequestMapping("/check")

public String regitercheck()

{ return " check registered ";

@RequestMapping("/register-user/{userName}/{password}")

public String regiterUser(@PathVariable("userName") String


userName,@PathVariable("password")String password )

User u=new User();

u.setId(2);

u.setId(12);

u.setName(userName);

u.setPassword(password);

userRepo.save(u);

System.out.println("====going to regestration from login microservices end");

return "registered Succesufull"+userName;

}
}

User.java

package com.Springboot.mvc.model;

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

@Entity//marks class class should be maped in database

public class User {

@Id//id is a primary key

@GeneratedValue(strategy=GenerationType.IDENTITY)

private int id;

private String name;

private String password;

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

super();

this.id = id;

this.name = name;

this.password = password;

public int getId() {

return id;
}

public void setId(int id) {

this.id = id;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public String getPassword() {

return password;

public void setPassword(String password) {

this.password = password;

public User() {

super();

// TODO Auto-generated constructor stub

}
UserRepo.java
package com.Springboot.mvc.model;

import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepo extends JpaRepository<User,Integer> {

User findByName(String userName);

Application-properties
spring.datasource.url=jdbc:mysql://localhost:3306/micro?
useSSL=false
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MyS
QL5InnoDBDialect
server.port=8081

You might also like